From b00e35dc173e18f47ed32cdb2097ad69c758da0a Mon Sep 17 00:00:00 2001 From: 502647092 Date: Fri, 15 Jan 2016 00:05:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=20=E4=BF=AE=E5=A4=8D=E5=95=86=E5=BA=97=E5=88=9B=E5=BB=BABUG(7?= =?UTF-8?q?=E8=80=81=E6=9D=BF)...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 502647092 --- .../QuickShop/Command/CommandBuy.java | 50 +- .../QuickShop/Command/CommandClean.java | 62 +- .../QuickShop/Command/CommandEmpty.java | 54 +- .../QuickShop/Command/CommandExport.java | 116 +- .../QuickShop/Command/CommandFind.java | 170 +-- .../QuickShop/Command/CommandInfo.java | 82 +- .../QuickShop/Command/CommandPrice.java | 160 +- .../QuickShop/Command/CommandRefill.java | 62 +- .../QuickShop/Command/CommandReload.java | 30 +- .../QuickShop/Command/CommandRemove.java | 54 +- .../QuickShop/Command/CommandSell.java | 50 +- .../QuickShop/Command/CommandSetOwner.java | 50 +- .../QuickShop/Command/CommandUnlimited.java | 48 +- .../QuickShop/Command/QuickShopCommands.java | 48 +- .../QuickShop/Config/ConfigManager.java | 334 ++--- .../QuickShop/Database/BufferStatement.java | 122 +- .../maxgamer/QuickShop/Database/Database.java | 356 ++--- .../QuickShop/Database/DatabaseCore.java | 8 +- .../QuickShop/Database/DatabaseHelper.java | 103 +- .../QuickShop/Database/MySQLCore.java | 138 +- .../QuickShop/Database/SQLiteCore.java | 184 +-- .../maxgamer/QuickShop/Economy/Economy.java | 222 +-- .../QuickShop/Economy/EconomyCore.java | 208 +-- .../QuickShop/Economy/Economy_Vault.java | 182 +-- .../QuickShop/Listeners/BlockListener.java | 182 +-- .../QuickShop/Listeners/ChatListener.java | 24 +- .../QuickShop/Listeners/ChunkListener.java | 52 +- .../QuickShop/Listeners/LockListener.java | 248 ++-- .../QuickShop/Listeners/PlayerListener.java | 324 ++-- .../QuickShop/Listeners/ProtectListener.java | 248 ++-- .../QuickShop/Listeners/WorldListener.java | 126 +- .../org/maxgamer/QuickShop/QuickShop.java | 634 ++++---- .../QuickShop/Shop/ContainerShop.java | 1300 ++++++++--------- .../maxgamer/QuickShop/Shop/DisplayItem.java | 56 +- .../org/maxgamer/QuickShop/Shop/FakeItem.java | 360 ++--- .../org/maxgamer/QuickShop/Shop/Info.java | 164 +-- .../maxgamer/QuickShop/Shop/NormalItem.java | 186 +-- .../org/maxgamer/QuickShop/Shop/Shop.java | 66 +- .../maxgamer/QuickShop/Shop/ShopAction.java | 4 +- .../maxgamer/QuickShop/Shop/ShopChunk.java | 66 +- .../QuickShop/Shop/ShopCreateEvent.java | 78 +- .../maxgamer/QuickShop/Shop/ShopManager.java | 1136 +++++++------- .../QuickShop/Shop/ShopPreCreateEvent.java | 78 +- .../QuickShop/Shop/ShopPurchaseEvent.java | 118 +- .../org/maxgamer/QuickShop/Shop/ShopType.java | 42 +- .../org/maxgamer/QuickShop/Util/MarkUtil.java | 28 +- .../org/maxgamer/QuickShop/Util/MsgUtil.java | 352 ++--- .../java/org/maxgamer/QuickShop/Util/NMS.java | 14 +- .../org/maxgamer/QuickShop/Util/Util.java | 968 ++++++------ .../QuickShop/Watcher/ItemWatcher.java | 60 +- .../QuickShop/Watcher/LogWatcher.java | 72 +- 51 files changed, 4943 insertions(+), 4936 deletions(-) diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandBuy.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandBuy.java index 88c4f42..52cf178 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandBuy.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandBuy.java @@ -14,32 +14,32 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandBuy extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandBuy(final QuickShop plugin) { - super("b"); - this.plugin = plugin; - setOnlyPlayerExecutable(); - setPermission("quickshop.create.buy"); - setDescription(MsgUtil.p("command.description.buy")); - } + public CommandBuy(final QuickShop plugin) { + super("b"); + this.plugin = plugin; + setOnlyPlayerExecutable(); + setPermission("quickshop.create.buy"); + setDescription(MsgUtil.p("command.description.buy")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null && shop.getOwner().equals(((Player) sender).getName())) { - shop.setShopType(ShopType.BUYING); - shop.setSignText(); - shop.update(); - sender.sendMessage(MsgUtil.p("command.now-buying", shop.getDataName())); - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null && shop.getOwner().equals(((Player) sender).getName())) { + shop.setShopType(ShopType.BUYING); + shop.setSignText(); + shop.update(); + sender.sendMessage(MsgUtil.p("command.now-buying", shop.getDataName())); + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandClean.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandClean.java index e0be0fb..7a69fca 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandClean.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandClean.java @@ -13,37 +13,37 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandClean extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandClean(final QuickShop plugin) { - super("c"); - this.plugin = plugin; - setPermission("quickshop.clean"); - setDescription(MsgUtil.p("command.description.clean")); - } + public CommandClean(final QuickShop plugin) { + super("c"); + this.plugin = plugin; + setPermission("quickshop.clean"); + setDescription(MsgUtil.p("command.description.clean")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - sender.sendMessage(MsgUtil.p("command.cleaning")); - final Iterator shIt = plugin.getShopManager().getShopIterator(); - int i = 0; - while (shIt.hasNext()) { - final Shop shop = shIt.next(); - try { - if (shop.getLocation().getWorld() != null && shop.isSelling() && shop.getRemainingStock() == 0 && shop instanceof ContainerShop) { - final ContainerShop cs = (ContainerShop) shop; - if (cs.isDoubleShop()) { - continue; - } - shIt.remove(); // Is selling, but has no stock, and is a chest shop, but is not a double shop. Can be deleted safely. - i++; - } - } catch (final IllegalStateException e) { - // shIt.remove(); // The shop is not there anymore, remove it - } - } - MsgUtil.clean(); - sender.sendMessage(MsgUtil.p("command.cleaned", "" + i)); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + sender.sendMessage(MsgUtil.p("command.cleaning")); + final Iterator shIt = plugin.getShopManager().getShopIterator(); + int i = 0; + while (shIt.hasNext()) { + final Shop shop = shIt.next(); + try { + if (shop.getLocation().getWorld() != null && shop.isSelling() && shop.getRemainingStock() == 0 && shop instanceof ContainerShop) { + final ContainerShop cs = (ContainerShop) shop; + if (cs.isDoubleShop()) { + continue; + } + shIt.remove(); // Is selling, but has no stock, and is a chest shop, but is not a double shop. Can be deleted safely. + i++; + } + } catch (final IllegalStateException e) { + // shIt.remove(); // The shop is not there anymore, remove it + } + } + MsgUtil.clean(); + sender.sendMessage(MsgUtil.p("command.cleaned", "" + i)); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandEmpty.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandEmpty.java index ad5c1ec..b97a873 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandEmpty.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandEmpty.java @@ -14,33 +14,33 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandEmpty extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandEmpty(final QuickShop plugin) { - super("e"); - this.plugin = plugin; - setPermission("quickshop.empty"); - setDescription(MsgUtil.p("command.description.empty")); - } + public CommandEmpty(final QuickShop plugin) { + super("e"); + this.plugin = plugin; + setPermission("quickshop.empty"); + setDescription(MsgUtil.p("command.description.empty")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if (shop instanceof ContainerShop) { - final ContainerShop cs = (ContainerShop) shop; - cs.getInventory().clear(); - sender.sendMessage(MsgUtil.p("empty-success")); - } else { - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - } - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if (shop instanceof ContainerShop) { + final ContainerShop cs = (ContainerShop) shop; + cs.getInventory().clear(); + sender.sendMessage(MsgUtil.p("empty-success")); + } else { + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + } + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandExport.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandExport.java index fc2c7f3..2c66912 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandExport.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandExport.java @@ -16,64 +16,64 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandExport extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandExport(final QuickShop plugin) { - super("export"); - this.plugin = plugin; - setPermission("quickshop.export"); - setMinimumArguments(1); - setPossibleArguments("[mysql|sqlite]"); - setDescription(MsgUtil.p("command.description.export")); - } + public CommandExport(final QuickShop plugin) { + super("export"); + this.plugin = plugin; + setPermission("quickshop.export"); + setMinimumArguments(1); + setPossibleArguments("[mysql|sqlite]"); + setDescription(MsgUtil.p("command.description.export")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final String type = args[0].toLowerCase(); - if (type.startsWith("mysql")) { - if (plugin.getDB().getCore() instanceof MySQLCore) { - sender.sendMessage(ChatColor.RED + "数据已保存在 MySQL 无需转换!"); - return; - } - final ConfigurationSection cfg = plugin.getConfig().getConfigurationSection("database"); - final String host = cfg.getString("host"); - final String port = cfg.getString("port"); - final String user = cfg.getString("user"); - final String pass = cfg.getString("password"); - final String name = cfg.getString("database"); - final MySQLCore core = new MySQLCore(host, user, pass, name, port); - Database target; - try { - target = new Database(core); - QuickShop.instance.getDB().copyTo(target); - sender.sendMessage(ChatColor.GREEN + "导出成功 - 数据已保存至 MySQL " + user + "@" + host + "." + name); - } catch (final Exception e) { - e.printStackTrace(); - sender.sendMessage(ChatColor.RED + "导出数据到 MySQL 失败 " + user + "@" + host + "." + name + ChatColor.DARK_RED + " 由于: " + e.getMessage()); - } - return; - } - if (type.startsWith("sql") || type.contains("file")) { - if (plugin.getDB().getCore() instanceof SQLiteCore) { - sender.sendMessage(ChatColor.RED + "数据已保存在 SQLite 无需转换!"); - return; - } - final File file = new File(plugin.getDataFolder(), "shops.db"); - if (file.exists()) { - if (file.delete() == false) { - sender.sendMessage(ChatColor.RED + "警告: 删除旧的数据文件 shops.db 失败. 可能会导致部分信息错误."); - } - } - final SQLiteCore core = new SQLiteCore(file); - try { - final Database target = new Database(core); - QuickShop.instance.getDB().copyTo(target); - sender.sendMessage(ChatColor.GREEN + "导出成功 - 数据已保存至 SQLite: " + file.toString()); - } catch (final Exception e) { - e.printStackTrace(); - sender.sendMessage(ChatColor.RED + "导出数据到 SQLite: " + file.toString() + " 失败 由于: " + e.getMessage()); - } - return; - } - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final String type = args[0].toLowerCase(); + if (type.startsWith("mysql")) { + if (plugin.getDB().getCore() instanceof MySQLCore) { + sender.sendMessage(ChatColor.RED + "数据已保存在 MySQL 无需转换!"); + return; + } + final ConfigurationSection cfg = plugin.getConfig().getConfigurationSection("database"); + final String host = cfg.getString("host"); + final String port = cfg.getString("port"); + final String user = cfg.getString("user"); + final String pass = cfg.getString("password"); + final String name = cfg.getString("database"); + final MySQLCore core = new MySQLCore(host, user, pass, name, port); + Database target; + try { + target = new Database(core); + QuickShop.instance.getDB().copyTo(target); + sender.sendMessage(ChatColor.GREEN + "导出成功 - 数据已保存至 MySQL " + user + "@" + host + "." + name); + } catch (final Exception e) { + e.printStackTrace(); + sender.sendMessage(ChatColor.RED + "导出数据到 MySQL 失败 " + user + "@" + host + "." + name + ChatColor.DARK_RED + " 由于: " + e.getMessage()); + } + return; + } + if (type.startsWith("sql") || type.contains("file")) { + if (plugin.getDB().getCore() instanceof SQLiteCore) { + sender.sendMessage(ChatColor.RED + "数据已保存在 SQLite 无需转换!"); + return; + } + final File file = new File(plugin.getDataFolder(), "shops.db"); + if (file.exists()) { + if (file.delete() == false) { + sender.sendMessage(ChatColor.RED + "警告: 删除旧的数据文件 shops.db 失败. 可能会导致部分信息错误."); + } + } + final SQLiteCore core = new SQLiteCore(file); + try { + final Database target = new Database(core); + QuickShop.instance.getDB().copyTo(target); + sender.sendMessage(ChatColor.GREEN + "导出成功 - 数据已保存至 SQLite: " + file.toString()); + } catch (final Exception e) { + e.printStackTrace(); + sender.sendMessage(ChatColor.RED + "导出数据到 SQLite: " + file.toString() + " 失败 由于: " + e.getMessage()); + } + return; + } + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandFind.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandFind.java index fe79a89..296920e 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandFind.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandFind.java @@ -17,92 +17,92 @@ import cn.citycraft.PluginHelper.commands.BaseCommand; import cn.citycraft.PluginHelper.utils.StringUtil; public class CommandFind extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandFind(final QuickShop plugin) { - super("f"); - this.plugin = plugin; - setMinimumArguments(2); - setOnlyPlayerExecutable(); - setPermission("quickshop.find"); - setDescription(MsgUtil.p("command.description.find")); - } + public CommandFind(final QuickShop plugin) { + super("f"); + this.plugin = plugin; + setMinimumArguments(2); + setOnlyPlayerExecutable(); + setPermission("quickshop.find"); + setDescription(MsgUtil.p("command.description.find")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - String lookFor = StringUtil.consolidateStrings(args, 0); - lookFor = lookFor.toLowerCase(); - final Player p = (Player) sender; - final Location loc = p.getEyeLocation().clone(); - final double minDistance = plugin.getConfig().getInt("shop.find-distance"); - double minDistanceSquared = minDistance * minDistance; - final int chunkRadius = (int) minDistance / 16 + 1; - Shop closest = null; - final Chunk c = loc.getChunk(); - for (int x = -chunkRadius + c.getX(); x < chunkRadius + c.getX(); x++) { - for (int z = -chunkRadius + c.getZ(); z < chunkRadius + c.getZ(); z++) { - final Chunk d = c.getWorld().getChunkAt(x, z); - final HashMap inChunk = plugin.getShopManager().getShops(d); - if (inChunk == null) { - continue; - } - for (final Shop shop : inChunk.values()) { - if (shop.getDataName().toLowerCase().contains(lookFor) && shop.getLocation().distanceSquared(loc) < minDistanceSquared) { - closest = shop; - minDistanceSquared = shop.getLocation().distanceSquared(loc); - } - } - } - } - if (closest == null) { - sender.sendMessage(MsgUtil.p("no-nearby-shop", args[0])); - return; - } - final Location lookat = closest.getLocation().clone().add(0.5, 0.5, 0.5); - // Hack fix to make /qs find not used by /back - p.teleport(this.lookAt(loc, lookat).add(0, -1.62, 0), TeleportCause.PLUGIN); - p.sendMessage(MsgUtil.p("nearby-shop-this-way", "" + (int) Math.floor(Math.sqrt(minDistanceSquared)))); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + String lookFor = StringUtil.consolidateStrings(args, 0); + lookFor = lookFor.toLowerCase(); + final Player p = (Player) sender; + final Location loc = p.getEyeLocation().clone(); + final double minDistance = plugin.getConfig().getInt("shop.find-distance"); + double minDistanceSquared = minDistance * minDistance; + final int chunkRadius = (int) minDistance / 16 + 1; + Shop closest = null; + final Chunk c = loc.getChunk(); + for (int x = -chunkRadius + c.getX(); x < chunkRadius + c.getX(); x++) { + for (int z = -chunkRadius + c.getZ(); z < chunkRadius + c.getZ(); z++) { + final Chunk d = c.getWorld().getChunkAt(x, z); + final HashMap inChunk = plugin.getShopManager().getShops(d); + if (inChunk == null) { + continue; + } + for (final Shop shop : inChunk.values()) { + if (shop.getDataName().toLowerCase().contains(lookFor) && shop.getLocation().distanceSquared(loc) < minDistanceSquared) { + closest = shop; + minDistanceSquared = shop.getLocation().distanceSquared(loc); + } + } + } + } + if (closest == null) { + sender.sendMessage(MsgUtil.p("no-nearby-shop", args[0])); + return; + } + final Location lookat = closest.getLocation().clone().add(0.5, 0.5, 0.5); + // Hack fix to make /qs find not used by /back + p.teleport(this.lookAt(loc, lookat).add(0, -1.62, 0), TeleportCause.PLUGIN); + p.sendMessage(MsgUtil.p("nearby-shop-this-way", "" + (int) Math.floor(Math.sqrt(minDistanceSquared)))); + return; + } - /** - * Returns loc with modified pitch/yaw angles so it faces lookat - * - * @param loc - * The location a players head is - * @param lookat - * The location they should be looking - * @return The location the player should be facing to have their crosshairs - * on the location lookAt Kudos to bergerkiller for most of this - * function - */ - public Location lookAt(Location loc, final Location lookat) { - // Clone the loc to prevent applied changes to the input loc - loc = loc.clone(); - // Values of change in distance (make it relative) - final double dx = lookat.getX() - loc.getX(); - final double dy = lookat.getY() - loc.getY(); - final double dz = lookat.getZ() - loc.getZ(); - // Set yaw - if (dx != 0) { - // Set yaw start value based on dx - if (dx < 0) { - loc.setYaw((float) (1.5 * Math.PI)); - } else { - loc.setYaw((float) (0.5 * Math.PI)); - } - loc.setYaw(loc.getYaw() - (float) Math.atan(dz / dx)); - } else if (dz < 0) { - loc.setYaw((float) Math.PI); - } - // Get the distance from dx/dz - final double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); - final float pitch = (float) -Math.atan(dy / dxz); - // Set values, convert to degrees - // Minecraft yaw (vertical) angles are inverted (negative) - loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI + 360); - // But pitch angles are normal - loc.setPitch(pitch * 180f / (float) Math.PI); - return loc; - } + /** + * Returns loc with modified pitch/yaw angles so it faces lookat + * + * @param loc + * The location a players head is + * @param lookat + * The location they should be looking + * @return The location the player should be facing to have their crosshairs + * on the location lookAt Kudos to bergerkiller for most of this + * function + */ + public Location lookAt(Location loc, final Location lookat) { + // Clone the loc to prevent applied changes to the input loc + loc = loc.clone(); + // Values of change in distance (make it relative) + final double dx = lookat.getX() - loc.getX(); + final double dy = lookat.getY() - loc.getY(); + final double dz = lookat.getZ() - loc.getZ(); + // Set yaw + if (dx != 0) { + // Set yaw start value based on dx + if (dx < 0) { + loc.setYaw((float) (1.5 * Math.PI)); + } else { + loc.setYaw((float) (0.5 * Math.PI)); + } + loc.setYaw(loc.getYaw() - (float) Math.atan(dz / dx)); + } else if (dz < 0) { + loc.setYaw((float) Math.PI); + } + // Get the distance from dx/dz + final double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); + final float pitch = (float) -Math.atan(dy / dxz); + // Set values, convert to degrees + // Minecraft yaw (vertical) angles are inverted (negative) + loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI + 360); + // But pitch angles are normal + loc.setPitch(pitch * 180f / (float) Math.PI); + return loc; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandInfo.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandInfo.java index ea83ede..5610a61 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandInfo.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandInfo.java @@ -16,47 +16,47 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandInfo extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandInfo(final QuickShop plugin) { - super("i"); - this.plugin = plugin; - setPermission("quickshop.info"); - setDescription(MsgUtil.p("command.description.info")); - } + public CommandInfo(final QuickShop plugin) { + super("i"); + this.plugin = plugin; + setPermission("quickshop.info"); + setDescription(MsgUtil.p("command.description.info")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - int buying, selling, doubles, chunks, worlds, unlimited; - buying = selling = doubles = chunks = worlds = unlimited = 0; - int nostock = 0; - sender.sendMessage(ChatColor.RED + "开始检索商店信息中..."); - for (final HashMap> inWorld : plugin.getShopManager().getShops().values()) { - worlds++; - for (final HashMap inChunk : inWorld.values()) { - chunks++; - for (final Shop shop : inChunk.values()) { - if (shop.isUnlimited()) { - unlimited++; - } - if (shop.isBuying()) { - buying++; - } else if (shop.isSelling()) { - selling++; - } - if (shop instanceof ContainerShop && ((ContainerShop) shop).isDoubleShop()) { - doubles++; - } else if (shop.isSelling() && shop.getRemainingStock() == 0) { - nostock++; - } - } - } - } - sender.sendMessage(MsgUtil.p("info.title", chunks, buying + selling, worlds)); - sender.sendMessage(MsgUtil.p("info.selling", selling)); - sender.sendMessage(MsgUtil.p("info.buying", buying)); - sender.sendMessage(MsgUtil.p("info.unlimited", unlimited)); - sender.sendMessage(MsgUtil.p("info.double", doubles)); - sender.sendMessage(MsgUtil.p("info.canclean", nostock)); - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + int buying, selling, doubles, chunks, worlds, unlimited; + buying = selling = doubles = chunks = worlds = unlimited = 0; + int nostock = 0; + sender.sendMessage(ChatColor.RED + "开始检索商店信息中..."); + for (final HashMap> inWorld : plugin.getShopManager().getShops().values()) { + worlds++; + for (final HashMap inChunk : inWorld.values()) { + chunks++; + for (final Shop shop : inChunk.values()) { + if (shop.isUnlimited()) { + unlimited++; + } + if (shop.isBuying()) { + buying++; + } else if (shop.isSelling()) { + selling++; + } + if (shop instanceof ContainerShop && ((ContainerShop) shop).isDoubleShop()) { + doubles++; + } else if (shop.isSelling() && shop.getRemainingStock() == 0) { + nostock++; + } + } + } + } + sender.sendMessage(MsgUtil.p("info.title", chunks, buying + selling, worlds)); + sender.sendMessage(MsgUtil.p("info.selling", selling)); + sender.sendMessage(MsgUtil.p("info.buying", buying)); + sender.sendMessage(MsgUtil.p("info.unlimited", unlimited)); + sender.sendMessage(MsgUtil.p("info.double", doubles)); + sender.sendMessage(MsgUtil.p("info.canclean", nostock)); + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandPrice.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandPrice.java index 5702d70..8ee4ae0 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandPrice.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandPrice.java @@ -14,86 +14,86 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandPrice extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandPrice(final QuickShop plugin) { - super("p"); - this.plugin = plugin; - setMinimumArguments(1); - setOnlyPlayerExecutable(); - setPossibleArguments("<价格>"); - setPermission("quickshop.create.changeprice"); - setDescription(MsgUtil.p("command.description.price")); - } + public CommandPrice(final QuickShop plugin) { + super("p"); + this.plugin = plugin; + setMinimumArguments(1); + setOnlyPlayerExecutable(); + setPossibleArguments("<价格>"); + setPermission("quickshop.create.changeprice"); + setDescription(MsgUtil.p("command.description.price")); + } - @SuppressWarnings("deprecation") - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final Player p = (Player) sender; - double price; - try { - price = Double.parseDouble(args[0]); - } catch (final NumberFormatException e) { - sender.sendMessage(MsgUtil.p("thats-not-a-number")); - return; - } - if (price < 0.01) { - sender.sendMessage(MsgUtil.p("price-too-cheap")); - return; - } - double fee = 0; - if (plugin.getConfigManager().isPriceChangeRequiresFee()) { - fee = plugin.getConfigManager().getFeeForPriceChange(); - if (fee > 0 && plugin.getEcon().getBalance(p.getName()) < fee) { - sender.sendMessage(MsgUtil.p("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); - return; - } - } - final BlockIterator bIt = new BlockIterator(p, 10); - // Loop through every block they're looking at upto 10 blocks away - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null && (shop.getOwner().equals(p.getName()) || sender.hasPermission("quickshop.other.price"))) { - if (shop.getPrice() == price) { - // Stop here if there isn't a price change - sender.sendMessage(MsgUtil.p("no-price-change")); - return; - } - if (fee > 0) { - if (!plugin.getEcon().withdraw(p.getName(), fee)) { - sender.sendMessage(MsgUtil.p("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); - return; - } - sender.sendMessage(MsgUtil.p("fee-charged-for-price-change", plugin.getEcon().format(fee))); - plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), fee); - } - // Update the shop - shop.setPrice(price); - shop.setSignText(); - shop.update(); - sender.sendMessage(MsgUtil.p("price-is-now", plugin.getEcon().format(shop.getPrice()))); - // Chest shops can be double shops. - if (shop instanceof ContainerShop) { - final ContainerShop cs = (ContainerShop) shop; - if (cs.isDoubleShop()) { - final Shop nextTo = cs.getAttachedShop(); - if (cs.isSelling()) { - if (cs.getPrice() < nextTo.getPrice()) { - sender.sendMessage(MsgUtil.p("buying-more-than-selling")); - } - } else { - // Buying - if (cs.getPrice() > nextTo.getPrice()) { - sender.sendMessage(MsgUtil.p("buying-more-than-selling")); - } - } - } - } - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @SuppressWarnings("deprecation") + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final Player p = (Player) sender; + double price; + try { + price = Double.parseDouble(args[0]); + } catch (final NumberFormatException e) { + sender.sendMessage(MsgUtil.p("thats-not-a-number")); + return; + } + if (price < 0.01) { + sender.sendMessage(MsgUtil.p("price-too-cheap")); + return; + } + double fee = 0; + if (plugin.getConfigManager().isPriceChangeRequiresFee()) { + fee = plugin.getConfigManager().getFeeForPriceChange(); + if (fee > 0 && plugin.getEcon().getBalance(p.getName()) < fee) { + sender.sendMessage(MsgUtil.p("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); + return; + } + } + final BlockIterator bIt = new BlockIterator(p, 10); + // Loop through every block they're looking at upto 10 blocks away + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null && (shop.getOwner().equals(p.getName()) || sender.hasPermission("quickshop.other.price"))) { + if (shop.getPrice() == price) { + // Stop here if there isn't a price change + sender.sendMessage(MsgUtil.p("no-price-change")); + return; + } + if (fee > 0) { + if (!plugin.getEcon().withdraw(p.getName(), fee)) { + sender.sendMessage(MsgUtil.p("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); + return; + } + sender.sendMessage(MsgUtil.p("fee-charged-for-price-change", plugin.getEcon().format(fee))); + plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), fee); + } + // Update the shop + shop.setPrice(price); + shop.setSignText(); + shop.update(); + sender.sendMessage(MsgUtil.p("price-is-now", plugin.getEcon().format(shop.getPrice()))); + // Chest shops can be double shops. + if (shop instanceof ContainerShop) { + final ContainerShop cs = (ContainerShop) shop; + if (cs.isDoubleShop()) { + final Shop nextTo = cs.getAttachedShop(); + if (cs.isSelling()) { + if (cs.getPrice() < nextTo.getPrice()) { + sender.sendMessage(MsgUtil.p("buying-more-than-selling")); + } + } else { + // Buying + if (cs.getPrice() > nextTo.getPrice()) { + sender.sendMessage(MsgUtil.p("buying-more-than-selling")); + } + } + } + } + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandRefill.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandRefill.java index a81ad71..23f681e 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandRefill.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandRefill.java @@ -13,37 +13,37 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandRefill extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandRefill(final QuickShop plugin) { - super("r"); - this.plugin = plugin; - setMinimumArguments(1); - setPossibleArguments("<数量>"); - setPermission("quickshop.refill"); - setDescription(MsgUtil.p("command.description.refill")); - } + public CommandRefill(final QuickShop plugin) { + super("r"); + this.plugin = plugin; + setMinimumArguments(1); + setPossibleArguments("<数量>"); + setPermission("quickshop.refill"); + setDescription(MsgUtil.p("command.description.refill")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - int add; - try { - add = Integer.parseInt(args[0]); - } catch (final NumberFormatException e) { - sender.sendMessage(MsgUtil.p("thats-not-a-number")); - return; - } - final BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - shop.add(shop.getItem(), add); - sender.sendMessage(MsgUtil.p("refill-success")); - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + int add; + try { + add = Integer.parseInt(args[0]); + } catch (final NumberFormatException e) { + sender.sendMessage(MsgUtil.p("thats-not-a-number")); + return; + } + final BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + shop.add(shop.getItem(), add); + sender.sendMessage(MsgUtil.p("refill-success")); + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandReload.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandReload.java index 9d4c113..7a59a8c 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandReload.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandReload.java @@ -10,21 +10,21 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandReload extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandReload(final QuickShop plugin) { - super("reload"); - this.plugin = plugin; - setPermission("quickshop.reload"); - setDescription(MsgUtil.p("command.description.reload")); - } + public CommandReload(final QuickShop plugin) { + super("reload"); + this.plugin = plugin; + setPermission("quickshop.reload"); + setDescription(MsgUtil.p("command.description.reload")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - sender.sendMessage(MsgUtil.p("command.reloading")); - plugin.reloadConfig(); - Bukkit.getPluginManager().disablePlugin(plugin); - Bukkit.getPluginManager().enablePlugin(plugin); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + sender.sendMessage(MsgUtil.p("command.reloading")); + plugin.reloadConfig(); + Bukkit.getPluginManager().disablePlugin(plugin); + Bukkit.getPluginManager().enablePlugin(plugin); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandRemove.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandRemove.java index 601a7a0..c17580f 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandRemove.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandRemove.java @@ -14,33 +14,33 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandRemove extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandRemove(final QuickShop plugin) { - super("r"); - this.plugin = plugin; - setOnlyPlayerExecutable(); - setPermission("quickshop.delete"); - setDescription(MsgUtil.p("command.description.remove")); - } + public CommandRemove(final QuickShop plugin) { + super("r"); + this.plugin = plugin; + setOnlyPlayerExecutable(); + setPermission("quickshop.delete"); + setDescription(MsgUtil.p("command.description.remove")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final Player p = (Player) sender; - final BlockIterator bIt = new BlockIterator(p, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if (shop.getOwner().equals(p.getName())) { - shop.delete(); - sender.sendMessage(ChatColor.GREEN + "商店已成功移除"); - } else { - p.sendMessage(ChatColor.RED + "这个不是你的商店!"); - } - return; - } - } - p.sendMessage(ChatColor.RED + "未找到商店!"); - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final Player p = (Player) sender; + final BlockIterator bIt = new BlockIterator(p, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if (shop.getOwner().equals(p.getName())) { + shop.delete(); + sender.sendMessage(ChatColor.GREEN + "商店已成功移除"); + } else { + p.sendMessage(ChatColor.RED + "这个不是你的商店!"); + } + return; + } + } + p.sendMessage(ChatColor.RED + "未找到商店!"); + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandSell.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandSell.java index 8dca0c3..844e811 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandSell.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandSell.java @@ -14,31 +14,31 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandSell extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandSell(final QuickShop plugin) { - super("s"); - this.plugin = plugin; - setPermission("quickshop.create.sell"); - setOnlyPlayerExecutable(); - setDescription(MsgUtil.p("command.description.sell")); - } + public CommandSell(final QuickShop plugin) { + super("s"); + this.plugin = plugin; + setPermission("quickshop.create.sell"); + setOnlyPlayerExecutable(); + setDescription(MsgUtil.p("command.description.sell")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null && shop.getOwner().equals(((Player) sender).getName())) { - shop.setShopType(ShopType.SELLING); - shop.setSignText(); - shop.update(); - sender.sendMessage(MsgUtil.p("command.now-selling", shop.getDataName())); - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null && shop.getOwner().equals(((Player) sender).getName())) { + shop.setShopType(ShopType.SELLING); + shop.setSignText(); + shop.update(); + sender.sendMessage(MsgUtil.p("command.now-selling", shop.getDataName())); + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandSetOwner.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandSetOwner.java index 62f1789..dfd31b5 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandSetOwner.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandSetOwner.java @@ -13,32 +13,32 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandSetOwner extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandSetOwner(final QuickShop plugin) { - super("so"); - this.plugin = plugin; - setOnlyPlayerExecutable(); - setMinimumArguments(1); - setPermission("quickshop.setowner"); - setDescription(MsgUtil.p("command.description.setowner")); - } + public CommandSetOwner(final QuickShop plugin) { + super("so"); + this.plugin = plugin; + setOnlyPlayerExecutable(); + setMinimumArguments(1); + setPermission("quickshop.setowner"); + setDescription(MsgUtil.p("command.description.setowner")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - shop.setOwner(args[0]); - shop.update(); - sender.sendMessage(MsgUtil.p("command.new-owner", args[0])); - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + shop.setOwner(args[0]); + shop.update(); + sender.sendMessage(MsgUtil.p("command.new-owner", args[0])); + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/CommandUnlimited.java b/src/main/java/org/maxgamer/QuickShop/Command/CommandUnlimited.java index f89e4c4..380ec88 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/CommandUnlimited.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/CommandUnlimited.java @@ -13,31 +13,31 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import cn.citycraft.PluginHelper.commands.BaseCommand; public class CommandUnlimited extends BaseCommand { - QuickShop plugin; + QuickShop plugin; - public CommandUnlimited(final QuickShop plugin) { - super("u"); - this.plugin = plugin; - setOnlyPlayerExecutable(); - setPermission("quickshop.unlimited"); - setDescription(MsgUtil.p("command.description.unlimited")); - } + public CommandUnlimited(final QuickShop plugin) { + super("u"); + this.plugin = plugin; + setOnlyPlayerExecutable(); + setPermission("quickshop.unlimited"); + setDescription(MsgUtil.p("command.description.unlimited")); + } - @Override - public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { - final BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - final Block b = bIt.next(); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - shop.setUnlimited(!shop.isUnlimited()); - shop.update(); - sender.sendMessage(MsgUtil.p("command.toggle-unlimited", (shop.isUnlimited() ? "无限模式" : "有限模式"))); - return; - } - } - sender.sendMessage(MsgUtil.p("not-looking-at-shop")); - return; - } + @Override + public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException { + final BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + final Block b = bIt.next(); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + shop.setUnlimited(!shop.isUnlimited()); + shop.update(); + sender.sendMessage(MsgUtil.p("command.toggle-unlimited", (shop.isUnlimited() ? "无限模式" : "有限模式"))); + return; + } + } + sender.sendMessage(MsgUtil.p("not-looking-at-shop")); + return; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Command/QuickShopCommands.java b/src/main/java/org/maxgamer/QuickShop/Command/QuickShopCommands.java index 1f74e52..8208e64 100644 --- a/src/main/java/org/maxgamer/QuickShop/Command/QuickShopCommands.java +++ b/src/main/java/org/maxgamer/QuickShop/Command/QuickShopCommands.java @@ -9,31 +9,31 @@ import cn.citycraft.PluginHelper.commands.DefaultCommand; import cn.citycraft.PluginHelper.commands.HandlerSubCommand; public class QuickShopCommands implements DefaultCommand { - HandlerSubCommand hsc; - QuickShop plugin; + HandlerSubCommand hsc; + QuickShop plugin; - public QuickShopCommands(final QuickShop plugin) { - this.plugin = plugin; - hsc = new HandlerSubCommand(plugin, "qs"); - hsc.setDefaultCommand(this); - hsc.registerCommand(new CommandClean(plugin)); - hsc.registerCommand(new CommandEmpty(plugin)); - hsc.registerCommand(new CommandExport(plugin)); - hsc.registerCommand(new CommandFind(plugin)); - hsc.registerCommand(new CommandInfo(plugin)); - hsc.registerCommand(new CommandPrice(plugin)); - hsc.registerCommand(new CommandRefill(plugin)); - hsc.registerCommand(new CommandReload(plugin)); - hsc.registerCommand(new CommandRemove(plugin)); - hsc.registerCommand(new CommandBuy(plugin)); - hsc.registerCommand(new CommandSetOwner(plugin)); - hsc.registerCommand(new CommandSell(plugin)); - hsc.registerCommand(new CommandUnlimited(plugin)); - } + public QuickShopCommands(final QuickShop plugin) { + this.plugin = plugin; + hsc = new HandlerSubCommand(plugin, "qs"); + hsc.setDefaultCommand(this); + hsc.registerCommand(new CommandClean(plugin)); + hsc.registerCommand(new CommandEmpty(plugin)); + hsc.registerCommand(new CommandExport(plugin)); + hsc.registerCommand(new CommandFind(plugin)); + hsc.registerCommand(new CommandInfo(plugin)); + hsc.registerCommand(new CommandPrice(plugin)); + hsc.registerCommand(new CommandRefill(plugin)); + hsc.registerCommand(new CommandReload(plugin)); + hsc.registerCommand(new CommandRemove(plugin)); + hsc.registerCommand(new CommandBuy(plugin)); + hsc.registerCommand(new CommandSetOwner(plugin)); + hsc.registerCommand(new CommandSell(plugin)); + hsc.registerCommand(new CommandUnlimited(plugin)); + } - @Override - public void defaultExecute(final CommandSender sender, final Command command, final String label) throws CommandException { - hsc.sendHelp(sender, label); - } + @Override + public void defaultExecute(final CommandSender sender, final Command command, final String label) throws CommandException { + hsc.sendHelp(sender, label); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Config/ConfigManager.java b/src/main/java/org/maxgamer/QuickShop/Config/ConfigManager.java index 87012e2..10d3742 100644 --- a/src/main/java/org/maxgamer/QuickShop/Config/ConfigManager.java +++ b/src/main/java/org/maxgamer/QuickShop/Config/ConfigManager.java @@ -13,200 +13,200 @@ import cn.citycraft.PluginHelper.config.FileConfig; import cn.citycraft.PluginHelper.tellraw.FancyMessage; public class ConfigManager { - private boolean enableMagicLib = false; - /** Whether debug info should be shown in the console */ - private final boolean debug = false; + private boolean enableMagicLib = false; + /** Whether debug info should be shown in the console */ + private final boolean debug = false; - /** Whether we should use display items or not */ - private boolean display = true; - private double feeForPriceChange = 0.0; - private int findDistance = 30; - private String guiTitle = "§6[§b快捷商店§6]§r"; - /** Whether or not to limit players shop amounts */ - private boolean limit = false; + /** Whether we should use display items or not */ + private boolean display = true; + private double feeForPriceChange = 0.0; + private int findDistance = 30; + private String guiTitle = "§6[§b快捷商店§6]§r"; + /** Whether or not to limit players shop amounts */ + private boolean limit = false; - private int limitdefault = 0; - private final HashMap limits = new HashMap<>(); - private boolean logAction = true; - private boolean preventhopper = false; - /** - * Whether we players are charged a fee to change the price on their shop - * (To help deter endless undercutting - */ - private boolean priceChangeRequiresFee = false; - private boolean shopLock = true; - private boolean showTax = false; - /** Whether players are required to sneak to create/buy from a shop */ - private boolean sneak = false; - /** Whether players are required to sneak to create a shop */ - private boolean sneakCreate = false; - /** Whether players are required to sneak to trade with a shop */ - private boolean sneakTrade = false; - private Material superItem = Material.GOLD_AXE; - private double tax = 0; - private final String taxAccount; - private boolean fakeItem = false; + private int limitdefault = 0; + private final HashMap limits = new HashMap<>(); + private boolean logAction = true; + private boolean preventhopper = false; + /** + * Whether we players are charged a fee to change the price on their shop + * (To help deter endless undercutting + */ + private boolean priceChangeRequiresFee = false; + private boolean shopLock = true; + private boolean showTax = false; + /** Whether players are required to sneak to create/buy from a shop */ + private boolean sneak = false; + /** Whether players are required to sneak to create a shop */ + private boolean sneakCreate = false; + /** Whether players are required to sneak to trade with a shop */ + private boolean sneakTrade = false; + private Material superItem = Material.GOLD_AXE; + private double tax = 0; + private final String taxAccount; + private boolean fakeItem = false; - /** - * A set of players who have been warned - * ("Your shop isn't automatically locked") - */ - private final HashSet warnings = new HashSet<>(); + /** + * A set of players who have been warned + * ("Your shop isn't automatically locked") + */ + private final HashSet warnings = new HashSet<>(); - public ConfigManager(final QuickShop plugin) { - final FileConfig config = (FileConfig) plugin.getConfig(); - ConfigurationSection limitCfg = config.getConfigurationSection("limits"); - if (limitCfg != null) { - this.limit = limitCfg.getBoolean("use", false); - this.limitdefault = config.getInt("limits.default"); - limitCfg = limitCfg.getConfigurationSection("ranks"); - for (final String key : limitCfg.getKeys(true)) { - limits.put(key, limitCfg.getInt(key)); - } - } - try { - this.superItem = Material.valueOf(config.getString("superitem")); - } catch (final Exception e) { - } - this.tax = config.getDouble("tax"); - this.showTax = config.getBoolean("show-tax"); - this.taxAccount = config.getString("tax-account"); - this.logAction = config.getBoolean("log-actions"); - this.shopLock = config.getBoolean("shop.lock"); - this.display = config.getBoolean("shop.display-items"); - this.sneak = config.getBoolean("shop.sneak-only"); - this.sneakCreate = config.getBoolean("shop.sneak-to-create"); - this.sneakTrade = config.getBoolean("shop.sneak-to-trade"); - this.priceChangeRequiresFee = config.getBoolean("shop.price-change-requires-fee"); - this.findDistance = config.getInt("shop.find-distance"); - this.feeForPriceChange = config.getDouble("shop.fee-for-price-change"); - this.preventhopper = config.getBoolean("preventhopper"); - this.guiTitle = config.getMessage("guititle", guiTitle); - this.fakeItem = config.getBoolean("fakeitem", true); - if (config.getBoolean("fakeitem", true)) { - try { - plugin.getLogger().info("启用虚拟悬浮物 尝试启动中..."); - FakeItem.register(plugin); - plugin.getLogger().info("虚拟悬浮物功能测试正常..."); - fakeItem = true; - } catch (final Exception e) { - plugin.getLogger().warning("+========================================="); - plugin.getLogger().warning("| 警告: 虚拟物品启动失败 使用原版悬浮物品..."); - plugin.getLogger().warning("+========================================="); - } - } - if (config.getBoolean("usemagiclib", true)) { - try { - plugin.getLogger().info("启用魔改库 尝试启动中..."); - final FancyMessage fm = FancyMessage.newFM("test"); - fm.then("item").itemTooltip(new ItemStack(Material.DIAMOND_SWORD)); - fm.then("link").link("ci.citycraft.cn"); - fm.then("suggest").suggest("qs help"); - fm.toJSONString(); - plugin.getLogger().info("魔改库功能测试正常..."); - this.enableMagicLib = true; - } catch (final Error | Exception e) { - plugin.getLogger().warning("+========================================="); - plugin.getLogger().warning("| 警告: 启动魔改库失败 将使用GUI商店界面..."); - plugin.getLogger().warning("+========================================="); - } - } - } + public ConfigManager(final QuickShop plugin) { + final FileConfig config = (FileConfig) plugin.getConfig(); + ConfigurationSection limitCfg = config.getConfigurationSection("limits"); + if (limitCfg != null) { + this.limit = limitCfg.getBoolean("use", false); + this.limitdefault = config.getInt("limits.default"); + limitCfg = limitCfg.getConfigurationSection("ranks"); + for (final String key : limitCfg.getKeys(true)) { + limits.put(key, limitCfg.getInt(key)); + } + } + try { + this.superItem = Material.valueOf(config.getString("superitem")); + } catch (final Exception e) { + } + this.tax = config.getDouble("tax"); + this.showTax = config.getBoolean("show-tax"); + this.taxAccount = config.getString("tax-account"); + this.logAction = config.getBoolean("log-actions"); + this.shopLock = config.getBoolean("shop.lock"); + this.display = config.getBoolean("shop.display-items"); + this.sneak = config.getBoolean("shop.sneak-only"); + this.sneakCreate = config.getBoolean("shop.sneak-to-create"); + this.sneakTrade = config.getBoolean("shop.sneak-to-trade"); + this.priceChangeRequiresFee = config.getBoolean("shop.price-change-requires-fee"); + this.findDistance = config.getInt("shop.find-distance"); + this.feeForPriceChange = config.getDouble("shop.fee-for-price-change"); + this.preventhopper = config.getBoolean("preventhopper"); + this.guiTitle = config.getMessage("guititle", guiTitle); + this.fakeItem = config.getBoolean("fakeitem", true); + if (config.getBoolean("fakeitem", true)) { + try { + plugin.getLogger().info("启用虚拟悬浮物 尝试启动中..."); + FakeItem.register(plugin); + plugin.getLogger().info("虚拟悬浮物功能测试正常..."); + fakeItem = true; + } catch (final Exception e) { + plugin.getLogger().warning("+========================================="); + plugin.getLogger().warning("| 警告: 虚拟物品启动失败 使用原版悬浮物品..."); + plugin.getLogger().warning("+========================================="); + } + } + if (config.getBoolean("usemagiclib", true)) { + try { + plugin.getLogger().info("启用魔改库 尝试启动中..."); + final FancyMessage fm = FancyMessage.newFM("test"); + fm.then("item").itemTooltip(new ItemStack(Material.DIAMOND_SWORD)); + fm.then("link").link("ci.citycraft.cn"); + fm.then("suggest").suggest("qs help"); + fm.toJSONString(); + plugin.getLogger().info("魔改库功能测试正常..."); + this.enableMagicLib = true; + } catch (final Error | Exception e) { + plugin.getLogger().warning("+========================================="); + plugin.getLogger().warning("| 警告: 启动魔改库失败 将使用GUI商店界面..."); + plugin.getLogger().warning("+========================================="); + } + } + } - public double getFeeForPriceChange() { - return feeForPriceChange; - } + public double getFeeForPriceChange() { + return feeForPriceChange; + } - public int getFindDistance() { - return findDistance; - } + public int getFindDistance() { + return findDistance; + } - public String getGuiTitle() { - return guiTitle; - } + public String getGuiTitle() { + return guiTitle; + } - public int getLimitdefault() { - return limitdefault; - } + public int getLimitdefault() { + return limitdefault; + } - public HashMap getLimits() { - return limits; - } + public HashMap getLimits() { + return limits; + } - public Material getSuperItem() { - return superItem; - } + public Material getSuperItem() { + return superItem; + } - public double getTax() { - return tax; - } + public double getTax() { + return tax; + } - public String getTaxAccount() { - return taxAccount; - } + public String getTaxAccount() { + return taxAccount; + } - public HashSet getWarnings() { - return warnings; - } + public HashSet getWarnings() { + return warnings; + } - public boolean isDebug() { - return debug; - } + public boolean isDebug() { + return debug; + } - public boolean isDisplay() { - return display; - } + public boolean isDisplay() { + return display; + } - public boolean isEnableMagicLib() { - return enableMagicLib; - } + public boolean isEnableMagicLib() { + return enableMagicLib; + } - public boolean isFakeItem() { - return fakeItem; - } + public boolean isFakeItem() { + return fakeItem; + } - public boolean isLimit() { - return limit; - } + public boolean isLimit() { + return limit; + } - public boolean isLogAction() { - return logAction; - } + public boolean isLogAction() { + return logAction; + } - public boolean isPreventHopper() { - return preventhopper; - } + public boolean isPreventHopper() { + return preventhopper; + } - public boolean isPriceChangeRequiresFee() { - return priceChangeRequiresFee; - } + public boolean isPriceChangeRequiresFee() { + return priceChangeRequiresFee; + } - public boolean isShopLock() { - return shopLock; - } + public boolean isShopLock() { + return shopLock; + } - public boolean isShowTax() { - return showTax; - } + public boolean isShowTax() { + return showTax; + } - public boolean isSneak() { - return sneak; - } + public boolean isSneak() { + return sneak; + } - public boolean isSneakCreate() { - return sneakCreate; - } + public boolean isSneakCreate() { + return sneakCreate; + } - public boolean isSneakTrade() { - return sneakTrade; - } + public boolean isSneakTrade() { + return sneakTrade; + } - public void setEnableMagicLib(final boolean enableMagicLib) { - this.enableMagicLib = enableMagicLib; - } + public void setEnableMagicLib(final boolean enableMagicLib) { + this.enableMagicLib = enableMagicLib; + } - public void setFakeItem(final boolean fakeItem) { - this.fakeItem = fakeItem; - } + public void setFakeItem(final boolean fakeItem) { + this.fakeItem = fakeItem; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Database/BufferStatement.java b/src/main/java/org/maxgamer/QuickShop/Database/BufferStatement.java index d95163d..1137828 100644 --- a/src/main/java/org/maxgamer/QuickShop/Database/BufferStatement.java +++ b/src/main/java/org/maxgamer/QuickShop/Database/BufferStatement.java @@ -6,69 +6,69 @@ import java.sql.SQLException; import java.util.Arrays; public class BufferStatement { - private Object[] values; - private String query; - private Exception stacktrace; + private Object[] values; + private String query; + private Exception stacktrace; - /** - * Represents a PreparedStatement in a state before preparing it (E.g. No - * file I/O Required) - * - * @param query - * The query to execute. E.g. INSERT INTO accounts (user, passwd) - * VALUES (?, ?) - * @param values - * The values to replace ? with in - * query. These are in order. - */ - public BufferStatement(String query, Object... values) { - this.query = query; - this.values = values; - this.stacktrace = new Exception(); // For error handling - this.stacktrace.fillInStackTrace(); // We can declare where this - // statement came from. - } + /** + * Represents a PreparedStatement in a state before preparing it (E.g. No + * file I/O Required) + * + * @param query + * The query to execute. E.g. INSERT INTO accounts (user, passwd) + * VALUES (?, ?) + * @param values + * The values to replace ? with in + * query. These are in order. + */ + public BufferStatement(String query, Object... values) { + this.query = query; + this.values = values; + this.stacktrace = new Exception(); // For error handling + this.stacktrace.fillInStackTrace(); // We can declare where this + // statement came from. + } - /** - * Returns a prepared statement using the given connection. Will try to - * return an empty statement if something went wrong. If that fails, returns - * null. - * - * This method escapes everything automatically. - * - * @param con - * The connection to prepare this on using - * con.prepareStatement(..) - * @return The prepared statement, ready for execution. - */ - public PreparedStatement prepareStatement(Connection con) throws SQLException { - PreparedStatement ps; - ps = con.prepareStatement(query); - for (int i = 1; i <= values.length; i++) { - ps.setObject(i, values[i - 1]); - } - return ps; - } + /** + * Returns a prepared statement using the given connection. Will try to + * return an empty statement if something went wrong. If that fails, returns + * null. + * + * This method escapes everything automatically. + * + * @param con + * The connection to prepare this on using + * con.prepareStatement(..) + * @return The prepared statement, ready for execution. + */ + public PreparedStatement prepareStatement(Connection con) throws SQLException { + PreparedStatement ps; + ps = con.prepareStatement(query); + for (int i = 1; i <= values.length; i++) { + ps.setObject(i, values[i - 1]); + } + return ps; + } - /** - * Used for debugging. This stacktrace is recorded when the statement is - * created, so printing it to the screen will provide useful debugging - * information about where the query came from, if something went wrong - * while executing it. - * - * @return The stacktrace elements. - */ - public StackTraceElement[] getStackTrace() { - return stacktrace.getStackTrace(); - } + /** + * Used for debugging. This stacktrace is recorded when the statement is + * created, so printing it to the screen will provide useful debugging + * information about where the query came from, if something went wrong + * while executing it. + * + * @return The stacktrace elements. + */ + public StackTraceElement[] getStackTrace() { + return stacktrace.getStackTrace(); + } - /** - * @return A string representation of this statement. Returns - * "Query: " + query + ", values: " + - * Arrays.toString(values). - */ - @Override - public String toString() { - return "Query: " + query + ", values: " + Arrays.toString(values); - } + /** + * @return A string representation of this statement. Returns + * "Query: " + query + ", values: " + + * Arrays.toString(values). + */ + @Override + public String toString() { + return "Query: " + query + ", values: " + Arrays.toString(values); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Database/Database.java b/src/main/java/org/maxgamer/QuickShop/Database/Database.java index 4a658c8..e33adb5 100644 --- a/src/main/java/org/maxgamer/QuickShop/Database/Database.java +++ b/src/main/java/org/maxgamer/QuickShop/Database/Database.java @@ -8,192 +8,192 @@ import java.util.LinkedList; import java.util.List; public class Database { - private DatabaseCore core; + private DatabaseCore core; - /** - * Creates a new database and validates its connection. - * - * If the connection is invalid, this will throw a ConnectionException. - * - * @param core - * The core for the database, either MySQL or SQLite. - * @throws ConnectionException - * If the connection was invalid - */ - public Database(DatabaseCore core) throws ConnectionException { - try { - try { - if (!core.getConnection().isValid(10)) { - throw new ConnectionException("Database doesn not appear to be valid!"); - } - } catch (AbstractMethodError e) { - // You don't need to validate this core. - } - } catch (SQLException e) { - throw new ConnectionException(e.getMessage()); - } - this.core = core; - } + /** + * Creates a new database and validates its connection. + * + * If the connection is invalid, this will throw a ConnectionException. + * + * @param core + * The core for the database, either MySQL or SQLite. + * @throws ConnectionException + * If the connection was invalid + */ + public Database(DatabaseCore core) throws ConnectionException { + try { + try { + if (!core.getConnection().isValid(10)) { + throw new ConnectionException("Database doesn not appear to be valid!"); + } + } catch (AbstractMethodError e) { + // You don't need to validate this core. + } + } catch (SQLException e) { + throw new ConnectionException(e.getMessage()); + } + this.core = core; + } - /** - * Returns the database core object, that this database runs on. - * - * @return the database core object, that this database runs on. - */ - public DatabaseCore getCore() { - return core; - } + /** + * Returns the database core object, that this database runs on. + * + * @return the database core object, that this database runs on. + */ + public DatabaseCore getCore() { + return core; + } - /** - * Fetches the connection to this database for querying. Try to avoid doing - * this in the main thread. - * - * @return Fetches the connection to this database for querying. - */ - public Connection getConnection() { - return core.getConnection(); - } + /** + * Fetches the connection to this database for querying. Try to avoid doing + * this in the main thread. + * + * @return Fetches the connection to this database for querying. + */ + public Connection getConnection() { + return core.getConnection(); + } - /** - * Executes the given statement either immediately, or soon. - * - * @param query - * The query - * @param objs - * The string values for each ? in the given query. - */ - public void execute(String query, Object... objs) { - BufferStatement bs = new BufferStatement(query, objs); - core.queue(bs); - } + /** + * Executes the given statement either immediately, or soon. + * + * @param query + * The query + * @param objs + * The string values for each ? in the given query. + */ + public void execute(String query, Object... objs) { + BufferStatement bs = new BufferStatement(query, objs); + core.queue(bs); + } - /** - * Returns true if the table exists - * - * @param table - * The table to check for - * @return True if the table is found - */ - public boolean hasTable(String table) throws SQLException { - ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null); - while (rs.next()) { - if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) { - rs.close(); - return true; - } - } - rs.close(); - return false; - } + /** + * Returns true if the table exists + * + * @param table + * The table to check for + * @return True if the table is found + */ + public boolean hasTable(String table) throws SQLException { + ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null); + while (rs.next()) { + if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) { + rs.close(); + return true; + } + } + rs.close(); + return false; + } - /** - * Closes the database - */ - public void close() { - this.core.close(); - } + /** + * Closes the database + */ + public void close() { + this.core.close(); + } - /** - * Returns true if the given table has the given column - * - * @param table - * The table - * @param column - * The column - * @return True if the given table has the given column - * @throws SQLException - * If the database isn't connected - */ - public boolean hasColumn(String table, String column) throws SQLException { - if (!hasTable(table)) - return false; - String query = "SELECT * FROM " + table + " LIMIT 0,1"; - try { - PreparedStatement ps = this.getConnection().prepareStatement(query); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - rs.getString(column); // Throws an exception if it can't find - // that column - return true; - } - } catch (SQLException e) { - return false; - } - return false; // Uh, wtf. - } + /** + * Returns true if the given table has the given column + * + * @param table + * The table + * @param column + * The column + * @return True if the given table has the given column + * @throws SQLException + * If the database isn't connected + */ + public boolean hasColumn(String table, String column) throws SQLException { + if (!hasTable(table)) + return false; + String query = "SELECT * FROM " + table + " LIMIT 0,1"; + try { + PreparedStatement ps = this.getConnection().prepareStatement(query); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + rs.getString(column); // Throws an exception if it can't find + // that column + return true; + } + } catch (SQLException e) { + return false; + } + return false; // Uh, wtf. + } - /** - * Represents a connection error, generally when the server can't connect to - * MySQL or something. - */ - public static class ConnectionException extends Exception { - private static final long serialVersionUID = 8348749992936357317L; + /** + * Represents a connection error, generally when the server can't connect to + * MySQL or something. + */ + public static class ConnectionException extends Exception { + private static final long serialVersionUID = 8348749992936357317L; - public ConnectionException(String msg) { - super(msg); - } - } + public ConnectionException(String msg) { + super(msg); + } + } - /** - * Copies the contents of this database into the given database. Does not - * delete the contents of this database, or change any settings. This may - * take a long time, and will print out progress reports to System.out - * - * This method does not create the tables in the new database. You need to - * do that yourself. - * - * @param db - * The database to copy data to - * @throws SQLException - * if an error occurs. - */ - public void copyTo(Database db) throws SQLException { - ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null); - List tables = new LinkedList(); - while (rs.next()) { - tables.add(rs.getString("TABLE_NAME")); - } - rs.close(); - core.flush(); - // For each table - for (String table : tables) { - if (table.toLowerCase().startsWith("sqlite_autoindex_")) - continue; - System.out.println("Copying " + table); - // Wipe the old records - db.getConnection().prepareStatement("DELETE FROM " + table).execute(); - // Fetch all the data from the existing database - rs = getConnection().prepareStatement("SELECT * FROM " + table).executeQuery(); - int n = 0; - // Build the query - String query = "INSERT INTO " + table + " VALUES ("; - // Append another placeholder for the value - query += "?"; - for (int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { - // Add the rest of the placeholders and values. This is so we - // have (?, ?, ?) and not (?, ?, ?, ). - query += ", ?"; - } - // End the query - query += ")"; - PreparedStatement ps = db.getConnection().prepareStatement(query); - while (rs.next()) { - n++; - for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { - ps.setObject(i, rs.getObject(i)); - } - ps.addBatch(); - if (n % 100 == 0) { - ps.executeBatch(); - System.out.println(n + " records copied..."); - } - } - ps.executeBatch(); - // Close the resultset of that table - rs.close(); - } - // Success! - db.getConnection().close(); - this.getConnection().close(); - } + /** + * Copies the contents of this database into the given database. Does not + * delete the contents of this database, or change any settings. This may + * take a long time, and will print out progress reports to System.out + * + * This method does not create the tables in the new database. You need to + * do that yourself. + * + * @param db + * The database to copy data to + * @throws SQLException + * if an error occurs. + */ + public void copyTo(Database db) throws SQLException { + ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null); + List tables = new LinkedList(); + while (rs.next()) { + tables.add(rs.getString("TABLE_NAME")); + } + rs.close(); + core.flush(); + // For each table + for (String table : tables) { + if (table.toLowerCase().startsWith("sqlite_autoindex_")) + continue; + System.out.println("Copying " + table); + // Wipe the old records + db.getConnection().prepareStatement("DELETE FROM " + table).execute(); + // Fetch all the data from the existing database + rs = getConnection().prepareStatement("SELECT * FROM " + table).executeQuery(); + int n = 0; + // Build the query + String query = "INSERT INTO " + table + " VALUES ("; + // Append another placeholder for the value + query += "?"; + for (int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { + // Add the rest of the placeholders and values. This is so we + // have (?, ?, ?) and not (?, ?, ?, ). + query += ", ?"; + } + // End the query + query += ")"; + PreparedStatement ps = db.getConnection().prepareStatement(query); + while (rs.next()) { + n++; + for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { + ps.setObject(i, rs.getObject(i)); + } + ps.addBatch(); + if (n % 100 == 0) { + ps.executeBatch(); + System.out.println(n + " records copied..."); + } + } + ps.executeBatch(); + // Close the resultset of that table + rs.close(); + } + // Success! + db.getConnection().close(); + this.getConnection().close(); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Database/DatabaseCore.java b/src/main/java/org/maxgamer/QuickShop/Database/DatabaseCore.java index e6e71f6..b89289b 100644 --- a/src/main/java/org/maxgamer/QuickShop/Database/DatabaseCore.java +++ b/src/main/java/org/maxgamer/QuickShop/Database/DatabaseCore.java @@ -3,11 +3,11 @@ package org.maxgamer.QuickShop.Database; import java.sql.Connection; public interface DatabaseCore { - public Connection getConnection(); + public Connection getConnection(); - public void queue(BufferStatement bs); + public void queue(BufferStatement bs); - public void flush(); + public void flush(); - public void close(); + public void close(); } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Database/DatabaseHelper.java b/src/main/java/org/maxgamer/QuickShop/Database/DatabaseHelper.java index 97ada43..cbaaf5b 100644 --- a/src/main/java/org/maxgamer/QuickShop/Database/DatabaseHelper.java +++ b/src/main/java/org/maxgamer/QuickShop/Database/DatabaseHelper.java @@ -5,58 +5,59 @@ import java.sql.SQLException; import java.sql.Statement; public class DatabaseHelper { - public static void setup(Database db) throws SQLException { - if (!db.hasTable("shops")) { - createShopsTable(db); - } - if (!db.hasTable("messages")) { - createMessagesTable(db); - } - checkColumns(db); - } + public static void setup(Database db) throws SQLException { + if (!db.hasTable("shops")) { + createShopsTable(db); + } + if (!db.hasTable("messages")) { + createMessagesTable(db); + } + checkColumns(db); + } - /** - * Verifies that all required columns exist. - */ - public static void checkColumns(Database db) { - PreparedStatement ps = null; - try { - // V3.4.2 - ps = db.getConnection().prepareStatement("ALTER TABLE shops MODIFY COLUMN price double(32,2) NOT NULL AFTER owner"); - ps.execute(); - ps.close(); - } catch (SQLException e) { - } - try { - // V3.4.3 - ps = db.getConnection().prepareStatement("ALTER TABLE messages MODIFY COLUMN time BIGINT(32) NOT NULL AFTER message"); - ps.execute(); - ps.close(); - } catch (SQLException e) { - } - } + /** + * Verifies that all required columns exist. + */ + public static void checkColumns(Database db) { + PreparedStatement ps = null; + try { + // V3.4.2 + ps = db.getConnection().prepareStatement("ALTER TABLE shops MODIFY COLUMN price double(32,2) NOT NULL AFTER owner"); + ps.execute(); + ps.close(); + } catch (SQLException e) { + } + try { + // V3.4.3 + ps = db.getConnection().prepareStatement("ALTER TABLE messages MODIFY COLUMN time BIGINT(32) NOT NULL AFTER message"); + ps.execute(); + ps.close(); + } catch (SQLException e) { + } + } - /** - * Creates the database table 'shops'. - * - * @throws SQLException - * If the connection is invalid. - */ - public static void createShopsTable(Database db) throws SQLException { - Statement st = db.getConnection().createStatement(); - String createTable = "CREATE TABLE shops (" + "owner TEXT(32) NOT NULL, " + "price double(32, 2) NOT NULL, " + "itemConfig TEXT CHARSET utf8 NOT NULL, " + "x INTEGER(32) NOT NULL, " + "y INTEGER(32) NOT NULL, " + "z INTEGER(32) NOT NULL, " + "world VARCHAR(32) NOT NULL, " + "unlimited boolean, " + "type boolean, " + "PRIMARY KEY (x, y, z, world) " + ");"; - st.execute(createTable); - } + /** + * Creates the database table 'shops'. + * + * @throws SQLException + * If the connection is invalid. + */ + public static void createShopsTable(Database db) throws SQLException { + Statement st = db.getConnection().createStatement(); + String createTable = "CREATE TABLE shops (" + "owner TEXT(32) NOT NULL, " + "price double(32, 2) NOT NULL, " + "itemConfig TEXT CHARSET utf8 NOT NULL, " + "x INTEGER(32) NOT NULL, " + + "y INTEGER(32) NOT NULL, " + "z INTEGER(32) NOT NULL, " + "world VARCHAR(32) NOT NULL, " + "unlimited boolean, " + "type boolean, " + "PRIMARY KEY (x, y, z, world) " + ");"; + st.execute(createTable); + } - /** - * Creates the database table 'messages' - * - * @throws SQLException - * If the connection is invalid - */ - public static void createMessagesTable(Database db) throws SQLException { - Statement st = db.getConnection().createStatement(); - String createTable = "CREATE TABLE messages (" + "owner TEXT(32) NOT NULL, " + "message TEXT(200) NOT NULL, " + "time BIGINT(32) NOT NULL " + ");"; - st.execute(createTable); - } + /** + * Creates the database table 'messages' + * + * @throws SQLException + * If the connection is invalid + */ + public static void createMessagesTable(Database db) throws SQLException { + Statement st = db.getConnection().createStatement(); + String createTable = "CREATE TABLE messages (" + "owner TEXT(32) NOT NULL, " + "message TEXT(200) NOT NULL, " + "time BIGINT(32) NOT NULL " + ");"; + st.execute(createTable); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Database/MySQLCore.java b/src/main/java/org/maxgamer/QuickShop/Database/MySQLCore.java index 91c0ea4..10f1c62 100644 --- a/src/main/java/org/maxgamer/QuickShop/Database/MySQLCore.java +++ b/src/main/java/org/maxgamer/QuickShop/Database/MySQLCore.java @@ -8,78 +8,78 @@ import java.util.ArrayList; import java.util.Properties; public class MySQLCore implements DatabaseCore { - private String url; - /** The connection properties... user, pass, autoReconnect.. */ - private Properties info; - private static final int MAX_CONNECTIONS = 8; - private static ArrayList pool = new ArrayList(); + private String url; + /** The connection properties... user, pass, autoReconnect.. */ + private Properties info; + private static final int MAX_CONNECTIONS = 8; + private static ArrayList pool = new ArrayList(); - public MySQLCore(String host, String user, String pass, String database, String port) { - info = new Properties(); - info.put("autoReconnect", "true"); - info.put("user", user); - info.put("password", pass); - info.put("useUnicode", "true"); - info.put("characterEncoding", "utf8"); - this.url = "jdbc:mysql://" + host + ":" + port + "/" + database; - for (int i = 0; i < MAX_CONNECTIONS; i++) - pool.add(null); - } + public MySQLCore(String host, String user, String pass, String database, String port) { + info = new Properties(); + info.put("autoReconnect", "true"); + info.put("user", user); + info.put("password", pass); + info.put("useUnicode", "true"); + info.put("characterEncoding", "utf8"); + this.url = "jdbc:mysql://" + host + ":" + port + "/" + database; + for (int i = 0; i < MAX_CONNECTIONS; i++) + pool.add(null); + } - /** - * Gets the database connection for executing queries on. - * - * @return The database connection - */ - public Connection getConnection() { - for (int i = 0; i < MAX_CONNECTIONS; i++) { - Connection connection = pool.get(i); - try { - // If we have a current connection, fetch it - if (connection != null && !connection.isClosed()) { - if (connection.isValid(10)) { - return connection; - } - // Else, it is invalid, so we return another connection. - } - connection = DriverManager.getConnection(this.url, info); - pool.set(i, connection); - return connection; - } catch (SQLException e) { - e.printStackTrace(); - } - } - return null; - } + /** + * Gets the database connection for executing queries on. + * + * @return The database connection + */ + public Connection getConnection() { + for (int i = 0; i < MAX_CONNECTIONS; i++) { + Connection connection = pool.get(i); + try { + // If we have a current connection, fetch it + if (connection != null && !connection.isClosed()) { + if (connection.isValid(10)) { + return connection; + } + // Else, it is invalid, so we return another connection. + } + connection = DriverManager.getConnection(this.url, info); + pool.set(i, connection); + return connection; + } catch (SQLException e) { + e.printStackTrace(); + } + } + return null; + } - @Override - public void queue(BufferStatement bs) { - try { - Connection con = this.getConnection(); - while (con == null) { - try { - Thread.sleep(15); - } catch (InterruptedException e) { - } - // Try again - this.getConnection(); - } - PreparedStatement ps = bs.prepareStatement(con); - ps.execute(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - return; - } - } + @Override + public void queue(BufferStatement bs) { + try { + Connection con = this.getConnection(); + while (con == null) { + try { + Thread.sleep(15); + } catch (InterruptedException e) { + } + // Try again + this.getConnection(); + } + PreparedStatement ps = bs.prepareStatement(con); + ps.execute(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + return; + } + } - @Override - public void close() { - // Nothing, because queries are executed immediately for MySQL - } + @Override + public void close() { + // Nothing, because queries are executed immediately for MySQL + } - @Override - public void flush() { - // Nothing, because queries are executed immediately for MySQL - } + @Override + public void flush() { + // Nothing, because queries are executed immediately for MySQL + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Database/SQLiteCore.java b/src/main/java/org/maxgamer/QuickShop/Database/SQLiteCore.java index 6310be3..51b56ca 100644 --- a/src/main/java/org/maxgamer/QuickShop/Database/SQLiteCore.java +++ b/src/main/java/org/maxgamer/QuickShop/Database/SQLiteCore.java @@ -9,102 +9,102 @@ import java.sql.SQLException; import java.util.LinkedList; public class SQLiteCore implements DatabaseCore { - private Connection connection; - private final File dbFile; - private volatile Thread watcher; - private volatile LinkedList queue = new LinkedList(); + private Connection connection; + private final File dbFile; + private volatile Thread watcher; + private volatile LinkedList queue = new LinkedList(); - public SQLiteCore(final File dbFile) { - this.dbFile = dbFile; - } + public SQLiteCore(final File dbFile) { + this.dbFile = dbFile; + } - @Override - public void close() { - flush(); - } + @Override + public void close() { + flush(); + } - @Override - public void flush() { - while (queue.isEmpty() == false) { - BufferStatement bs; - synchronized (queue) { - bs = queue.removeFirst(); - } - synchronized (dbFile) { - try { - final PreparedStatement ps = bs.prepareStatement(getConnection()); - ps.execute(); - ps.close(); - } catch (final SQLException e) { - e.printStackTrace(); - } - } - } - } + @Override + public void flush() { + while (queue.isEmpty() == false) { + BufferStatement bs; + synchronized (queue) { + bs = queue.removeFirst(); + } + synchronized (dbFile) { + try { + final PreparedStatement ps = bs.prepareStatement(getConnection()); + ps.execute(); + ps.close(); + } catch (final SQLException e) { + e.printStackTrace(); + } + } + } + } - /** - * Gets the database connection for executing queries on. - * - * @return The database connection - */ - @Override - public Connection getConnection() { - try { - // If we have a current connection, fetch it - if (this.connection != null && !this.connection.isClosed()) { - return this.connection; - } - } catch (final SQLException e) { - e.printStackTrace(); - } - if (this.dbFile.exists()) { - // So we need a new connection - try { - Class.forName("org.sqlite.JDBC"); - this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.dbFile); - return this.connection; - } catch (final ClassNotFoundException e) { - e.printStackTrace(); - return null; - } catch (final SQLException e) { - e.printStackTrace(); - return null; - } - } - // So we need a new file too. - try { - // Create the file - this.dbFile.createNewFile(); - // Now we won't need a new file, just a connection. - // This will return that new connection. - return this.getConnection(); - } catch (final IOException e) { - e.printStackTrace(); - return null; - } - } + /** + * Gets the database connection for executing queries on. + * + * @return The database connection + */ + @Override + public Connection getConnection() { + try { + // If we have a current connection, fetch it + if (this.connection != null && !this.connection.isClosed()) { + return this.connection; + } + } catch (final SQLException e) { + e.printStackTrace(); + } + if (this.dbFile.exists()) { + // So we need a new connection + try { + Class.forName("org.sqlite.JDBC"); + this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.dbFile); + return this.connection; + } catch (final ClassNotFoundException e) { + e.printStackTrace(); + return null; + } catch (final SQLException e) { + e.printStackTrace(); + return null; + } + } + // So we need a new file too. + try { + // Create the file + this.dbFile.createNewFile(); + // Now we won't need a new file, just a connection. + // This will return that new connection. + return this.getConnection(); + } catch (final IOException e) { + e.printStackTrace(); + return null; + } + } - @Override - public void queue(final BufferStatement bs) { - synchronized (queue) { - queue.add(bs); - } - if (watcher == null || !watcher.isAlive()) { - startWatcher(); - } - } + @Override + public void queue(final BufferStatement bs) { + synchronized (queue) { + queue.add(bs); + } + if (watcher == null || !watcher.isAlive()) { + startWatcher(); + } + } - private void startWatcher() { - watcher = new Thread() { - @Override - public void run() { - try { - Thread.sleep(30000); - } catch (final InterruptedException e) { - } - flush(); - } - }; - watcher.start(); - } + private void startWatcher() { + watcher = new Thread() { + @Override + public void run() { + try { + Thread.sleep(30000); + } catch (final InterruptedException e) { + } + flush(); + } + }; + watcher.start(); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Economy/Economy.java b/src/main/java/org/maxgamer/QuickShop/Economy/Economy.java index abb2826..f3567eb 100644 --- a/src/main/java/org/maxgamer/QuickShop/Economy/Economy.java +++ b/src/main/java/org/maxgamer/QuickShop/Economy/Economy.java @@ -3,129 +3,129 @@ package org.maxgamer.QuickShop.Economy; import java.util.UUID; public class Economy implements EconomyCore { - private final EconomyCore core; + private final EconomyCore core; - public Economy(final EconomyCore core) { - this.core = core; - } + public Economy(final EconomyCore core) { + this.core = core; + } - @Override - public String currencyNamePlural() { - return this.core.currencyNamePlural(); - } + @Override + public String currencyNamePlural() { + return this.core.currencyNamePlural(); + } - /** - * Deposits a given amount of money from thin air to the given username. - * - * @param name - * The exact (case insensitive) username to give money to - * @param amount - * The amount to give them - * @return True if success (Should be almost always) - */ - @Override - @Deprecated - public boolean deposit(final String name, final double amount) { - return this.core.deposit(name, amount); - } + /** + * Deposits a given amount of money from thin air to the given username. + * + * @param name + * The exact (case insensitive) username to give money to + * @param amount + * The amount to give them + * @return True if success (Should be almost always) + */ + @Override + @Deprecated + public boolean deposit(final String name, final double amount) { + return this.core.deposit(name, amount); + } - @Override - public boolean deposit(final UUID name, final double amount) { - return this.core.deposit(name, amount); - } + @Override + public boolean deposit(final UUID name, final double amount) { + return this.core.deposit(name, amount); + } - /** - * Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50 - * Dollars 5 Cents - * - * @param balance - * The given number - * @return The balance in human readable text. - */ - @Override - public String format(final double balance) { - return this.core.format(balance); - } + /** + * Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50 + * Dollars 5 Cents + * + * @param balance + * The given number + * @return The balance in human readable text. + */ + @Override + public String format(final double balance) { + return this.core.format(balance); + } - /** - * Fetches the balance of the given account name - * - * @param name - * The name of the account - * @return Their current balance. - */ - @Override - @Deprecated - public double getBalance(final String name) { - return this.core.getBalance(name); - } + /** + * Fetches the balance of the given account name + * + * @param name + * The name of the account + * @return Their current balance. + */ + @Override + @Deprecated + public double getBalance(final String name) { + return this.core.getBalance(name); + } - @Override - public double getBalance(final UUID name) { - return this.core.getBalance(name); - } + @Override + public double getBalance(final UUID name) { + return this.core.getBalance(name); + } - @Deprecated - public boolean has(final String name, final double amount) { - return this.core.getBalance(name) >= amount; - } + @Deprecated + public boolean has(final String name, final double amount) { + return this.core.getBalance(name) >= amount; + } - /** - * Checks that this economy is valid. Returns false if it is not valid. - * - * @return True if this economy will work, false if it will not. - */ - @Override - public boolean isValid() { - return this.core.isValid(); - } + /** + * Checks that this economy is valid. Returns false if it is not valid. + * + * @return True if this economy will work, false if it will not. + */ + @Override + public boolean isValid() { + return this.core.isValid(); + } - @Override - public String toString() { - return this.core.getClass().getName().split("_")[1]; - } + @Override + public String toString() { + return this.core.getClass().getName().split("_")[1]; + } - /** - * Transfers the given amount of money from Player1 to Player2 - * - * @param from - * The player who is paying money - * @param to - * The player who is receiving money - * @param amount - * The amount to transfer - * @return true if success (Payer had enough cash, receiver was able to - * receive the funds) - */ - @Override - @Deprecated - public boolean transfer(final String from, final String to, final double amount) { - return this.core.transfer(from, to, amount); - } + /** + * Transfers the given amount of money from Player1 to Player2 + * + * @param from + * The player who is paying money + * @param to + * The player who is receiving money + * @param amount + * The amount to transfer + * @return true if success (Payer had enough cash, receiver was able to + * receive the funds) + */ + @Override + @Deprecated + public boolean transfer(final String from, final String to, final double amount) { + return this.core.transfer(from, to, amount); + } - @Override - public boolean transfer(final UUID from, final UUID to, final double amount) { - return this.core.transfer(from, to, amount); - } + @Override + public boolean transfer(final UUID from, final UUID to, final double amount) { + return this.core.transfer(from, to, amount); + } - /** - * Withdraws a given amount of money from the given username and turns it to - * thin air. - * - * @param name - * The exact (case insensitive) username to take money from - * @param amount - * The amount to take from them - * @return True if success, false if they didn't have enough cash - */ - @Override - @Deprecated - public boolean withdraw(final String name, final double amount) { - return this.core.withdraw(name, amount); - } + /** + * Withdraws a given amount of money from the given username and turns it to + * thin air. + * + * @param name + * The exact (case insensitive) username to take money from + * @param amount + * The amount to take from them + * @return True if success, false if they didn't have enough cash + */ + @Override + @Deprecated + public boolean withdraw(final String name, final double amount) { + return this.core.withdraw(name, amount); + } - @Override - public boolean withdraw(final UUID name, final double amount) { - return this.core.withdraw(name, amount); - } + @Override + public boolean withdraw(final UUID name, final double amount) { + return this.core.withdraw(name, amount); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Economy/EconomyCore.java b/src/main/java/org/maxgamer/QuickShop/Economy/EconomyCore.java index 1d8269d..11b33a6 100644 --- a/src/main/java/org/maxgamer/QuickShop/Economy/EconomyCore.java +++ b/src/main/java/org/maxgamer/QuickShop/Economy/EconomyCore.java @@ -6,118 +6,118 @@ import java.util.UUID; * @author netherfoam Represents an economy. */ public interface EconomyCore { - public String currencyNamePlural(); + public String currencyNamePlural(); - /** - * Deposits a given amount of money from thin air to the given username. - * - * @param name - * The exact (case insensitive) username to give money to - * @param amount - * The amount to give them - * @return True if success (Should be almost always) - */ - @Deprecated - public boolean deposit(String name, double amount); + /** + * Deposits a given amount of money from thin air to the given username. + * + * @param name + * The exact (case insensitive) username to give money to + * @param amount + * The amount to give them + * @return True if success (Should be almost always) + */ + @Deprecated + public boolean deposit(String name, double amount); - /** - * Deposits a given amount of money from thin air to the given username. - * - * @param name - * The exact (case insensitive) username to give money to - * @param amount - * The amount to give them - * @return True if success (Should be almost always) - */ - public boolean deposit(UUID name, double amount); + /** + * Deposits a given amount of money from thin air to the given username. + * + * @param name + * The exact (case insensitive) username to give money to + * @param amount + * The amount to give them + * @return True if success (Should be almost always) + */ + public boolean deposit(UUID name, double amount); - /** - * Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50 - * Dollars 5 Cents - * - * @param balance - * The given number - * @return The balance in human readable text. - */ - public String format(double balance); + /** + * Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50 + * Dollars 5 Cents + * + * @param balance + * The given number + * @return The balance in human readable text. + */ + public String format(double balance); - /** - * Fetches the balance of the given account name - * - * @param name - * The name of the account - * @return Their current balance. - */ - @Deprecated - public double getBalance(String name); + /** + * Fetches the balance of the given account name + * + * @param name + * The name of the account + * @return Their current balance. + */ + @Deprecated + public double getBalance(String name); - /** - * Fetches the balance of the given account name - * - * @param name - * The name of the account - * @return Their current balance. - */ - public double getBalance(UUID name); + /** + * Fetches the balance of the given account name + * + * @param name + * The name of the account + * @return Their current balance. + */ + public double getBalance(UUID name); - /** - * Checks that this economy is valid. Returns false if it is not valid. - * - * @return True if this economy will work, false if it will not. - */ - public boolean isValid(); + /** + * Checks that this economy is valid. Returns false if it is not valid. + * + * @return True if this economy will work, false if it will not. + */ + public boolean isValid(); - /** - * Transfers the given amount of money from Player1 to Player2 - * - * @param from - * The player who is paying money - * @param to - * The player who is receiving money - * @param amount - * The amount to transfer - * @return true if success (Payer had enough cash, receiver was able to - * receive the funds) - */ - @Deprecated - public boolean transfer(String from, String to, double amount); + /** + * Transfers the given amount of money from Player1 to Player2 + * + * @param from + * The player who is paying money + * @param to + * The player who is receiving money + * @param amount + * The amount to transfer + * @return true if success (Payer had enough cash, receiver was able to + * receive the funds) + */ + @Deprecated + public boolean transfer(String from, String to, double amount); - /** - * Transfers the given amount of money from Player1 to Player2 - * - * @param from - * The player who is paying money - * @param to - * The player who is receiving money - * @param amount - * The amount to transfer - * @return true if success (Payer had enough cash, receiver was able to - * receive the funds) - */ - public boolean transfer(UUID from, UUID to, double amount); + /** + * Transfers the given amount of money from Player1 to Player2 + * + * @param from + * The player who is paying money + * @param to + * The player who is receiving money + * @param amount + * The amount to transfer + * @return true if success (Payer had enough cash, receiver was able to + * receive the funds) + */ + public boolean transfer(UUID from, UUID to, double amount); - /** - * Withdraws a given amount of money from the given username and turns it to - * thin air. - * - * @param name - * The exact (case insensitive) username to take money from - * @param amount - * The amount to take from them - * @return True if success, false if they didn't have enough cash - */ - @Deprecated - public boolean withdraw(String name, double amount); + /** + * Withdraws a given amount of money from the given username and turns it to + * thin air. + * + * @param name + * The exact (case insensitive) username to take money from + * @param amount + * The amount to take from them + * @return True if success, false if they didn't have enough cash + */ + @Deprecated + public boolean withdraw(String name, double amount); - /** - * Withdraws a given amount of money from the given username and turns it to - * thin air. - * - * @param name - * The exact (case insensitive) username to take money from - * @param amount - * The amount to take from them - * @return True if success, false if they didn't have enough cash - */ - public boolean withdraw(UUID name, double amount); + /** + * Withdraws a given amount of money from the given username and turns it to + * thin air. + * + * @param name + * The exact (case insensitive) username to take money from + * @param amount + * The amount to take from them + * @return True if success, false if they didn't have enough cash + */ + public boolean withdraw(UUID name, double amount); } diff --git a/src/main/java/org/maxgamer/QuickShop/Economy/Economy_Vault.java b/src/main/java/org/maxgamer/QuickShop/Economy/Economy_Vault.java index cde6244..af91816 100644 --- a/src/main/java/org/maxgamer/QuickShop/Economy/Economy_Vault.java +++ b/src/main/java/org/maxgamer/QuickShop/Economy/Economy_Vault.java @@ -9,108 +9,108 @@ import org.bukkit.plugin.RegisteredServiceProvider; import net.milkbowl.vault.economy.Economy; public class Economy_Vault implements EconomyCore { - private Economy vault; + private Economy vault; - public Economy_Vault() { - setupEconomy(); - } + public Economy_Vault() { + setupEconomy(); + } - @Override - public String currencyNamePlural() { - return this.vault.currencyNamePlural(); - } + @Override + public String currencyNamePlural() { + return this.vault.currencyNamePlural(); + } - @Override - @Deprecated - public boolean deposit(final String name, final double amount) { - return this.vault.depositPlayer(name, amount).transactionSuccess(); - } + @Override + @Deprecated + public boolean deposit(final String name, final double amount) { + return this.vault.depositPlayer(name, amount).transactionSuccess(); + } - @Override - public boolean deposit(final UUID name, final double amount) { - final OfflinePlayer p = Bukkit.getOfflinePlayer(name); - return this.vault.depositPlayer(p, amount).transactionSuccess(); - } + @Override + public boolean deposit(final UUID name, final double amount) { + final OfflinePlayer p = Bukkit.getOfflinePlayer(name); + return this.vault.depositPlayer(p, amount).transactionSuccess(); + } - @Override - public String format(final double balance) { - try { - return this.vault.format(balance); - } catch (final NumberFormatException e) { - } - return "" + balance; - } + @Override + public String format(final double balance) { + try { + return this.vault.format(balance); + } catch (final NumberFormatException e) { + } + return "" + balance; + } - @Override - @Deprecated - public double getBalance(final String name) { - return this.vault.getBalance(name); - } + @Override + @Deprecated + public double getBalance(final String name) { + return this.vault.getBalance(name); + } - @Override - public double getBalance(final UUID name) { - final OfflinePlayer p = Bukkit.getOfflinePlayer(name); - return this.vault.getBalance(p); - } + @Override + public double getBalance(final UUID name) { + final OfflinePlayer p = Bukkit.getOfflinePlayer(name); + return this.vault.getBalance(p); + } - @Override - public boolean isValid() { - return this.vault != null; - } + @Override + public boolean isValid() { + return this.vault != null; + } - @Override - @Deprecated - public boolean transfer(final String from, final String to, final double amount) { - if (this.vault.getBalance(from) >= amount) { - if (this.vault.withdrawPlayer(from, amount).transactionSuccess()) { - if (!this.vault.depositPlayer(to, amount).transactionSuccess()) { - this.vault.depositPlayer(from, amount); - return false; - } - return true; - } - return false; - } - return false; - } + @Override + @Deprecated + public boolean transfer(final String from, final String to, final double amount) { + if (this.vault.getBalance(from) >= amount) { + if (this.vault.withdrawPlayer(from, amount).transactionSuccess()) { + if (!this.vault.depositPlayer(to, amount).transactionSuccess()) { + this.vault.depositPlayer(from, amount); + return false; + } + return true; + } + return false; + } + return false; + } - @Override - public boolean transfer(final UUID from, final UUID to, final double amount) { - final OfflinePlayer pFrom = Bukkit.getOfflinePlayer(from); - final OfflinePlayer pTo = Bukkit.getOfflinePlayer(to); - if (this.vault.getBalance(pFrom) >= amount) { - if (this.vault.withdrawPlayer(pFrom, amount).transactionSuccess()) { - if (!this.vault.depositPlayer(pTo, amount).transactionSuccess()) { - this.vault.depositPlayer(pFrom, amount); - return false; - } - return true; - } - return false; - } - return false; - } + @Override + public boolean transfer(final UUID from, final UUID to, final double amount) { + final OfflinePlayer pFrom = Bukkit.getOfflinePlayer(from); + final OfflinePlayer pTo = Bukkit.getOfflinePlayer(to); + if (this.vault.getBalance(pFrom) >= amount) { + if (this.vault.withdrawPlayer(pFrom, amount).transactionSuccess()) { + if (!this.vault.depositPlayer(pTo, amount).transactionSuccess()) { + this.vault.depositPlayer(pFrom, amount); + return false; + } + return true; + } + return false; + } + return false; + } - @Override - @Deprecated - public boolean withdraw(final String name, final double amount) { - return this.vault.withdrawPlayer(name, amount).transactionSuccess(); - } + @Override + @Deprecated + public boolean withdraw(final String name, final double amount) { + return this.vault.withdrawPlayer(name, amount).transactionSuccess(); + } - @Override - public boolean withdraw(final UUID name, final double amount) { - final OfflinePlayer p = Bukkit.getOfflinePlayer(name); - return this.vault.withdrawPlayer(p, amount).transactionSuccess(); - } + @Override + public boolean withdraw(final UUID name, final double amount) { + final OfflinePlayer p = Bukkit.getOfflinePlayer(name); + return this.vault.withdrawPlayer(p, amount).transactionSuccess(); + } - private boolean setupEconomy() { - try { - final RegisteredServiceProvider economyProvider = Bukkit.getServicesManager().getRegistration(Economy.class); - if (economyProvider != null) { - vault = (economyProvider.getProvider()); - } - } catch (final Exception e) { - } - return vault != null; - } + private boolean setupEconomy() { + try { + final RegisteredServiceProvider economyProvider = Bukkit.getServicesManager().getRegistration(Economy.class); + if (economyProvider != null) { + vault = (economyProvider.getProvider()); + } + } catch (final Exception e) { + } + return vault != null; + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/BlockListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/BlockListener.java index 7d19182..781cfae 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/BlockListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/BlockListener.java @@ -23,100 +23,100 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import org.maxgamer.QuickShop.Util.Util; public class BlockListener implements Listener { - private final QuickShop plugin; + private final QuickShop plugin; - public BlockListener(final QuickShop plugin) { - this.plugin = plugin; - } + public BlockListener(final QuickShop plugin) { + this.plugin = plugin; + } - /** - * Removes chests when they're destroyed. - */ - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBreak(final BlockBreakEvent e) { - final Block b = e.getBlock(); - final Player p = e.getPlayer(); - // If the shop was a chest - if (b.getState() instanceof InventoryHolder) { - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) { - return; - } - // If they're either survival or the owner, they can break it - final ItemStack pinh = p.getItemInHand(); - if (p.getName().equals(shop.getOwner()) || p.getGameMode() == GameMode.SURVIVAL || pinh == null || pinh.getType() == plugin.getConfigManager().getSuperItem()) { - // Cancel their current menu... Doesnt cancel other's menu's. - final Info action = plugin.getShopManager().getActions().get(p.getName()); - if (action != null) { - action.setAction(ShopAction.CANCELLED); - } - shop.delete(); - p.sendMessage(MsgUtil.p("success-removed-shop")); - } else { - e.setCancelled(true); - p.sendMessage(MsgUtil.p("no-creative-break")); - return; - } - } else if (b.getType() == Material.WALL_SIGN) { - final Shop shop = getShopNextTo(b.getLocation()); - if (shop == null) { - return; - } - e.setCancelled(true); - } - } + /** + * Removes chests when they're destroyed. + */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBreak(final BlockBreakEvent e) { + final Block b = e.getBlock(); + final Player p = e.getPlayer(); + // If the shop was a chest + if (b.getState() instanceof InventoryHolder) { + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) { + return; + } + // If they're either survival or the owner, they can break it + final ItemStack pinh = p.getItemInHand(); + if (p.getName().equals(shop.getOwner()) || p.getGameMode() == GameMode.SURVIVAL || pinh == null || pinh.getType() == plugin.getConfigManager().getSuperItem()) { + // Cancel their current menu... Doesnt cancel other's menu's. + final Info action = plugin.getShopManager().getActions().get(p.getName()); + if (action != null) { + action.setAction(ShopAction.CANCELLED); + } + shop.delete(); + p.sendMessage(MsgUtil.p("success-removed-shop")); + } else { + e.setCancelled(true); + p.sendMessage(MsgUtil.p("no-creative-break")); + return; + } + } else if (b.getType() == Material.WALL_SIGN) { + final Shop shop = getShopNextTo(b.getLocation()); + if (shop == null) { + return; + } + e.setCancelled(true); + } + } - /** - * Handles shops breaking through explosions - */ - @EventHandler(priority = EventPriority.HIGHEST) - public void onExplode(final EntityExplodeEvent e) { - if (e.isCancelled()) { - return; - } - for (int i = 0; i < e.blockList().size(); i++) { - final Block b = e.blockList().get(i); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - shop.delete(); - } - } - } + /** + * Handles shops breaking through explosions + */ + @EventHandler(priority = EventPriority.HIGHEST) + public void onExplode(final EntityExplodeEvent e) { + if (e.isCancelled()) { + return; + } + for (int i = 0; i < e.blockList().size(); i++) { + final Block b = e.blockList().get(i); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + shop.delete(); + } + } + } - /** - * Listens for chest placement, so a doublechest shop can't be created. - */ - @EventHandler(ignoreCancelled = true) - public void onPlace(final BlockPlaceEvent e) { - if (e.isCancelled()) { - return; - } - final BlockState bs = e.getBlock().getState(); - if (bs instanceof DoubleChest == false) { - return; - } - final Block b = e.getBlock(); - final Player p = e.getPlayer(); - final Block chest = Util.getSecondHalf(b); - if (chest != null && plugin.getShopManager().getShop(chest.getLocation()) != null && !p.hasPermission("quickshop.create.double")) { - e.setCancelled(true); - p.sendMessage(MsgUtil.p("no-double-chests")); - } - } + /** + * Listens for chest placement, so a doublechest shop can't be created. + */ + @EventHandler(ignoreCancelled = true) + public void onPlace(final BlockPlaceEvent e) { + if (e.isCancelled()) { + return; + } + final BlockState bs = e.getBlock().getState(); + if (bs instanceof DoubleChest == false) { + return; + } + final Block b = e.getBlock(); + final Player p = e.getPlayer(); + final Block chest = Util.getSecondHalf(b); + if (chest != null && plugin.getShopManager().getShop(chest.getLocation()) != null && !p.hasPermission("quickshop.create.double")) { + e.setCancelled(true); + p.sendMessage(MsgUtil.p("no-double-chests")); + } + } - /** - * Gets the shop a sign is attached to - * - * @param loc - * The location of the sign - * @return The shop - */ - private Shop getShopNextTo(final Location loc) { - final Block b = Util.getAttached(loc.getBlock()); - // Util.getAttached(b) - if (b == null) { - return null; - } - return plugin.getShopManager().getShop(b.getLocation()); - } + /** + * Gets the shop a sign is attached to + * + * @param loc + * The location of the sign + * @return The shop + */ + private Shop getShopNextTo(final Location loc) { + final Block b = Util.getAttached(loc.getBlock()); + // Util.getAttached(b) + if (b == null) { + return null; + } + return plugin.getShopManager().getShop(b.getLocation()); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/ChatListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/ChatListener.java index bec95ae..21ec663 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/ChatListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/ChatListener.java @@ -12,18 +12,18 @@ import org.maxgamer.QuickShop.QuickShop; * */ public class ChatListener implements Listener { - QuickShop plugin; + QuickShop plugin; - public ChatListener(final QuickShop plugin) { - this.plugin = plugin; - } + public ChatListener(final QuickShop plugin) { + this.plugin = plugin; + } - @EventHandler(priority = EventPriority.LOWEST) - public void onChat(final AsyncPlayerChatEvent e) { - if (!plugin.getShopManager().getActions().containsKey(e.getPlayer().getName())) { - return; - } - plugin.getShopManager().handleChat(e.getPlayer(), e.getMessage()); - e.setCancelled(true); - } + @EventHandler(priority = EventPriority.LOWEST) + public void onChat(final AsyncPlayerChatEvent e) { + if (!plugin.getShopManager().getActions().containsKey(e.getPlayer().getName())) { + return; + } + plugin.getShopManager().handleChat(e.getPlayer(), e.getMessage()); + e.setCancelled(true); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/ChunkListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/ChunkListener.java index 39697e5..f8cc181 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/ChunkListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/ChunkListener.java @@ -13,33 +13,33 @@ import org.maxgamer.QuickShop.QuickShop; import org.maxgamer.QuickShop.Shop.Shop; public class ChunkListener implements Listener { - private QuickShop plugin; + private QuickShop plugin; - public ChunkListener(QuickShop plugin) { - this.plugin = plugin; - } + public ChunkListener(QuickShop plugin) { + this.plugin = plugin; + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onChunkLoad(ChunkLoadEvent e) { - Chunk c = e.getChunk(); - if (plugin.getShopManager().getShops() == null) - return; - HashMap inChunk = plugin.getShopManager().getShops(c); - if (inChunk == null) - return; - for (Shop shop : inChunk.values()) { - shop.onLoad(); - } - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onChunkLoad(ChunkLoadEvent e) { + Chunk c = e.getChunk(); + if (plugin.getShopManager().getShops() == null) + return; + HashMap inChunk = plugin.getShopManager().getShops(c); + if (inChunk == null) + return; + for (Shop shop : inChunk.values()) { + shop.onLoad(); + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onChunkUnload(ChunkUnloadEvent e) { - Chunk c = e.getChunk(); - HashMap inChunk = plugin.getShopManager().getShops(c); - if (inChunk == null) - return; - for (Shop shop : inChunk.values()) { - shop.onUnload(); - } - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onChunkUnload(ChunkUnloadEvent e) { + Chunk c = e.getChunk(); + HashMap inChunk = plugin.getShopManager().getShops(c); + if (inChunk == null) + return; + for (Shop shop : inChunk.values()) { + shop.onUnload(); + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/LockListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/LockListener.java index 0b9acb3..fa33e39 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/LockListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/LockListener.java @@ -17,133 +17,133 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import org.maxgamer.QuickShop.Util.Util; public class LockListener implements Listener { - private final QuickShop plugin; + private final QuickShop plugin; - public LockListener(final QuickShop plugin) { - this.plugin = plugin; - } + public LockListener(final QuickShop plugin) { + this.plugin = plugin; + } - /** - * Removes chests when they're destroyed. - */ - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBreak(final BlockBreakEvent e) { - Block b = e.getBlock(); - final Player p = e.getPlayer(); - // If the chest was a chest - if (Util.canBeShop(b)) { - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) { - return; // Wasn't a shop - } - // If they owned it or have bypass perms, they can destroy it - if (!shop.getOwner().equals(p.getName()) && !p.hasPermission("quickshop.other.destroy")) { - e.setCancelled(true); - p.sendMessage(MsgUtil.p("no-permission")); - return; - } - } else if (b.getType() == Material.WALL_SIGN) { - b = Util.getAttached(b); - if (b == null) { - return; - } - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) { - return; - } - e.setCancelled(true); - } - } + /** + * Removes chests when they're destroyed. + */ + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBreak(final BlockBreakEvent e) { + Block b = e.getBlock(); + final Player p = e.getPlayer(); + // If the chest was a chest + if (Util.canBeShop(b)) { + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) { + return; // Wasn't a shop + } + // If they owned it or have bypass perms, they can destroy it + if (!shop.getOwner().equals(p.getName()) && !p.hasPermission("quickshop.other.destroy")) { + e.setCancelled(true); + p.sendMessage(MsgUtil.p("no-permission")); + return; + } + } else if (b.getType() == Material.WALL_SIGN) { + b = Util.getAttached(b); + if (b == null) { + return; + } + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) { + return; + } + e.setCancelled(true); + } + } - @EventHandler(ignoreCancelled = true) - public void onClick(final PlayerInteractEvent e) { - Block b = e.getClickedBlock(); - final Player p = e.getPlayer(); - if (e.getAction() != Action.RIGHT_CLICK_BLOCK) { - return; // Didn't right click it, we dont care. - } - if (!Util.canBeShop(b)) { - return; // Interacted with air - } - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - // Make sure they're not using the non-shop half of a double chest. - if (shop == null) { - b = Util.getSecondHalf(b); - if (b == null) { - return; - } - shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) { - return; - } - } - if (!shop.getOwner().equals(p.getName())) { - if (p.hasPermission("quickshop.other.open")) { - p.sendMessage(MsgUtil.p("bypassing-lock")); - return; - } - p.sendMessage(MsgUtil.p("that-is-locked")); - e.setCancelled(true); - return; - } - } + @EventHandler(ignoreCancelled = true) + public void onClick(final PlayerInteractEvent e) { + Block b = e.getClickedBlock(); + final Player p = e.getPlayer(); + if (e.getAction() != Action.RIGHT_CLICK_BLOCK) { + return; // Didn't right click it, we dont care. + } + if (!Util.canBeShop(b)) { + return; // Interacted with air + } + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + // Make sure they're not using the non-shop half of a double chest. + if (shop == null) { + b = Util.getSecondHalf(b); + if (b == null) { + return; + } + shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) { + return; + } + } + if (!shop.getOwner().equals(p.getName())) { + if (p.hasPermission("quickshop.other.open")) { + p.sendMessage(MsgUtil.p("bypassing-lock")); + return; + } + p.sendMessage(MsgUtil.p("that-is-locked")); + e.setCancelled(true); + return; + } + } - /** - * Handles shops breaking through explosions - */ - @EventHandler(priority = EventPriority.LOW) - public void onExplode(final EntityExplodeEvent e) { - if (e.isCancelled()) { - return; - } - for (int i = 0; i < e.blockList().size(); i++) { - final Block b = e.blockList().get(i); - final Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - // ToDo: Shouldn't I be decrementing 1 here? Concurrency and - // all.. - e.blockList().remove(b); - } - } - } + /** + * Handles shops breaking through explosions + */ + @EventHandler(priority = EventPriority.LOW) + public void onExplode(final EntityExplodeEvent e) { + if (e.isCancelled()) { + return; + } + for (int i = 0; i < e.blockList().size(); i++) { + final Block b = e.blockList().get(i); + final Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + // ToDo: Shouldn't I be decrementing 1 here? Concurrency and + // all.. + e.blockList().remove(b); + } + } + } - /** - * Handles hopper placement - */ - @EventHandler(priority = EventPriority.LOW) - public void onPlace(final BlockPlaceEvent e) { - final Block b = e.getBlock(); - try { - if (b.getType() != Material.HOPPER) { - return; - } - } catch (final NoSuchFieldError er) { - return; // Your server doesn't have hoppers - } - Block c = e.getBlockAgainst(); - if (Util.canBeShop(c) == false) { - return; - } - final Player p = e.getPlayer(); - Shop shop = plugin.getShopManager().getShop(c.getLocation()); - if (shop == null) { - c = Util.getSecondHalf(c); - if (c == null) { - return; // You didn't place a hopper on a shop. Meh. - } - shop = plugin.getShopManager().getShop(c.getLocation()); - if (shop == null) { - return; - } - } - if (p.getName().equals(shop.getOwner()) == false) { - if (p.hasPermission("quickshop.other.open")) { - p.sendMessage(MsgUtil.p("bypassing-lock")); - return; - } - p.sendMessage(MsgUtil.p("that-is-locked")); - e.setCancelled(true); - return; - } - } + /** + * Handles hopper placement + */ + @EventHandler(priority = EventPriority.LOW) + public void onPlace(final BlockPlaceEvent e) { + final Block b = e.getBlock(); + try { + if (b.getType() != Material.HOPPER) { + return; + } + } catch (final NoSuchFieldError er) { + return; // Your server doesn't have hoppers + } + Block c = e.getBlockAgainst(); + if (Util.canBeShop(c) == false) { + return; + } + final Player p = e.getPlayer(); + Shop shop = plugin.getShopManager().getShop(c.getLocation()); + if (shop == null) { + c = Util.getSecondHalf(c); + if (c == null) { + return; // You didn't place a hopper on a shop. Meh. + } + shop = plugin.getShopManager().getShop(c.getLocation()); + if (shop == null) { + return; + } + } + if (p.getName().equals(shop.getOwner()) == false) { + if (p.hasPermission("quickshop.other.open")) { + p.sendMessage(MsgUtil.p("bypassing-lock")); + return; + } + p.sendMessage(MsgUtil.p("that-is-locked")); + e.setCancelled(true); + return; + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/PlayerListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/PlayerListener.java index d3639d7..9407105 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/PlayerListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/PlayerListener.java @@ -29,173 +29,173 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import org.maxgamer.QuickShop.Util.Util; public class PlayerListener implements Listener { - private final QuickShop plugin; + private final QuickShop plugin; - public PlayerListener(final QuickShop plugin) { - this.plugin = plugin; - } + public PlayerListener(final QuickShop plugin) { + this.plugin = plugin; + } - @SuppressWarnings("deprecation") - /** - * Handles players left clicking a chest. Left click a NORMAL chest with - * item : Send creation menu Left click a SHOP chest : Send purchase menu - */ - @EventHandler(priority = EventPriority.MONITOR) - public void onClick(final PlayerInteractEvent e) { - final Block b = e.getClickedBlock(); - final Player p = e.getPlayer(); - if (e.getAction() != Action.LEFT_CLICK_BLOCK || (e.getMaterial() == plugin.getConfigManager().getSuperItem() && b.getType() == Material.WALL_SIGN)) { - return; - } - final Location loc = b.getLocation(); - final ItemStack item = e.getItem(); - // Get the shop - Shop shop = plugin.getShopManager().getShop(loc); - // If that wasn't a shop, search nearby shops - if (shop == null && b.getType() == Material.WALL_SIGN) { - final Block attached = Util.getAttached(b); - if (attached != null) { - shop = plugin.getShopManager().getShop(attached.getLocation()); - } - } - // Purchase handling - if (shop != null && p.hasPermission("quickshop.use") && (plugin.getConfigManager().isSneakTrade() == p.isSneaking())) { - shop.onClick(); - // Text menu - MsgUtil.sendShopInfo(p, shop); - if (!plugin.getConfigManager().isEnableMagicLib() && b.getType() == Material.WALL_SIGN) { - final Inventory in = Bukkit.createInventory(null, 9, plugin.getConfigManager().getGuiTitle()); - in.setItem(4, shop.getItem()); - p.openInventory(in); - } - // Add the new action - final HashMap actions = plugin.getShopManager().getActions(); - final Info info = new Info(shop.getLocation(), ShopAction.BUY, null, null, shop); - actions.put(p.getName(), info); - return; - } - // Handles creating shops - else if (shop == null && item != null && item.getType() != Material.AIR && p.hasPermission("quickshop.create.sell") && Util.canBeShop(b) && p.getGameMode() != GameMode.CREATIVE - && (plugin.getConfigManager().isSneakCreate() == p.isSneaking())) { - if (!plugin.getShopManager().canBuildShop(p, b, e.getBlockFace())) { - // As of the new checking system, most plugins will tell the - // player why they can't create a shop there. - // So telling them a message would cause spam etc. - return; - } - if (Util.getSecondHalf(b) != null && !p.hasPermission("quickshop.create.double")) { - p.sendMessage(MsgUtil.p("no-double-chests")); - return; - } - if (Util.isBlacklisted(item.getType()) && !p.hasPermission("quickshop.bypass." + item.getTypeId())) { - p.sendMessage(MsgUtil.p("blacklisted-item")); - return; - } - // Finds out where the sign should be placed for the shop - Block last = null; - final Location from = p.getLocation().clone(); - from.setY(b.getY()); - from.setPitch(0); - final BlockIterator bIt = new BlockIterator(from, 0, 7); - while (bIt.hasNext()) { - final Block n = bIt.next(); - if (n.equals(b)) { - break; - } - last = n; - } - // Send creation menu. - final Info info = new Info(b.getLocation(), ShopAction.CREATE, e.getItem(), last); - plugin.getShopManager().getActions().put(p.getName(), info); - p.sendMessage(MsgUtil.p("how-much-to-trade-for", Util.getName(info.getItem()))); - } - } + @SuppressWarnings("deprecation") + /** + * Handles players left clicking a chest. Left click a NORMAL chest with + * item : Send creation menu Left click a SHOP chest : Send purchase menu + */ + @EventHandler(priority = EventPriority.MONITOR) + public void onClick(final PlayerInteractEvent e) { + final Block b = e.getClickedBlock(); + final Player p = e.getPlayer(); + if (e.getAction() != Action.LEFT_CLICK_BLOCK || (e.getMaterial() == plugin.getConfigManager().getSuperItem() && b.getType() == Material.WALL_SIGN)) { + return; + } + final Location loc = b.getLocation(); + final ItemStack item = e.getItem(); + // Get the shop + Shop shop = plugin.getShopManager().getShop(loc); + // If that wasn't a shop, search nearby shops + if (shop == null && b.getType() == Material.WALL_SIGN) { + final Block attached = Util.getAttached(b); + if (attached != null) { + shop = plugin.getShopManager().getShop(attached.getLocation()); + } + } + // Purchase handling + if (shop != null && p.hasPermission("quickshop.use") && (plugin.getConfigManager().isSneakTrade() == p.isSneaking())) { + shop.onClick(); + // Text menu + MsgUtil.sendShopInfo(p, shop); + if (!plugin.getConfigManager().isEnableMagicLib() && b.getType() == Material.WALL_SIGN) { + final Inventory in = Bukkit.createInventory(null, 9, plugin.getConfigManager().getGuiTitle()); + in.setItem(4, shop.getItem()); + p.openInventory(in); + } + // Add the new action + final HashMap actions = plugin.getShopManager().getActions(); + final Info info = new Info(shop.getLocation(), ShopAction.BUY, null, null, shop); + actions.put(p.getName(), info); + return; + } + // Handles creating shops + else if (shop == null && item != null && item.getType() != Material.AIR && p.hasPermission("quickshop.create.sell") && Util.canBeShop(b) && p.getGameMode() != GameMode.CREATIVE + && (plugin.getConfigManager().isSneakCreate() == p.isSneaking())) { + if (!plugin.getShopManager().canBuildShop(p, b, e.getBlockFace())) { + // As of the new checking system, most plugins will tell the + // player why they can't create a shop there. + // So telling them a message would cause spam etc. + return; + } + if (Util.getSecondHalf(b) != null && !p.hasPermission("quickshop.create.double")) { + p.sendMessage(MsgUtil.p("no-double-chests")); + return; + } + if (Util.isBlacklisted(item.getType()) && !p.hasPermission("quickshop.bypass." + item.getTypeId())) { + p.sendMessage(MsgUtil.p("blacklisted-item")); + return; + } + // Finds out where the sign should be placed for the shop + Block last = null; + final Location from = p.getLocation().clone(); + from.setY(b.getY()); + from.setPitch(0); + final BlockIterator bIt = new BlockIterator(from, 0, 7); + while (bIt.hasNext()) { + final Block n = bIt.next(); + if (n.equals(b)) { + break; + } + last = n; + } + // Send creation menu. + final Info info = new Info(b.getLocation(), ShopAction.CREATE, e.getItem(), last); + plugin.getShopManager().getActions().put(p.getName(), info); + p.sendMessage(MsgUtil.p("how-much-to-trade-for", Util.getName(info.getItem()))); + } + } - @EventHandler - public void onJoin(final PlayerJoinEvent e) { - // Notify the player any messages they were sent - Bukkit.getScheduler().runTaskLater(QuickShop.instance, new Runnable() { - @Override - public void run() { - MsgUtil.flush(e.getPlayer()); - } - }, 60); - } + @EventHandler + public void onJoin(final PlayerJoinEvent e) { + // Notify the player any messages they were sent + Bukkit.getScheduler().runTaskLater(QuickShop.instance, new Runnable() { + @Override + public void run() { + MsgUtil.flush(e.getPlayer()); + } + }, 60); + } - /** - * Waits for a player to move too far from a shop, then cancels the menu. - */ - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(final PlayerMoveEvent e) { - final Info info = plugin.getShopManager().getActions().get(e.getPlayer().getName()); - if (info != null) { - final Player p = e.getPlayer(); - final Location loc1 = info.getLocation(); - final Location loc2 = p.getLocation(); - if (loc1.getWorld() != loc2.getWorld() || loc1.distanceSquared(loc2) > 25) { - if (info.getAction() == ShopAction.CREATE) { - p.sendMessage(MsgUtil.p("shop-creation-cancelled")); - } else if (info.getAction() == ShopAction.BUY) { - p.sendMessage(MsgUtil.p("shop-purchase-cancelled")); - } - plugin.getShopManager().getActions().remove(p.getName()); - return; - } - } - } + /** + * Waits for a player to move too far from a shop, then cancels the menu. + */ + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(final PlayerMoveEvent e) { + final Info info = plugin.getShopManager().getActions().get(e.getPlayer().getName()); + if (info != null) { + final Player p = e.getPlayer(); + final Location loc1 = info.getLocation(); + final Location loc2 = p.getLocation(); + if (loc1.getWorld() != loc2.getWorld() || loc1.distanceSquared(loc2) > 25) { + if (info.getAction() == ShopAction.CREATE) { + p.sendMessage(MsgUtil.p("shop-creation-cancelled")); + } else if (info.getAction() == ShopAction.BUY) { + p.sendMessage(MsgUtil.p("shop-purchase-cancelled")); + } + plugin.getShopManager().getActions().remove(p.getName()); + return; + } + } + } - @EventHandler - public void onPlayerQuit(final PlayerQuitEvent e) { - // Remove them from the menu - plugin.getShopManager().getActions().remove(e.getPlayer().getName()); - } + @EventHandler + public void onPlayerQuit(final PlayerQuitEvent e) { + // Remove them from the menu + plugin.getShopManager().getActions().remove(e.getPlayer().getName()); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onSuperItemClick(final PlayerInteractEvent e) { - final Player p = e.getPlayer(); - if (p.getGameMode() != GameMode.SURVIVAL || e.getMaterial() != plugin.getConfigManager().getSuperItem()) { - return; - } - final Block b = e.getClickedBlock(); - if (b == null || b.getType() == null) { - return; - } - // If that wasn't a shop, search nearby shops - if (b.getType() == Material.WALL_SIGN) { - final Block attached = Util.getAttached(b); - final Shop shop = attached == null ? null : plugin.getShopManager().getShop(attached.getLocation()); - if (shop != null) { - final Location loc = shop.getLocation(); - String shopmode = ""; - if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (p.hasPermission("quickshop.unlimited") && (shop.getOwner().equalsIgnoreCase(p.getName()) || p.isOp())) { - shop.setUnlimited(!shop.isUnlimited()); - shopmode = shop.isUnlimited() ? "§e无限模式" : "§c有限模式"; - p.sendMessage(MsgUtil.p("command.toggle-unlimited", shopmode)); - } - } else { - if (shop.getShopType() == ShopType.BUYING && p.hasPermission("quickshop.create.sell") && (shop.getOwner().equalsIgnoreCase(p.getName()) || p.isOp())) { - shop.setShopType(ShopType.SELLING); - p.sendMessage(MsgUtil.p("command.now-selling", shop.getDataName())); - shopmode = "出售模式"; - } else if (shop.getShopType() == ShopType.SELLING && p.hasPermission("quickshop.create.buy") && (shop.getOwner().equalsIgnoreCase(p.getName()) || p.isOp())) { - shop.setShopType(ShopType.BUYING); - p.sendMessage(MsgUtil.p("command.now-buying", shop.getDataName())); - shopmode = "收购模式"; - } - } - if (!shopmode.isEmpty()) { - plugin.log(String.format("玩家: %s 将 %s(%s,%s,%s) 的商店切换为 %s !", p.getName(), loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ(), shopmode)); - } - shop.setSignText(); - shop.update(); - } - } - } + @EventHandler(priority = EventPriority.MONITOR) + public void onSuperItemClick(final PlayerInteractEvent e) { + final Player p = e.getPlayer(); + if (p.getGameMode() != GameMode.SURVIVAL || e.getMaterial() != plugin.getConfigManager().getSuperItem()) { + return; + } + final Block b = e.getClickedBlock(); + if (b == null || b.getType() == null) { + return; + } + // If that wasn't a shop, search nearby shops + if (b.getType() == Material.WALL_SIGN) { + final Block attached = Util.getAttached(b); + final Shop shop = attached == null ? null : plugin.getShopManager().getShop(attached.getLocation()); + if (shop != null) { + final Location loc = shop.getLocation(); + String shopmode = ""; + if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (p.hasPermission("quickshop.unlimited") && (shop.getOwner().equalsIgnoreCase(p.getName()) || p.isOp())) { + shop.setUnlimited(!shop.isUnlimited()); + shopmode = shop.isUnlimited() ? "§e无限模式" : "§c有限模式"; + p.sendMessage(MsgUtil.p("command.toggle-unlimited", shopmode)); + } + } else { + if (shop.getShopType() == ShopType.BUYING && p.hasPermission("quickshop.create.sell") && (shop.getOwner().equalsIgnoreCase(p.getName()) || p.isOp())) { + shop.setShopType(ShopType.SELLING); + p.sendMessage(MsgUtil.p("command.now-selling", shop.getDataName())); + shopmode = "出售模式"; + } else if (shop.getShopType() == ShopType.SELLING && p.hasPermission("quickshop.create.buy") && (shop.getOwner().equalsIgnoreCase(p.getName()) || p.isOp())) { + shop.setShopType(ShopType.BUYING); + p.sendMessage(MsgUtil.p("command.now-buying", shop.getDataName())); + shopmode = "收购模式"; + } + } + if (!shopmode.isEmpty()) { + plugin.log(String.format("玩家: %s 将 %s(%s,%s,%s) 的商店切换为 %s !", p.getName(), loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ(), shopmode)); + } + shop.setSignText(); + shop.update(); + } + } + } - @EventHandler(ignoreCancelled = true) - public void onTeleport(final PlayerTeleportEvent e) { - final PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); - onMove(me); - } + @EventHandler(ignoreCancelled = true) + public void onTeleport(final PlayerTeleportEvent e) { + final PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); + onMove(me); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/ProtectListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/ProtectListener.java index 8b68e8c..78f30e6 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/ProtectListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/ProtectListener.java @@ -24,138 +24,138 @@ import org.maxgamer.QuickShop.Util.MarkUtil; public class ProtectListener implements Listener { - private final QuickShop plugin; + private final QuickShop plugin; - public ProtectListener(final QuickShop plugin) { - this.plugin = plugin; - } + public ProtectListener(final QuickShop plugin) { + this.plugin = plugin; + } - public Shop getShop(final Inventory inv) { - if (inv == null) { - return null; - } - InventoryHolder holder = inv.getHolder(); - if (holder instanceof DoubleChest) { - holder = ((DoubleChest) holder).getLeftSide(); - } + public Shop getShop(final Inventory inv) { + if (inv == null) { + return null; + } + InventoryHolder holder = inv.getHolder(); + if (holder instanceof DoubleChest) { + holder = ((DoubleChest) holder).getLeftSide(); + } - if (holder instanceof BlockState) { - final Block block = ((BlockState) holder).getBlock(); - final Shop sp = plugin.getShopManager().getShop(block.getLocation()); - if (sp != null) { - return sp; - } - } - return null; - } + if (holder instanceof BlockState) { + final Block block = ((BlockState) holder).getBlock(); + final Shop sp = plugin.getShopManager().getShop(block.getLocation()); + if (sp != null) { + return sp; + } + } + return null; + } - @EventHandler - public void onInvMove(final InventoryMoveItemEvent e) { - final ItemStack ci = e.getItem(); - if (MarkUtil.hasMark(ci)) { - e.setCancelled(true); - } - final Inventory src = e.getSource(); - final Inventory me = e.getInitiator(); - final Inventory des = e.getDestination(); - final Shop srcshop = getShop(src); - final Shop meshop = getShop(me); - final Shop desshop = getShop(des); - if ((srcshop != null && meshop == null) || (meshop != null && desshop == null) || (srcshop != null && desshop != null && srcshop.getOwner().equalsIgnoreCase(desshop.getOwner()))) { - e.setCancelled(true); - } - } + @EventHandler + public void onInvMove(final InventoryMoveItemEvent e) { + final ItemStack ci = e.getItem(); + if (MarkUtil.hasMark(ci)) { + e.setCancelled(true); + } + final Inventory src = e.getSource(); + final Inventory me = e.getInitiator(); + final Inventory des = e.getDestination(); + final Shop srcshop = getShop(src); + final Shop meshop = getShop(me); + final Shop desshop = getShop(des); + if ((srcshop != null && meshop == null) || (meshop != null && desshop == null) || (srcshop != null && desshop != null && srcshop.getOwner().equalsIgnoreCase(desshop.getOwner()))) { + e.setCancelled(true); + } + } - @EventHandler - public void onInvPickup(final InventoryPickupItemEvent e) { - if (!plugin.getConfigManager().isPreventHopper()) { - return; - } - final ItemStack ci = e.getItem().getItemStack(); - if (MarkUtil.hasMark(ci)) { - e.setCancelled(true); - } - } + @EventHandler + public void onInvPickup(final InventoryPickupItemEvent e) { + if (!plugin.getConfigManager().isPreventHopper()) { + return; + } + final ItemStack ci = e.getItem().getItemStack(); + if (MarkUtil.hasMark(ci)) { + e.setCancelled(true); + } + } - @EventHandler - public void onItemClick(final InventoryClickEvent e) { - final Player p = (Player) e.getWhoClicked(); - final ItemStack ci = e.getCurrentItem(); - final Inventory inv = e.getInventory(); - final int solt = e.getSlot(); - if (inv.getType() != InventoryType.PLAYER && inv.getType() != InventoryType.HOPPER) { - if (inv.getTitle().equalsIgnoreCase(plugin.getConfigManager().getGuiTitle())) { - e.setCancelled(true); - p.closeInventory(); - } - return; - } - try { - if (MarkUtil.hasMark(ci)) { - inv.setItem(solt, new ItemStack(Material.AIR)); - sendWarning(p, ci, "§d§l获取"); - p.closeInventory(); - } - } catch (final Exception ex) { - } - } + @EventHandler + public void onItemClick(final InventoryClickEvent e) { + final Player p = (Player) e.getWhoClicked(); + final ItemStack ci = e.getCurrentItem(); + final Inventory inv = e.getInventory(); + final int solt = e.getSlot(); + if (inv.getType() != InventoryType.PLAYER && inv.getType() != InventoryType.HOPPER) { + if (inv.getTitle().equalsIgnoreCase(plugin.getConfigManager().getGuiTitle())) { + e.setCancelled(true); + p.closeInventory(); + } + return; + } + try { + if (MarkUtil.hasMark(ci)) { + inv.setItem(solt, new ItemStack(Material.AIR)); + sendWarning(p, ci, "§d§l获取"); + p.closeInventory(); + } + } catch (final Exception ex) { + } + } - @EventHandler - public void onPlayerHandlerItem(final PlayerItemHeldEvent e) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { - @Override - public void run() { - final Player p = e.getPlayer(); - final PlayerInventory inv = p.getInventory(); - final ItemStack[] cis = inv.getArmorContents(); - for (int i = 0; i < cis.length; i++) { - final ItemStack itemStack = cis[i]; - if (MarkUtil.hasMark(itemStack)) { - cis[i] = new ItemStack(Material.AIR); - sendWarning(p, itemStack, "§e§l穿戴"); - } - } - inv.setArmorContents(cis); - final int newslot = e.getNewSlot(); - final ItemStack newItem = inv.getItem(newslot); - if (MarkUtil.hasMark(newItem)) { - inv.setItem(newslot, new ItemStack(Material.AIR)); - sendWarning(p, newItem, "§3§l使用"); - } - } - }); - } + @EventHandler + public void onPlayerHandlerItem(final PlayerItemHeldEvent e) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + final Player p = e.getPlayer(); + final PlayerInventory inv = p.getInventory(); + final ItemStack[] cis = inv.getArmorContents(); + for (int i = 0; i < cis.length; i++) { + final ItemStack itemStack = cis[i]; + if (MarkUtil.hasMark(itemStack)) { + cis[i] = new ItemStack(Material.AIR); + sendWarning(p, itemStack, "§e§l穿戴"); + } + } + inv.setArmorContents(cis); + final int newslot = e.getNewSlot(); + final ItemStack newItem = inv.getItem(newslot); + if (MarkUtil.hasMark(newItem)) { + inv.setItem(newslot, new ItemStack(Material.AIR)); + sendWarning(p, newItem, "§3§l使用"); + } + } + }); + } - @EventHandler - public void onPlayerPickup(final PlayerPickupItemEvent e) { - final ItemStack ci = e.getItem().getItemStack(); - if (MarkUtil.hasMark(ci)) { - e.setCancelled(true); - } - } + @EventHandler + public void onPlayerPickup(final PlayerPickupItemEvent e) { + final ItemStack ci = e.getItem().getItemStack(); + if (MarkUtil.hasMark(ci)) { + e.setCancelled(true); + } + } - private void clearIllegalItem(final Player player) { - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { - @Override - public void run() { - final Inventory inv = player.getInventory(); - int clearnum = 0; - for (final ItemStack itemStack : inv) { - if (MarkUtil.hasMark(itemStack)) { - inv.remove(itemStack); - clearnum++; - } - } - if (clearnum != 0) { - Bukkit.broadcastMessage(plugin.getConfigManager().getGuiTitle() + " §4提示 §d扫描完毕 §d已清理 §a" + player.getName() + " §c非法获取的物品 §4" + clearnum + " §c个物品..."); - } - } - }); - } + private void clearIllegalItem(final Player player) { + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + final Inventory inv = player.getInventory(); + int clearnum = 0; + for (final ItemStack itemStack : inv) { + if (MarkUtil.hasMark(itemStack)) { + inv.remove(itemStack); + clearnum++; + } + } + if (clearnum != 0) { + Bukkit.broadcastMessage(plugin.getConfigManager().getGuiTitle() + " §4提示 §d扫描完毕 §d已清理 §a" + player.getName() + " §c非法获取的物品 §4" + clearnum + " §c个物品..."); + } + } + }); + } - private void sendWarning(final Player p, final ItemStack ci, final String action) { - Bukkit.broadcastMessage(plugin.getConfigManager().getGuiTitle() + " §4警告 " + p.getDisplayName() + " §c非法 " + action + " " + ci.getItemMeta().getDisplayName()); - Bukkit.broadcastMessage(plugin.getConfigManager().getGuiTitle() + " §4提示 §d系统 §d已清理 §a" + p.getName() + " §c非法获取的物品 §a并扫描玩家背包..."); - clearIllegalItem(p); - } + private void sendWarning(final Player p, final ItemStack ci, final String action) { + Bukkit.broadcastMessage(plugin.getConfigManager().getGuiTitle() + " §4警告 " + p.getDisplayName() + " §c非法 " + action + " " + ci.getItemMeta().getDisplayName()); + Bukkit.broadcastMessage(plugin.getConfigManager().getGuiTitle() + " §4提示 §d系统 §d已清理 §a" + p.getName() + " §c非法获取的物品 §a并扫描玩家背包..."); + clearIllegalItem(p); + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Listeners/WorldListener.java b/src/main/java/org/maxgamer/QuickShop/Listeners/WorldListener.java index d2e0666..83aa829 100644 --- a/src/main/java/org/maxgamer/QuickShop/Listeners/WorldListener.java +++ b/src/main/java/org/maxgamer/QuickShop/Listeners/WorldListener.java @@ -15,70 +15,70 @@ import org.maxgamer.QuickShop.Shop.Shop; import org.maxgamer.QuickShop.Shop.ShopChunk; public class WorldListener implements Listener { - QuickShop plugin; + QuickShop plugin; - public WorldListener(final QuickShop plugin) { - this.plugin = plugin; - } + public WorldListener(final QuickShop plugin) { + this.plugin = plugin; + } - @EventHandler - public void onWorldLoad(final WorldLoadEvent e) { - /* - * ************************************* - * This listener fixes any broken world references. Such as hashmap - * lookups will fail, because the World reference is different, but the - * world value is the same. - * ************************************* - */ - final World world = e.getWorld(); - // New world data - final HashMap> inWorld = new HashMap>(1); - // Old world data - final HashMap> oldInWorld = plugin.getShopManager().getShops(world.getName()); - // Nothing in the old world, therefore we don't care. No locations to - // update. - if (oldInWorld == null) { - return; - } - for (final Entry> oldInChunk : oldInWorld.entrySet()) { - final HashMap inChunk = new HashMap(1); - // Put the new chunk were the old chunk was - inWorld.put(oldInChunk.getKey(), inChunk); - for (final Entry entry : oldInChunk.getValue().entrySet()) { - final Shop shop = entry.getValue(); - shop.getLocation().setWorld(world); - inChunk.put(shop.getLocation(), shop); - } - } - // Done - Now we can store the new world dataz! - plugin.getShopManager().getShops().put(world.getName(), inWorld); - // This is a workaround, because I don't get parsed chunk events when a - // world first loads.... - // So manually tell all of these shops they're loaded. - for (final Chunk chunk : world.getLoadedChunks()) { - final HashMap inChunk = plugin.getShopManager().getShops(chunk); - if (inChunk == null) { - continue; - } - for (final Shop shop : inChunk.values()) { - shop.onLoad(); - } - } - } + @EventHandler + public void onWorldLoad(final WorldLoadEvent e) { + /* + * ************************************* + * This listener fixes any broken world references. Such as hashmap + * lookups will fail, because the World reference is different, but the + * world value is the same. + * ************************************* + */ + final World world = e.getWorld(); + // New world data + final HashMap> inWorld = new HashMap>(1); + // Old world data + final HashMap> oldInWorld = plugin.getShopManager().getShops(world.getName()); + // Nothing in the old world, therefore we don't care. No locations to + // update. + if (oldInWorld == null) { + return; + } + for (final Entry> oldInChunk : oldInWorld.entrySet()) { + final HashMap inChunk = new HashMap(1); + // Put the new chunk were the old chunk was + inWorld.put(oldInChunk.getKey(), inChunk); + for (final Entry entry : oldInChunk.getValue().entrySet()) { + final Shop shop = entry.getValue(); + shop.getLocation().setWorld(world); + inChunk.put(shop.getLocation(), shop); + } + } + // Done - Now we can store the new world dataz! + plugin.getShopManager().getShops().put(world.getName(), inWorld); + // This is a workaround, because I don't get parsed chunk events when a + // world first loads.... + // So manually tell all of these shops they're loaded. + for (final Chunk chunk : world.getLoadedChunks()) { + final HashMap inChunk = plugin.getShopManager().getShops(chunk); + if (inChunk == null) { + continue; + } + for (final Shop shop : inChunk.values()) { + shop.onLoad(); + } + } + } - @EventHandler - public void onWorldUnload(final WorldUnloadEvent e) { - // This is a workaround, because I don't get parsed chunk events when a - // world unloads, I think... - // So manually tell all of these shops they're unloaded. - for (final Chunk chunk : e.getWorld().getLoadedChunks()) { - final HashMap inChunk = plugin.getShopManager().getShops(chunk); - if (inChunk == null) { - continue; - } - for (final Shop shop : inChunk.values()) { - shop.onUnload(); - } - } - } + @EventHandler + public void onWorldUnload(final WorldUnloadEvent e) { + // This is a workaround, because I don't get parsed chunk events when a + // world unloads, I think... + // So manually tell all of these shops they're unloaded. + for (final Chunk chunk : e.getWorld().getLoadedChunks()) { + final HashMap inChunk = plugin.getShopManager().getShops(chunk); + if (inChunk == null) { + continue; + } + for (final Shop shop : inChunk.values()) { + shop.onUnload(); + } + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/QuickShop.java b/src/main/java/org/maxgamer/QuickShop/QuickShop.java index b6686c7..71777da 100644 --- a/src/main/java/org/maxgamer/QuickShop/QuickShop.java +++ b/src/main/java/org/maxgamer/QuickShop/QuickShop.java @@ -57,337 +57,337 @@ import cn.citycraft.PluginHelper.utils.LocalUtil; import cn.citycraft.PluginHelper.utils.VersionChecker; public class QuickShop extends JavaPlugin { - /** 初始化 QuickShop 的接口 */ - public static QuickShop instance; - /** 插件的配置文件 */ - public FileConfig config; - // private HeroChatListener heroChatListener; - // Listeners (These don't) - /** The Config Manager used to read config */ - private ConfigManager configManager; - /** The database for storing all our data for persistence */ - private Database database; - /** The economy we hook into for transactions */ - private Economy economy; - private BukkitTask itemWatcherTask; - private LogWatcher logWatcher; - /** The Shop Manager used to store shops */ - private ShopManager shopManager; + /** 初始化 QuickShop 的接口 */ + public static QuickShop instance; + /** 插件的配置文件 */ + public FileConfig config; + // private HeroChatListener heroChatListener; + // Listeners (These don't) + /** The Config Manager used to read config */ + private ConfigManager configManager; + /** The database for storing all our data for persistence */ + private Database database; + /** The economy we hook into for transactions */ + private Economy economy; + private BukkitTask itemWatcherTask; + private LogWatcher logWatcher; + /** The Shop Manager used to store shops */ + private ShopManager shopManager; - /** - * Prints debug information if QuickShop is configured to do so. - * - * @param s - * The string to print. - */ - public void debug(final String s) { - if (!configManager.isDebug()) { - return; - } - this.getLogger().info(ChatColor.YELLOW + "[Debug] " + s); - } + /** + * Prints debug information if QuickShop is configured to do so. + * + * @param s + * The string to print. + */ + public void debug(final String s) { + if (!configManager.isDebug()) { + return; + } + this.getLogger().info(ChatColor.YELLOW + "[Debug] " + s); + } - @Override - public FileConfiguration getConfig() { - return config; - } + @Override + public FileConfiguration getConfig() { + return config; + } - public ConfigManager getConfigManager() { - return configManager; - } + public ConfigManager getConfigManager() { + return configManager; + } - /** - * @return Returns the database handler for queries etc. - */ - public Database getDB() { - return this.database; - } + /** + * @return Returns the database handler for queries etc. + */ + public Database getDB() { + return this.database; + } - /** - * Returns the economy for moving currency around - * - * @return The economy for moving currency around - */ - public EconomyCore getEcon() { - return economy; - } + /** + * Returns the economy for moving currency around + * + * @return The economy for moving currency around + */ + public EconomyCore getEcon() { + return economy; + } - public int getShopLimit(final Player p) { - int max = configManager.getLimitdefault(); - for (final Entry entry : configManager.getLimits().entrySet()) { - if (entry.getValue() > max && p.hasPermission(entry.getKey())) { - max = entry.getValue(); - } - } - return max; - } + public int getShopLimit(final Player p) { + int max = configManager.getLimitdefault(); + for (final Entry entry : configManager.getLimits().entrySet()) { + if (entry.getValue() > max && p.hasPermission(entry.getKey())) { + max = entry.getValue(); + } + } + return max; + } - /** - * Returns the ShopManager. This is used for fetching, adding and removing - * shops. - * - * @return The ShopManager. - */ - public ShopManager getShopManager() { - return this.shopManager; - } + /** + * Returns the ShopManager. This is used for fetching, adding and removing + * shops. + * + * @return The ShopManager. + */ + public ShopManager getShopManager() { + return this.shopManager; + } - /** - * Tries to load the economy and its core. If this fails, it will try to use - * vault. If that fails, it will return false. - * - * @return true if successful, false if the core is invalid or is not found, - * and vault cannot be used. - */ - public boolean loadEcon() { - final EconomyCore core = new Economy_Vault(); - if (!core.isValid()) { - getLogger().warning("无法找到经济管理类插件..."); - getLogger().warning("卸载插件!!!"); - this.getPluginLoader().disablePlugin(this); - return false; - } - this.economy = new Economy(core); - return true; - } + /** + * Tries to load the economy and its core. If this fails, it will try to use + * vault. If that fails, it will return false. + * + * @return true if successful, false if the core is invalid or is not found, + * and vault cannot be used. + */ + public boolean loadEcon() { + final EconomyCore core = new Economy_Vault(); + if (!core.isValid()) { + getLogger().warning("无法找到经济管理类插件..."); + getLogger().warning("卸载插件!!!"); + this.getPluginLoader().disablePlugin(this); + return false; + } + this.economy = new Economy(core); + return true; + } - public void loadShop() { - if (!LocalUtil.isInit()) { - this.getLogger().warning("本地化工具尚未初始化完成 商店汉化信息将在稍后刷新..."); - this.getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { - @Override - public void run() { - int error = 0; - try { - while (!LocalUtil.isInit()) { - try { - Thread.sleep(500); - } catch (final InterruptedException e) { - } - } - getLogger().info("本地化工具载入完成 刷新汉化信息..."); - final Iterator shops = shopManager.getShopIterator(); - while (shops.hasNext()) { - shops.next().onClick(); - } - } catch (final Exception e) { - error++; - } - if (error != 0) { - getLogger().info("信息刷新完成 期间发生 " + error + " 个错误 已忽略(不是BUG 无需反馈)..."); - } - } - }); - } - /* 从数据库载入商店信息到内存 */ - int count = 0; // 商店个数 - int unload = 0; - Connection con; - try { - getLogger().info("开始从数据库载入商店数据..."); - con = database.getConnection(); - final PreparedStatement ps = con.prepareStatement("SELECT * FROM shops"); - final ResultSet rs = ps.executeQuery(); - int errors = 0; - while (rs.next()) { - int x = 0; - int y = 0; - int z = 0; - String worldName = null; - try { - x = rs.getInt("x"); - y = rs.getInt("y"); - z = rs.getInt("z"); - worldName = rs.getString("world"); - final World world = Bukkit.getWorld(worldName); - final ItemStack item = Util.deserialize(rs.getString("itemConfig")); - final String owner = rs.getString("owner"); - final double price = rs.getDouble("price"); - final Location loc = new Location(world, x, y, z); - /* Skip invalid shops, if we know of any */ - if (world != null && loc.getChunk().isLoaded() && (loc.getBlock().getState() instanceof InventoryHolder) == false) { - getLogger().info("商店不是一个可存储的方块 坐标 " + rs.getString("world") + ", " + x + ", " + y + ", " + z + ". 删除..."); - database.execute("DELETE FROM shops WHERE x = ? AND y = ? and z = ? and world = ?", x, y, z, worldName); - continue; - } - final int type = rs.getInt("type"); - final Shop shop = new ContainerShop(loc, price, item, owner); - shop.setUnlimited(rs.getBoolean("unlimited")); - shop.setShopType(ShopType.fromID(type)); - shopManager.loadShop(rs.getString("world"), shop); - if (loc.getWorld() != null && loc.getChunk().isLoaded()) { - shop.onLoad(); - } - count++; - } catch (final IllegalStateException e) { - unload++; - } catch (final Exception e) { - errors++; - e.printStackTrace(); - getLogger().warning("载入商店数据时发生错误! 商店位置: " + worldName + " (" + x + ", " + y + ", " + z + ")..."); - if (errors < 3) { - getLogger().warning("删除错误的商店数据..."); - database.execute("DELETE FROM shops WHERE x = ? AND y = ? and z = ? and world = ?", x, y, z, worldName); - } else { - getLogger().warning("过多的错误数据 可能您的数据库文件已损坏! 请检查数据库文件!"); - e.printStackTrace(); - break; - } - } - } - } catch (final SQLException e) { - getLogger().warning("无法载入商店数据..."); - getLogger().warning("错误信息: " + e.getMessage()); - e.printStackTrace(); - } - getLogger().info("已载入 " + count + " 个商店 剩余 " + unload + " 个商店将在区块载入后加载..."); - } + public void loadShop() { + if (!LocalUtil.isInit()) { + this.getLogger().warning("本地化工具尚未初始化完成 商店汉化信息将在稍后刷新..."); + this.getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { + @Override + public void run() { + int error = 0; + try { + while (!LocalUtil.isInit()) { + try { + Thread.sleep(500); + } catch (final InterruptedException e) { + } + } + getLogger().info("本地化工具载入完成 刷新汉化信息..."); + final Iterator shops = shopManager.getShopIterator(); + while (shops.hasNext()) { + shops.next().onClick(); + } + } catch (final Exception e) { + error++; + } + if (error != 0) { + getLogger().info("信息刷新完成 期间发生 " + error + " 个错误 已忽略(不是BUG 无需反馈)..."); + } + } + }); + } + /* 从数据库载入商店信息到内存 */ + int count = 0; // 商店个数 + int unload = 0; + Connection con; + try { + getLogger().info("开始从数据库载入商店数据..."); + con = database.getConnection(); + final PreparedStatement ps = con.prepareStatement("SELECT * FROM shops"); + final ResultSet rs = ps.executeQuery(); + int errors = 0; + while (rs.next()) { + int x = 0; + int y = 0; + int z = 0; + String worldName = null; + try { + x = rs.getInt("x"); + y = rs.getInt("y"); + z = rs.getInt("z"); + worldName = rs.getString("world"); + final World world = Bukkit.getWorld(worldName); + final ItemStack item = Util.deserialize(rs.getString("itemConfig")); + final String owner = rs.getString("owner"); + final double price = rs.getDouble("price"); + final Location loc = new Location(world, x, y, z); + /* Skip invalid shops, if we know of any */ + if (world != null && loc.getChunk().isLoaded() && (loc.getBlock().getState() instanceof InventoryHolder) == false) { + getLogger().info("商店不是一个可存储的方块 坐标 " + rs.getString("world") + ", " + x + ", " + y + ", " + z + ". 删除..."); + database.execute("DELETE FROM shops WHERE x = ? AND y = ? and z = ? and world = ?", x, y, z, worldName); + continue; + } + final int type = rs.getInt("type"); + final Shop shop = new ContainerShop(loc, price, item, owner); + shop.setUnlimited(rs.getBoolean("unlimited")); + shop.setShopType(ShopType.fromID(type)); + shopManager.loadShop(rs.getString("world"), shop); + if (loc.getWorld() != null && loc.getChunk().isLoaded()) { + shop.onLoad(); + } + count++; + } catch (final IllegalStateException e) { + unload++; + } catch (final Exception e) { + errors++; + e.printStackTrace(); + getLogger().warning("载入商店数据时发生错误! 商店位置: " + worldName + " (" + x + ", " + y + ", " + z + ")..."); + if (errors < 3) { + getLogger().warning("删除错误的商店数据..."); + database.execute("DELETE FROM shops WHERE x = ? AND y = ? and z = ? and world = ?", x, y, z, worldName); + } else { + getLogger().warning("过多的错误数据 可能您的数据库文件已损坏! 请检查数据库文件!"); + e.printStackTrace(); + break; + } + } + } + } catch (final SQLException e) { + getLogger().warning("无法载入商店数据..."); + getLogger().warning("错误信息: " + e.getMessage()); + e.printStackTrace(); + } + getLogger().info("已载入 " + count + " 个商店 剩余 " + unload + " 个商店将在区块载入后加载..."); + } - /** - * Logs the given string to qs.log, if QuickShop is configured to do so. - * - * @param s - * The string to log. It will be prefixed with the date and time. - */ - public void log(final String s) { - if (this.logWatcher == null) { - return; - } - final Date date = Calendar.getInstance().getTime(); - final Timestamp time = new Timestamp(date.getTime()); - this.logWatcher.add("[" + time.toString() + "] " + s); - } + /** + * Logs the given string to qs.log, if QuickShop is configured to do so. + * + * @param s + * The string to log. It will be prefixed with the date and time. + */ + public void log(final String s) { + if (this.logWatcher == null) { + return; + } + final Date date = Calendar.getInstance().getTime(); + final Timestamp time = new Timestamp(date.getTime()); + this.logWatcher.add("[" + time.toString() + "] " + s); + } - @Override - public void onDisable() { - if (itemWatcherTask != null) { - itemWatcherTask.cancel(); - } - if (logWatcher != null) { - logWatcher.task.cancel(); - logWatcher.close(); // Closes the file - } - /* Remove all display items, and any dupes we can find */ - if (shopManager != null) { - shopManager.clear(); - } - /* Empty the buffer */ - if (database != null) { - database.close(); - try { - database.getConnection().close(); - } catch (final SQLException e) { - } - } - if (configManager != null) { - configManager.getWarnings().clear(); - } - } + @Override + public void onDisable() { + if (itemWatcherTask != null) { + itemWatcherTask.cancel(); + } + if (logWatcher != null) { + logWatcher.task.cancel(); + logWatcher.close(); // Closes the file + } + /* Remove all display items, and any dupes we can find */ + if (shopManager != null) { + shopManager.clear(); + } + /* Empty the buffer */ + if (database != null) { + database.close(); + try { + database.getConnection().close(); + } catch (final SQLException e) { + } + } + if (configManager != null) { + configManager.getWarnings().clear(); + } + } - @Override - public void onEnable() { - instance = this; - if (loadEcon() == false) { - return; - } - LocalUtil.init(this); - // Initialize Util - Util.initialize(); - // Create the shop manager. - configManager = new ConfigManager(this); - shopManager = new ShopManager(this); - if (configManager.isFakeItem()) { - if (!FakeItem.isRegistered()) { - try { - FakeItem.register(this); - } catch (final Exception e) { - } - } - } - if (configManager.isLogAction()) { - // Logger Handler - this.logWatcher = new LogWatcher(this, new File(this.getDataFolder(), "qs.log")); - logWatcher.task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, this.logWatcher, 150, 150); - } - if (configManager.isShopLock()) { - final LockListener ll = new LockListener(this); - getServer().getPluginManager().registerEvents(ll, this); - } - try { - final ConfigurationSection dbCfg = getConfig().getConfigurationSection("database"); - DatabaseCore dbCore; - if (dbCfg.getBoolean("mysql")) { - getLogger().info("启用MySQL 开始连接数据库..."); - // MySQL database - Required database be created first. - final String user = dbCfg.getString("user"); - final String pass = dbCfg.getString("password"); - final String host = dbCfg.getString("host"); - final String port = dbCfg.getString("port"); - final String database = dbCfg.getString("database"); - dbCore = new MySQLCore(host, user, pass, database, port); - } else { - // SQLite database - Doing this handles file creation - dbCore = new SQLiteCore(new File(this.getDataFolder(), "shops.db")); - } - this.database = new Database(dbCore); - // Make the database up to date - DatabaseHelper.setup(getDB()); - } catch (final Exception e) { - getLogger().warning("数据库连接错误或配置错误..."); - getLogger().warning("错误信息: " + e.getMessage()); - e.printStackTrace(); - getLogger().warning("关闭插件!!!"); - getServer().getPluginManager().disablePlugin(this); - return; - } - loadShop(); - MsgUtil.loadTransactionMessages(); - MsgUtil.clean(); - // Register events - final PluginManager pm = this.getServer().getPluginManager(); - final Plugin wsc = pm.getPlugin("WowSuchCleaner"); - if (wsc != null && wsc.isEnabled()) { - getLogger().info("发现 WowSuchCleaner 插件 开启相关功能..."); - try { - Class.forName("io.github.Cnly.WowSuchCleaner.WowSuchCleaner.ItemPreCleanEvent"); - pm.registerEvents(new WowSuchCleanerListener(), this); - } catch (final ClassNotFoundException e) { - getLogger().info("WowSuchCleaner 版本过低 可能造成悬浮物上架..."); - } - } - pm.registerEvents(new BlockListener(this), this); - pm.registerEvents(new PlayerListener(this), this); - pm.registerEvents(new WorldListener(this), this); - pm.registerEvents(new ProtectListener(this), this); - pm.registerEvents(new ChatListener(this), this); - if (configManager.isDisplay()) { - Bukkit.getServer().getPluginManager().registerEvents(new ChunkListener(this), this); - // Display item handler thread - getLogger().info("开启商店检查以及悬浮物刷新线程..."); - final ItemWatcher itemWatcher = new ItemWatcher(this); - itemWatcherTask = Bukkit.getScheduler().runTaskTimer(this, itemWatcher, 20, 1800); - } + @Override + public void onEnable() { + instance = this; + if (loadEcon() == false) { + return; + } + LocalUtil.init(this); + // Initialize Util + Util.initialize(); + // Create the shop manager. + configManager = new ConfigManager(this); + shopManager = new ShopManager(this); + if (configManager.isFakeItem()) { + if (!FakeItem.isRegistered()) { + try { + FakeItem.register(this); + } catch (final Exception e) { + } + } + } + if (configManager.isLogAction()) { + // Logger Handler + this.logWatcher = new LogWatcher(this, new File(this.getDataFolder(), "qs.log")); + logWatcher.task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, this.logWatcher, 150, 150); + } + if (configManager.isShopLock()) { + final LockListener ll = new LockListener(this); + getServer().getPluginManager().registerEvents(ll, this); + } + try { + final ConfigurationSection dbCfg = getConfig().getConfigurationSection("database"); + DatabaseCore dbCore; + if (dbCfg.getBoolean("mysql")) { + getLogger().info("启用MySQL 开始连接数据库..."); + // MySQL database - Required database be created first. + final String user = dbCfg.getString("user"); + final String pass = dbCfg.getString("password"); + final String host = dbCfg.getString("host"); + final String port = dbCfg.getString("port"); + final String database = dbCfg.getString("database"); + dbCore = new MySQLCore(host, user, pass, database, port); + } else { + // SQLite database - Doing this handles file creation + dbCore = new SQLiteCore(new File(this.getDataFolder(), "shops.db")); + } + this.database = new Database(dbCore); + // Make the database up to date + DatabaseHelper.setup(getDB()); + } catch (final Exception e) { + getLogger().warning("数据库连接错误或配置错误..."); + getLogger().warning("错误信息: " + e.getMessage()); + e.printStackTrace(); + getLogger().warning("关闭插件!!!"); + getServer().getPluginManager().disablePlugin(this); + return; + } + loadShop(); + MsgUtil.loadTransactionMessages(); + MsgUtil.clean(); + // Register events + final PluginManager pm = this.getServer().getPluginManager(); + final Plugin wsc = pm.getPlugin("WowSuchCleaner"); + if (wsc != null && wsc.isEnabled()) { + getLogger().info("发现 WowSuchCleaner 插件 开启相关功能..."); + try { + Class.forName("io.github.Cnly.WowSuchCleaner.WowSuchCleaner.ItemPreCleanEvent"); + pm.registerEvents(new WowSuchCleanerListener(), this); + } catch (final ClassNotFoundException e) { + getLogger().info("WowSuchCleaner 版本过低 可能造成悬浮物上架..."); + } + } + pm.registerEvents(new BlockListener(this), this); + pm.registerEvents(new PlayerListener(this), this); + pm.registerEvents(new WorldListener(this), this); + pm.registerEvents(new ProtectListener(this), this); + pm.registerEvents(new ChatListener(this), this); + if (configManager.isDisplay()) { + Bukkit.getServer().getPluginManager().registerEvents(new ChunkListener(this), this); + // Display item handler thread + getLogger().info("开启商店检查以及悬浮物刷新线程..."); + final ItemWatcher itemWatcher = new ItemWatcher(this); + itemWatcherTask = Bukkit.getScheduler().runTaskTimer(this, itemWatcher, 20, 1800); + } - // Command handlers - new QuickShopCommands(this); + // Command handlers + new QuickShopCommands(this); - if (configManager.getFindDistance() > 100) { - getLogger().warning("商店查找半径过大 可能导致服务器Lag! 推荐使用低于 100 的配置!"); - } - this.getLogger().info("载入完成! 版本: " + this.getDescription().getVersion() + " 重制 by 喵♂呜"); - new VersionChecker(this); - } + if (configManager.getFindDistance() > 100) { + getLogger().warning("商店查找半径过大 可能导致服务器Lag! 推荐使用低于 100 的配置!"); + } + this.getLogger().info("载入完成! 版本: " + this.getDescription().getVersion() + " 重制 by 喵♂呜"); + new VersionChecker(this); + } - @Override - public void onLoad() { - config = new FileConfig(this); - MsgUtil.init(this); - } + @Override + public void onLoad() { + config = new FileConfig(this); + MsgUtil.init(this); + } - /** Reloads QuickShops config */ - @Override - public void reloadConfig() { - config.reload(); - LocalUtil.reload(this); - } + /** Reloads QuickShops config */ + @Override + public void reloadConfig() { + config.reload(); + LocalUtil.reload(this); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ContainerShop.java b/src/main/java/org/maxgamer/QuickShop/Shop/ContainerShop.java index f9de264..0055e03 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ContainerShop.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ContainerShop.java @@ -23,697 +23,697 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import org.maxgamer.QuickShop.Util.Util; public class ContainerShop implements Shop { - private DisplayItem displayName; - private final ItemStack item; - private final Location loc; - private String owner; - private final QuickShop plugin; - private double price; - private ShopType shopType; - private boolean unlimited; + private DisplayItem displayItem; + private final ItemStack item; + private final Location loc; + private String owner; + private final QuickShop plugin; + private double price; + private ShopType shopType; + private boolean unlimited; - /** - * Adds a new shop. - * - * @param loc - * The location of the chest block - * @param price - * The cost per item - * @param item - * The itemstack with the properties we want. This is .cloned, no - * need to worry about references - * @param owner - * The player who owns this shop. - */ - public ContainerShop(final Location loc, final double price, final ItemStack item, final String owner) { - this.loc = loc; - this.price = price; - this.owner = owner; - this.item = item.clone(); - this.plugin = (QuickShop) Bukkit.getPluginManager().getPlugin("QuickShop"); - this.item.setAmount(1); - if (plugin.getConfigManager().isDisplay()) { - if (plugin.getConfigManager().isFakeItem()) { - this.displayName = new FakeItem(this, this.getItem()); - } else { - this.displayName = new NormalItem(this, this.getItem()); - } - } - this.shopType = ShopType.SELLING; - } + /** + * Adds a new shop. + * + * @param loc + * The location of the chest block + * @param price + * The cost per item + * @param item + * The itemstack with the properties we want. This is .cloned, no + * need to worry about references + * @param owner + * The player who owns this shop. + */ + public ContainerShop(final Location loc, final double price, final ItemStack item, final String owner) { + this.loc = loc; + this.price = price; + this.owner = owner; + this.item = item.clone(); + this.plugin = (QuickShop) Bukkit.getPluginManager().getPlugin("QuickShop"); + this.item.setAmount(1); + if (plugin.getConfigManager().isDisplay()) { + if (plugin.getConfigManager().isFakeItem()) { + this.displayItem = new FakeItem(this, this.getItem()); + } else { + this.displayItem = new NormalItem(this, this.getItem()); + } + } + this.shopType = ShopType.SELLING; + } - private ContainerShop(final ContainerShop s) { - this.displayName = s.displayName; - this.shopType = s.shopType; - this.item = s.item; - this.loc = s.loc; - this.plugin = s.plugin; - this.unlimited = s.unlimited; - this.owner = s.owner; - this.price = s.price; - } + private ContainerShop(final ContainerShop s) { + this.displayItem = s.displayItem; + this.shopType = s.shopType; + this.item = s.item; + this.loc = s.loc; + this.plugin = s.plugin; + this.unlimited = s.unlimited; + this.owner = s.owner; + this.price = s.price; + } - /** - * Add an item to shops chest. - * - * @param item - * The itemstack. The amount does not matter, just everything - * else - * @param amount - * The amount to add to the shop. - */ - @Override - public void add(final ItemStack item, final int amount) { - if (this.unlimited) { - return; - } - final Inventory inv = this.getInventory(); - int remains = amount; - while (remains > 0) { - final int stackSize = Math.min(remains, item.getMaxStackSize()); - item.setAmount(stackSize); - inv.addItem(item); - remains = remains - stackSize; - } - } + /** + * Add an item to shops chest. + * + * @param item + * The itemstack. The amount does not matter, just everything + * else + * @param amount + * The amount to add to the shop. + */ + @Override + public void add(final ItemStack item, final int amount) { + if (this.unlimited) { + return; + } + final Inventory inv = this.getInventory(); + int remains = amount; + while (remains > 0) { + final int stackSize = Math.min(remains, item.getMaxStackSize()); + item.setAmount(stackSize); + inv.addItem(item); + remains = remains - stackSize; + } + } - /** - * Buys amount of item from Player p. Does NOT check our inventory, or - * balances - * - * @param p - * The player to buy from - * @param item - * The itemStack to buy - * @param amount - * The amount to buy - */ - @Override - public void buy(final Player p, int amount) { - if (amount < 0) { - this.sell(p, -amount); - } - if (this.isUnlimited()) { - final ItemStack[] contents = p.getInventory().getContents(); - for (int i = 0; amount > 0 && i < contents.length; i++) { - final ItemStack stack = contents[i]; - if (stack == null) { - continue; // No item - } - if (matches(stack)) { - final int stackSize = Math.min(amount, stack.getAmount()); - stack.setAmount(stack.getAmount() - stackSize); - amount -= stackSize; - } - } - // Send the players new inventory to them - p.getInventory().setContents(contents); - // This should not happen. - if (amount > 0) { - plugin.getLogger().log(Level.WARNING, "Could not take all items from a players inventory on purchase! " + p.getName() + ", missing: " + amount + ", item: " + this.getDataName() + "!"); - } - } else { - final ItemStack[] playerContents = p.getInventory().getContents(); - final Inventory chestInv = this.getInventory(); - for (int i = 0; amount > 0 && i < playerContents.length; i++) { - ItemStack item = playerContents[i]; - if (item != null && this.matches(item)) { - // Copy it, we don't want to interfere - item = item.clone(); - // Amount = total, item.getAmount() = how many items in the - // stack - final int stackSize = Math.min(amount, item.getAmount()); - // If Amount is item.getAmount(), then this sets the amount - // to 0 - // Else it sets it to the remainder - playerContents[i].setAmount(playerContents[i].getAmount() - stackSize); - // We can modify this, it is a copy. - item.setAmount(stackSize); - // Add the items to the players inventory - chestInv.addItem(item); - amount -= stackSize; - } - } - // Now update the players inventory. - p.getInventory().setContents(playerContents); - } - } + /** + * Buys amount of item from Player p. Does NOT check our inventory, or + * balances + * + * @param p + * The player to buy from + * @param item + * The itemStack to buy + * @param amount + * The amount to buy + */ + @Override + public void buy(final Player p, int amount) { + if (amount < 0) { + this.sell(p, -amount); + } + if (this.isUnlimited()) { + final ItemStack[] contents = p.getInventory().getContents(); + for (int i = 0; amount > 0 && i < contents.length; i++) { + final ItemStack stack = contents[i]; + if (stack == null) { + continue; // No item + } + if (matches(stack)) { + final int stackSize = Math.min(amount, stack.getAmount()); + stack.setAmount(stack.getAmount() - stackSize); + amount -= stackSize; + } + } + // Send the players new inventory to them + p.getInventory().setContents(contents); + // This should not happen. + if (amount > 0) { + plugin.getLogger().log(Level.WARNING, "Could not take all items from a players inventory on purchase! " + p.getName() + ", missing: " + amount + ", item: " + this.getDataName() + "!"); + } + } else { + final ItemStack[] playerContents = p.getInventory().getContents(); + final Inventory chestInv = this.getInventory(); + for (int i = 0; amount > 0 && i < playerContents.length; i++) { + ItemStack item = playerContents[i]; + if (item != null && this.matches(item)) { + // Copy it, we don't want to interfere + item = item.clone(); + // Amount = total, item.getAmount() = how many items in the + // stack + final int stackSize = Math.min(amount, item.getAmount()); + // If Amount is item.getAmount(), then this sets the amount + // to 0 + // Else it sets it to the remainder + playerContents[i].setAmount(playerContents[i].getAmount() - stackSize); + // We can modify this, it is a copy. + item.setAmount(stackSize); + // Add the items to the players inventory + chestInv.addItem(item); + amount -= stackSize; + } + } + // Now update the players inventory. + p.getInventory().setContents(playerContents); + } + } - /** - * Returns a clone of this shop. References to the same display item, - * itemstack, location and owner as this shop does. Do not modify them or - * you will modify this shop. - * - * **NOT A DEEP CLONE** - */ - @Override - public ContainerShop clone() { - return new ContainerShop(this); - } + /** + * Returns a clone of this shop. References to the same display item, + * itemstack, location and owner as this shop does. Do not modify them or + * you will modify this shop. + * + * **NOT A DEEP CLONE** + */ + @Override + public ContainerShop clone() { + return new ContainerShop(this); + } - /** - * Deletes the shop from the list of shops and queues it for database - * deletion *DOES* delete it from memory - */ - @Override - public void delete() { - delete(true); - } + /** + * Deletes the shop from the list of shops and queues it for database + * deletion *DOES* delete it from memory + */ + @Override + public void delete() { + delete(true); + } - /** - * Deletes the shop from the list of shops and queues it for database - * deletion - * - * @param fromMemory - * True if you are *NOT* iterating over this currently, *false if - * you are iterating* - */ - @SuppressWarnings("deprecation") - @Override - public void delete(final boolean fromMemory) { - // Delete the display item - if (this.getDisplayItem() != null) { - this.getDisplayItem().remove(); - } - // Delete the signs around it - for (final Sign s : this.getSigns()) { - s.getBlock().setType(Material.AIR); - } - // Delete it from the database - final int x = this.getLocation().getBlockX(); - final int y = this.getLocation().getBlockY(); - final int z = this.getLocation().getBlockZ(); - final String world = this.getLocation().getWorld().getName(); - plugin.getDB().execute("DELETE FROM shops WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "'"); - // Refund if necessary - if (plugin.getConfig().getBoolean("shop.refund")) { - plugin.getEcon().deposit(this.getOwner(), plugin.getConfig().getDouble("shop.cost")); - } - if (fromMemory) { - // Delete it from memory - plugin.getShopManager().removeShop(this); - } - } + /** + * Deletes the shop from the list of shops and queues it for database + * deletion + * + * @param fromMemory + * True if you are *NOT* iterating over this currently, *false if + * you are iterating* + */ + @SuppressWarnings("deprecation") + @Override + public void delete(final boolean fromMemory) { + // Delete the display item + if (this.getDisplayItem() != null) { + this.getDisplayItem().remove(); + } + // Delete the signs around it + for (final Sign s : this.getSigns()) { + s.getBlock().setType(Material.AIR); + } + // Delete it from the database + final int x = this.getLocation().getBlockX(); + final int y = this.getLocation().getBlockY(); + final int z = this.getLocation().getBlockZ(); + final String world = this.getLocation().getWorld().getName(); + plugin.getDB().execute("DELETE FROM shops WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "'"); + // Refund if necessary + if (plugin.getConfig().getBoolean("shop.refund")) { + plugin.getEcon().deposit(this.getOwner(), plugin.getConfig().getDouble("shop.cost")); + } + if (fromMemory) { + // Delete it from memory + plugin.getShopManager().removeShop(this); + } + } - /** - * Returns the shop that shares it's inventory with this one. - * - * @return the shop that shares it's inventory with this one. Will return - * null if this shop is not attached to another. - */ - public ContainerShop getAttachedShop() { - final Block c = Util.getSecondHalf(this.getLocation().getBlock()); - if (c == null) { - return null; - } - final Shop shop = plugin.getShopManager().getShop(c.getLocation()); - return shop == null ? null : (ContainerShop) shop; - } + /** + * Returns the shop that shares it's inventory with this one. + * + * @return the shop that shares it's inventory with this one. Will return + * null if this shop is not attached to another. + */ + public ContainerShop getAttachedShop() { + final Block c = Util.getSecondHalf(this.getLocation().getBlock()); + if (c == null) { + return null; + } + final Shop shop = plugin.getShopManager().getShop(c.getLocation()); + return shop == null ? null : (ContainerShop) shop; + } - /** - * Convenience method. Equivilant to - * org.maxgamer.quickshop.Util.getName(shop.getItem()). - * - * @return The name of this shops item - */ - @Override - public String getDataName() { - return Util.getName(this.getItem()); - } + /** + * Convenience method. Equivilant to + * org.maxgamer.quickshop.Util.getName(shop.getItem()). + * + * @return The name of this shops item + */ + @Override + public String getDataName() { + return Util.getName(this.getItem()); + } - /** - * Returns the display item associated with this shop. - * - * @return The display item associated with this shop. - */ - public DisplayItem getDisplayItem() { - return this.displayName; - } + /** + * Returns the display item associated with this shop. + * + * @return The display item associated with this shop. + */ + public DisplayItem getDisplayItem() { + return this.displayItem; + } - /** - * @return The durability of the item - */ - @Override - public short getDurability() { - return this.item.getDurability(); - } + /** + * @return The durability of the item + */ + @Override + public short getDurability() { + return this.item.getDurability(); + } - /** - * @return The enchantments the shop has on its items. - */ - public Map getEnchants() { - return this.item.getItemMeta().getEnchants(); - } + /** + * @return The enchantments the shop has on its items. + */ + public Map getEnchants() { + return this.item.getItemMeta().getEnchants(); + } - /** - * @return The chest this shop is based on. - */ - public Inventory getInventory() throws IllegalStateException { - InventoryHolder container; - try { - container = (InventoryHolder) this.loc.getBlock().getState(); - return container.getInventory(); - } catch (final Exception e) { - throw new IllegalStateException("Inventory doesn't exist anymore"); - } - } + /** + * @return The chest this shop is based on. + */ + public Inventory getInventory() throws IllegalStateException { + InventoryHolder container; + try { + container = (InventoryHolder) this.loc.getBlock().getState(); + return container.getInventory(); + } catch (final Exception e) { + throw new IllegalStateException("Inventory doesn't exist anymore"); + } + } - /** - * @return Returns a dummy itemstack of the item this shop is selling. - */ - @Override - public ItemStack getItem() { - return item; - } + /** + * @return Returns a dummy itemstack of the item this shop is selling. + */ + @Override + public ItemStack getItem() { + return item; + } - /** - * @return The location of the shops chest - */ - @Override - public Location getLocation() { - return this.loc; - } + /** + * @return The location of the shops chest + */ + @Override + public Location getLocation() { + return this.loc; + } - /** - * @return The ItemStack type of this shop - */ - public Material getMaterial() { - return this.item.getType(); - } + /** + * @return The ItemStack type of this shop + */ + public Material getMaterial() { + return this.item.getType(); + } - /** - * @return The name of the player who owns the shop. - */ - @Override - public String getOwner() { - return this.owner; - } + /** + * @return The name of the player who owns the shop. + */ + @Override + public String getOwner() { + return this.owner; + } - /** - * @return The price per item this shop is selling - */ - @Override - public double getPrice() { - return this.price; - } + /** + * @return The price per item this shop is selling + */ + @Override + public double getPrice() { + return this.price; + } - /** - * Returns the number of free spots in the chest for the particular item. - * - * @param stackSize - * @return - */ - @Override - public int getRemainingSpace() { - if (this.unlimited) { - return 10000; - } - return Util.countSpace(this.getInventory(), item); - } + /** + * Returns the number of free spots in the chest for the particular item. + * + * @param stackSize + * @return + */ + @Override + public int getRemainingSpace() { + if (this.unlimited) { + return 10000; + } + return Util.countSpace(this.getInventory(), item); + } - /** - * Returns the number of items this shop has in stock. - * - * @return The number of items available for purchase. - */ - @Override - public int getRemainingStock() { - if (this.unlimited) { - return 10000; - } - return Util.countItems(this.getInventory(), this.getItem()); - } + /** + * Returns the number of items this shop has in stock. + * + * @return The number of items available for purchase. + */ + @Override + public int getRemainingStock() { + if (this.unlimited) { + return 10000; + } + return Util.countItems(this.getInventory(), this.getItem()); + } - @Override - public ShopType getShopType() { - return this.shopType; - } + @Override + public ShopType getShopType() { + return this.shopType; + } - /** - * Returns a list of signs that are attached to this shop (QuickShop and - * blank signs only) - * - * @return a list of signs that are attached to this shop (QuickShop and - * blank signs only) - */ - @Override - public List getSigns() { - final ArrayList signs = new ArrayList(1); - if (this.getLocation().getWorld() == null) { - return signs; - } - final Block[] blocks = new Block[4]; - blocks[0] = loc.getBlock().getRelative(1, 0, 0); - blocks[1] = loc.getBlock().getRelative(-1, 0, 0); - blocks[2] = loc.getBlock().getRelative(0, 0, 1); - blocks[3] = loc.getBlock().getRelative(0, 0, -1); - for (final Block b : blocks) { - if (b.getType() != Material.WALL_SIGN) { - continue; - } - if (!isAttached(b)) { - continue; - } - final Sign sign = (Sign) b.getState(); - if (sign.getLine(0).contains("[QuickShop]")) { - signs.add(sign); - } else { - boolean text = false; - for (final String s : sign.getLines()) { - if (!s.isEmpty()) { - text = true; - break; - } - } - if (!text) { - signs.add(sign); - } - } - } - return signs; - } + /** + * Returns a list of signs that are attached to this shop (QuickShop and + * blank signs only) + * + * @return a list of signs that are attached to this shop (QuickShop and + * blank signs only) + */ + @Override + public List getSigns() { + final ArrayList signs = new ArrayList(1); + if (this.getLocation().getWorld() == null) { + return signs; + } + final Block[] blocks = new Block[4]; + blocks[0] = loc.getBlock().getRelative(1, 0, 0); + blocks[1] = loc.getBlock().getRelative(-1, 0, 0); + blocks[2] = loc.getBlock().getRelative(0, 0, 1); + blocks[3] = loc.getBlock().getRelative(0, 0, -1); + for (final Block b : blocks) { + if (b.getType() != Material.WALL_SIGN) { + continue; + } + if (!isAttached(b)) { + continue; + } + final Sign sign = (Sign) b.getState(); + if (sign.getLine(0).contains("[QuickShop]")) { + signs.add(sign); + } else { + boolean text = false; + for (final String s : sign.getLines()) { + if (!s.isEmpty()) { + text = true; + break; + } + } + if (!text) { + signs.add(sign); + } + } + } + return signs; + } - @Override - public boolean isAttached(final Block b) { - if (b.getType() != Material.WALL_SIGN) { - new IllegalArgumentException(b + " Is not a sign!").printStackTrace(); - } - return this.getLocation().getBlock().equals(Util.getAttached(b)); - } + @Override + public boolean isAttached(final Block b) { + if (b.getType() != Material.WALL_SIGN) { + new IllegalArgumentException(b + " Is not a sign!").printStackTrace(); + } + return this.getLocation().getBlock().equals(Util.getAttached(b)); + } - @Override - public boolean isBuying() { - return this.shopType == ShopType.BUYING; - } + @Override + public boolean isBuying() { + return this.shopType == ShopType.BUYING; + } - /** - * Returns true if this shop is a double chest, and the other half is - * selling/buying the same as this is buying/selling. - * - * @return true if this shop is a double chest, and the other half is - * selling/buying the same as this is buying/selling. - */ - public boolean isDoubleShop() { - final ContainerShop nextTo = this.getAttachedShop(); - if (nextTo == null) { - return false; - } - if (nextTo.matches(this.getItem())) { - // They're both trading the same item - if (this.getShopType() == nextTo.getShopType()) { - // They're both buying or both selling => Not a double shop, - // just two shops. - return false; - } - // One is buying, one is selling. - return true; - } - return false; - } + /** + * Returns true if this shop is a double chest, and the other half is + * selling/buying the same as this is buying/selling. + * + * @return true if this shop is a double chest, and the other half is + * selling/buying the same as this is buying/selling. + */ + public boolean isDoubleShop() { + final ContainerShop nextTo = this.getAttachedShop(); + if (nextTo == null) { + return false; + } + if (nextTo.matches(this.getItem())) { + // They're both trading the same item + if (this.getShopType() == nextTo.getShopType()) { + // They're both buying or both selling => Not a double shop, + // just two shops. + return false; + } + // One is buying, one is selling. + return true; + } + return false; + } - @Override - public boolean isSelling() { - return this.shopType == ShopType.SELLING; - } + @Override + public boolean isSelling() { + return this.shopType == ShopType.SELLING; + } - @Override - public boolean isUnlimited() { - return this.unlimited; - } + @Override + public boolean isUnlimited() { + return this.unlimited; + } - @Override - public boolean isValid() { - checkDisplay(); - return Util.canBeShop(this.getLocation().getBlock()); - } + @Override + public boolean isValid() { + checkDisplay(); + return Util.canBeShop(this.getLocation().getBlock()); + } - /** - * Returns true if the ItemStack matches what this shop is selling/buying - * - * @param item - * The ItemStack - * @return True if the ItemStack is the same (Excludes amounts) - */ - @Override - public boolean matches(final ItemStack item) { - return Util.matches(this.item, item); - } + /** + * Returns true if the ItemStack matches what this shop is selling/buying + * + * @param item + * The ItemStack + * @return True if the ItemStack is the same (Excludes amounts) + */ + @Override + public boolean matches(final ItemStack item) { + return Util.matches(this.item, item); + } - @Override - public void onClick() { - this.setSignText(); - } + @Override + public void onClick() { + this.setSignText(); + } - @Override - public void onLoad() { - checkDisplay(); - } + @Override + public void onLoad() { + checkDisplay(); + } - @Override - public void onUnload() { - if (this.getDisplayItem() != null) { - this.getDisplayItem().remove(); - this.displayName = null; - } - } + @Override + public void onUnload() { + if (this.getDisplayItem() != null) { + this.getDisplayItem().remove(); + this.displayItem = null; + } + } - /** - * Removes an item from the shop. - * - * @param item - * The itemstack. The amount does not matter, just everything - * else - * @param amount - * The amount to remove from the shop. - */ - @Override - public void remove(final ItemStack item, final int amount) { - if (this.unlimited) { - return; - } - final Inventory inv = this.getInventory(); - int remains = amount; - while (remains > 0) { - final int stackSize = Math.min(remains, item.getMaxStackSize()); - item.setAmount(stackSize); - inv.removeItem(item); - remains = remains - stackSize; - } - } + /** + * Removes an item from the shop. + * + * @param item + * The itemstack. The amount does not matter, just everything + * else + * @param amount + * The amount to remove from the shop. + */ + @Override + public void remove(final ItemStack item, final int amount) { + if (this.unlimited) { + return; + } + final Inventory inv = this.getInventory(); + int remains = amount; + while (remains > 0) { + final int stackSize = Math.min(remains, item.getMaxStackSize()); + item.setAmount(stackSize); + inv.removeItem(item); + remains = remains - stackSize; + } + } - /** - * Sells amount of item to Player p. Does NOT check our inventory, or - * balances - * - * @param p - * The player to sell to - * @param amount - * The amount to sell - */ - @Override - public void sell(final Player p, int amount) { - if (amount < 0) { - this.buy(p, -amount); - } - // Items to drop on floor - final ArrayList floor = new ArrayList(5); - final Inventory pInv = p.getInventory(); - if (this.isUnlimited()) { - final ItemStack item = this.item.clone(); - while (amount > 0) { - final int stackSize = Math.min(amount, this.item.getMaxStackSize()); - item.setAmount(stackSize); - pInv.addItem(item); - amount -= stackSize; - } - } else { - final ItemStack[] chestContents = this.getInventory().getContents(); - for (int i = 0; amount > 0 && i < chestContents.length; i++) { - // Can't clone it here, it could be null - ItemStack item = chestContents[i]; - if (item != null && this.matches(item)) { - // Copy it, we don't want to interfere - item = item.clone(); - // Amount = total, item.getAmount() = how many items in the - // stack - final int stackSize = Math.min(amount, item.getAmount()); - // If Amount is item.getAmount(), then this sets the amount - // to 0 - // Else it sets it to the remainder - chestContents[i].setAmount(chestContents[i].getAmount() - stackSize); - // We can modify this, it is a copy. - item.setAmount(stackSize); - // Add the items to the players inventory - floor.addAll(pInv.addItem(item).values()); - amount -= stackSize; - } - } - // We now have to update the chests inventory manually. - this.getInventory().setContents(chestContents); - } - for (int i = 0; i < floor.size(); i++) { - p.getWorld().dropItem(p.getLocation(), floor.get(i)); - } - } + /** + * Sells amount of item to Player p. Does NOT check our inventory, or + * balances + * + * @param p + * The player to sell to + * @param amount + * The amount to sell + */ + @Override + public void sell(final Player p, int amount) { + if (amount < 0) { + this.buy(p, -amount); + } + // Items to drop on floor + final ArrayList floor = new ArrayList(5); + final Inventory pInv = p.getInventory(); + if (this.isUnlimited()) { + final ItemStack item = this.item.clone(); + while (amount > 0) { + final int stackSize = Math.min(amount, this.item.getMaxStackSize()); + item.setAmount(stackSize); + pInv.addItem(item); + amount -= stackSize; + } + } else { + final ItemStack[] chestContents = this.getInventory().getContents(); + for (int i = 0; amount > 0 && i < chestContents.length; i++) { + // Can't clone it here, it could be null + ItemStack item = chestContents[i]; + if (item != null && this.matches(item)) { + // Copy it, we don't want to interfere + item = item.clone(); + // Amount = total, item.getAmount() = how many items in the + // stack + final int stackSize = Math.min(amount, item.getAmount()); + // If Amount is item.getAmount(), then this sets the amount + // to 0 + // Else it sets it to the remainder + chestContents[i].setAmount(chestContents[i].getAmount() - stackSize); + // We can modify this, it is a copy. + item.setAmount(stackSize); + // Add the items to the players inventory + floor.addAll(pInv.addItem(item).values()); + amount -= stackSize; + } + } + // We now have to update the chests inventory manually. + this.getInventory().setContents(chestContents); + } + for (int i = 0; i < floor.size(); i++) { + p.getWorld().dropItem(p.getLocation(), floor.get(i)); + } + } - /** - * Changes the owner of this shop to the given player. - * - * @param owner - * The name of the owner. You must do shop.update() after to save - * it after a reboot. - */ - @Override - public void setOwner(final String owner) { - this.owner = owner; - } + /** + * Changes the owner of this shop to the given player. + * + * @param owner + * The name of the owner. You must do shop.update() after to save + * it after a reboot. + */ + @Override + public void setOwner(final String owner) { + this.owner = owner; + } - /** - * Sets the price of the shop. Does not update it in the database. Use - * shop.update() for that. - * - * @param price - * The new price of the shop. - */ - @Override - public void setPrice(final double price) { - this.price = price; - } + /** + * Sets the price of the shop. Does not update it in the database. Use + * shop.update() for that. + * + * @param price + * The new price of the shop. + */ + @Override + public void setPrice(final double price) { + this.price = price; + } - /** - * Changes a shop type to Buying or Selling. Also updates the signs nearby. - * - * @param shopType - * The new type (ShopType.BUYING or ShopType.SELLING) - */ - @Override - public void setShopType(final ShopType shopType) { - this.shopType = shopType; - this.setSignText(); - } + /** + * Changes a shop type to Buying or Selling. Also updates the signs nearby. + * + * @param shopType + * The new type (ShopType.BUYING or ShopType.SELLING) + */ + @Override + public void setShopType(final ShopType shopType) { + this.shopType = shopType; + this.setSignText(); + } - /** - * Updates signs attached to the shop - */ - @Override - public void setSignText() { - if (Util.isLoaded(this.getLocation()) == false) { - return; - } - final String[] lines = new String[4]; - lines[0] = ChatColor.RED + "[QuickShop]"; - if (this.isBuying()) { - final int remsp = this.getRemainingSpace(); - lines[1] = MsgUtil.p("signs.buying", "" + (remsp == 10000 ? "无限" : remsp)); - } - if (this.isSelling()) { - final int remst = this.getRemainingStock(); - lines[1] = MsgUtil.p("signs.selling", "" + (remst == 10000 ? "无限" : remst)); - } - lines[2] = Util.getNameForSign(this.item); - lines[3] = MsgUtil.p("signs.price", "" + this.getPrice()); - this.setSignText(lines); - } + /** + * Updates signs attached to the shop + */ + @Override + public void setSignText() { + if (Util.isLoaded(this.getLocation()) == false) { + return; + } + final String[] lines = new String[4]; + lines[0] = ChatColor.RED + "[QuickShop]"; + if (this.isBuying()) { + final int remsp = this.getRemainingSpace(); + lines[1] = MsgUtil.p("signs.buying", "" + (remsp == 10000 ? "无限" : remsp)); + } + if (this.isSelling()) { + final int remst = this.getRemainingStock(); + lines[1] = MsgUtil.p("signs.selling", "" + (remst == 10000 ? "无限" : remst)); + } + lines[2] = Util.getNameForSign(this.item); + lines[3] = MsgUtil.p("signs.price", "" + this.getPrice()); + this.setSignText(lines); + } - /** - * Changes all lines of text on a sign near the shop - * - * @param lines - * The array of lines to change. Index is line number. - */ - @Override - public void setSignText(final String[] lines) { - if (Util.isLoaded(this.getLocation()) == false) { - return; - } - for (final Sign sign : this.getSigns()) { - for (int i = 0; i < lines.length; i++) { - sign.setLine(i, lines[i]); - } - sign.update(); - } - } + /** + * Changes all lines of text on a sign near the shop + * + * @param lines + * The array of lines to change. Index is line number. + */ + @Override + public void setSignText(final String[] lines) { + if (Util.isLoaded(this.getLocation()) == false) { + return; + } + for (final Sign sign : this.getSigns()) { + for (int i = 0; i < lines.length; i++) { + sign.setLine(i, lines[i]); + } + sign.update(); + } + } - @Override - public void setUnlimited(final boolean unlimited) { - this.unlimited = unlimited; - } + @Override + public void setUnlimited(final boolean unlimited) { + this.unlimited = unlimited; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("商店 " + (loc.getWorld() == null ? "世界尚未载入" : "坐标: " + loc.getWorld().getName()) + "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " - + loc.getBlockZ() + ")"); - sb.append(" 所有者: " + getOwner()); - if (isUnlimited()) { - sb.append(" 无限模式: true"); - } - sb.append(" 价格: " + getPrice()); - sb.append(" 物品: " + getItem().toString()); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("商店 " + (loc.getWorld() == null ? "世界尚未载入" : "坐标: " + loc.getWorld().getName()) + "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + + loc.getBlockZ() + ")"); + sb.append(" 所有者: " + getOwner()); + if (isUnlimited()) { + sb.append(" 无限模式: true"); + } + sb.append(" 价格: " + getPrice()); + sb.append(" 物品: " + getItem().toString()); + return sb.toString(); + } - /** - * Upates the shop into the database. - */ - @Override - public void update() { - final int x = this.getLocation().getBlockX(); - final int y = this.getLocation().getBlockY(); - final int z = this.getLocation().getBlockZ(); - final String world = this.getLocation().getWorld().getName(); - final int unlimited = this.isUnlimited() ? 1 : 0; - final String q = "UPDATE shops SET owner = ?, itemConfig = ?, unlimited = ?, type = ?, price = ? WHERE x = ? AND y = ? and z = ? and world = ?"; - try { - plugin.getDB().execute(q, this.getOwner(), Util.serialize(this.getItem()), unlimited, shopType.toID(), this.getPrice(), x, y, z, world); - } catch (final Exception e) { - plugin.getLogger().warning("无法保存商店到数据库!!!"); - plugin.getLogger().warning("错误信息: " + e.getMessage()); - e.printStackTrace(); - } - } + /** + * Upates the shop into the database. + */ + @Override + public void update() { + final int x = this.getLocation().getBlockX(); + final int y = this.getLocation().getBlockY(); + final int z = this.getLocation().getBlockZ(); + final String world = this.getLocation().getWorld().getName(); + final int unlimited = this.isUnlimited() ? 1 : 0; + final String q = "UPDATE shops SET owner = ?, itemConfig = ?, unlimited = ?, type = ?, price = ? WHERE x = ? AND y = ? and z = ? and world = ?"; + try { + plugin.getDB().execute(q, this.getOwner(), Util.serialize(this.getItem()), unlimited, shopType.toID(), this.getPrice(), x, y, z, world); + } catch (final Exception e) { + plugin.getLogger().warning("无法保存商店到数据库!!!"); + plugin.getLogger().warning("错误信息: " + e.getMessage()); + e.printStackTrace(); + } + } - private void checkDisplay() { - if (plugin.getConfigManager().isDisplay() == false) { - return; - } - if (getLocation().getWorld() == null) { - return; // not loaded - } - final boolean trans = Util.isTransparent(getLocation().clone().add(0.5, 1.2, 0.5).getBlock().getType()); - if (trans && this.getDisplayItem() == null) { - if (plugin.getConfigManager().isFakeItem()) { - this.displayName = new FakeItem(this, this.getItem()); - } else { - this.displayName = new NormalItem(this, this.getItem()); - } - this.getDisplayItem().spawn(); - return; - } - if (this.getDisplayItem() != null) { - if (!trans) { // We have a display item in a block... delete it - this.getDisplayItem().remove(); - this.displayName = null; - return; - } - final DisplayItem disItem = this.getDisplayItem(); - final Location dispLoc = disItem.getDisplayLocation(); - if (dispLoc.getBlock() != null && dispLoc.getBlock().getType() == Material.WATER) { // Flowing - // water.Stationery water does not move items. - disItem.remove(); - return; - } - if (disItem.getItem() == null) { - disItem.removeDupe(); - disItem.spawn(); - return; - } - final Item item = disItem.getItem(); - if (item.getTicksLived() > 5000 || !item.isValid() || item.isDead()) { - disItem.respawn(); - disItem.removeDupe(); - } else if (item.getLocation().distanceSquared(dispLoc) > 1) { - item.teleport(dispLoc, TeleportCause.PLUGIN); - } - } - } + private void checkDisplay() { + if (plugin.getConfigManager().isDisplay() == false) { + return; + } + if (getLocation().getWorld() == null) { + return; // not loaded + } + final boolean trans = Util.isTransparent(getLocation().clone().add(0.5, 1.2, 0.5).getBlock().getType()); + if (trans && this.getDisplayItem() == null) { + if (plugin.getConfigManager().isFakeItem()) { + this.displayItem = new FakeItem(this, this.getItem()); + } else { + this.displayItem = new NormalItem(this, this.getItem()); + } + this.getDisplayItem().spawn(); + return; + } + if (this.getDisplayItem() != null && displayItem instanceof NormalItem) { + if (!trans) { // We have a display item in a block... delete it + this.getDisplayItem().remove(); + this.displayItem = null; + return; + } + final DisplayItem disItem = this.getDisplayItem(); + final Location dispLoc = disItem.getDisplayLocation(); + if (dispLoc.getBlock() != null && dispLoc.getBlock().getType() == Material.WATER) { // Flowing + // water.Stationery water does not move items. + disItem.remove(); + return; + } + if (disItem.getItem() == null) { + disItem.removeDupe(); + disItem.spawn(); + return; + } + final Item item = disItem.getItem(); + if (item.getTicksLived() > 5000 || !item.isValid() || item.isDead()) { + disItem.respawn(); + disItem.removeDupe(); + } else if (item.getLocation().distanceSquared(dispLoc) > 1) { + item.teleport(dispLoc, TeleportCause.PLUGIN); + } + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/DisplayItem.java b/src/main/java/org/maxgamer/QuickShop/Shop/DisplayItem.java index 99f0e94..b5a1975 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/DisplayItem.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/DisplayItem.java @@ -8,37 +8,37 @@ import org.bukkit.entity.Item; * cannot be interacted with. */ public interface DisplayItem { - /** - * 获得悬浮物地点 - * - * @return 获得悬浮地点 - */ - public Location getDisplayLocation(); + /** + * 获得悬浮物地点 + * + * @return 获得悬浮地点 + */ + public Location getDisplayLocation(); - /** - * @return {@link Item} - */ - public Item getItem(); + /** + * @return {@link Item} + */ + public Item getItem(); - /** - * 移除悬浮物 - */ - public void remove(); + /** + * 移除悬浮物 + */ + public void remove(); - /** - * 移除多余物品 - * - * @return - */ - public boolean removeDupe(); + /** + * 移除多余物品 + * + * @return + */ + public boolean removeDupe(); - /** - * 更新悬浮物 - */ - public void respawn(); + /** + * 更新悬浮物 + */ + public void respawn(); - /** - * 刷出悬浮物 - */ - public void spawn(); + /** + * 刷出悬浮物 + */ + public void spawn(); } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/FakeItem.java b/src/main/java/org/maxgamer/QuickShop/Shop/FakeItem.java index d5755ac..f8ae202 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/FakeItem.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/FakeItem.java @@ -31,207 +31,209 @@ import com.comphenix.protocol.wrappers.WrappedWatchableObject; */ public class FakeItem implements DisplayItem { - private static Map> fakes = new HashMap>(); - private static boolean registered = false; - private static int lastId = Integer.MAX_VALUE; + private static Map> fakes = new HashMap>(); + private static boolean registered = false; + private static int lastId = Integer.MAX_VALUE; - private final ItemStack itemStack; - private final Location location; - private final int eid; - private boolean created = false; + private final ItemStack itemStack; + private final Location location; + private final int eid; + private boolean created = false; - public static boolean isRegistered() { - return registered; - } + public static boolean isRegistered() { + return registered; + } - public static void register(final Plugin plugin) { - if (registered) { - return; - } - final PluginManager pm = Bukkit.getPluginManager(); - final Plugin p = pm.getPlugin("ProtocolLib"); - if (p != null) { - if (!p.isEnabled()) { - pm.enablePlugin(p); - } - if (!p.isEnabled()) { - throw new IllegalStateException("The ProtocolLib enable Failed."); - } - } else { - throw new IllegalStateException("The Server Not Found ProtocolLib."); - } - final PacketAdapter chunkPacketListener = new PacketAdapter(plugin, PacketType.Play.Server.MAP_CHUNK) { - @Override - public void onPacketSending(final PacketEvent event) { - final PacketContainer packet = event.getPacket(); - final Player p = event.getPlayer(); - final int chunkX = packet.getIntegers().read(0); - final int chunkZ = packet.getIntegers().read(1); - final List fakesInChunk = fakes.get(getChunkIdentifyString(p.getWorld().getChunkAt(chunkX, chunkZ))); - if (fakesInChunk != null) { - try { - for (final FakeItem fake : fakesInChunk) { - ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getSpawnPacket()); - ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getVelocityPacket()); - ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getMetadataPacket()); - } - } catch (final InvocationTargetException e) { - } - } - } - }; - final PacketAdapter chunkBulkPacketListener = new PacketAdapter(plugin, PacketType.Play.Server.MAP_CHUNK_BULK) { - @Override - public void onPacketSending(final PacketEvent event) { - final PacketContainer packet = event.getPacket(); - final Player p = event.getPlayer(); - final int[] chunksX = packet.getIntegerArrays().read(0); - final int[] chunksZ = packet.getIntegerArrays().read(1); - for (int i = 0; i < chunksX.length; i++) { - final List fakesInChunk = fakes.get(getChunkIdentifyString(p.getWorld().getChunkAt(chunksX[i], chunksZ[i]))); - if (fakesInChunk != null) { - try { - for (final FakeItem fake : fakesInChunk) { - ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getSpawnPacket()); - ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getVelocityPacket()); - ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getMetadataPacket()); - } - } catch (final InvocationTargetException e) { - } - } - } - } - }; + public static void register(final Plugin plugin) { + if (registered) { + return; + } + final PluginManager pm = Bukkit.getPluginManager(); + final Plugin p = pm.getPlugin("ProtocolLib"); + if (p != null) { + if (!p.isEnabled()) { + pm.enablePlugin(p); + } + if (!p.isEnabled()) { + throw new IllegalStateException("The ProtocolLib enable Failed."); + } + } else { + throw new IllegalStateException("The Server Not Found ProtocolLib."); + } + final PacketAdapter chunkPacketListener = new PacketAdapter(plugin, PacketType.Play.Server.MAP_CHUNK) { + @Override + public void onPacketSending(final PacketEvent event) { + final PacketContainer packet = event.getPacket(); + final Player p = event.getPlayer(); + final int chunkX = packet.getIntegers().read(0); + final int chunkZ = packet.getIntegers().read(1); + final List fakesInChunk = fakes.get(getChunkIdentifyString(p.getWorld().getChunkAt(chunkX, chunkZ))); + if (fakesInChunk != null) { + try { + for (final FakeItem fake : fakesInChunk) { + ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getSpawnPacket()); + ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getVelocityPacket()); + ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getMetadataPacket()); + } + } catch (final InvocationTargetException e) { + } + } + } + }; + final PacketAdapter chunkBulkPacketListener = new PacketAdapter(plugin, PacketType.Play.Server.MAP_CHUNK_BULK) { + @Override + public void onPacketSending(final PacketEvent event) { + final PacketContainer packet = event.getPacket(); + final Player p = event.getPlayer(); + final int[] chunksX = packet.getIntegerArrays().read(0); + final int[] chunksZ = packet.getIntegerArrays().read(1); + for (int i = 0; i < chunksX.length; i++) { + final List fakesInChunk = fakes.get(getChunkIdentifyString(p.getWorld().getChunkAt(chunksX[i], chunksZ[i]))); + if (fakesInChunk != null) { + try { + for (final FakeItem fake : fakesInChunk) { + ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getSpawnPacket()); + ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getVelocityPacket()); + ProtocolLibrary.getProtocolManager().sendServerPacket(p, fake.getMetadataPacket()); + } + } catch (final InvocationTargetException e) { + } + } + } + } + }; - ProtocolLibrary.getProtocolManager().addPacketListener(chunkPacketListener); - ProtocolLibrary.getProtocolManager().addPacketListener(chunkBulkPacketListener); - registered = true; - } + ProtocolLibrary.getProtocolManager().addPacketListener(chunkPacketListener); + ProtocolLibrary.getProtocolManager().addPacketListener(chunkBulkPacketListener); + registered = true; + } - private static String getChunkIdentifyString(final Chunk chunk) { - return chunk.getWorld().getName() + "@@" + chunk.getX() + "@@" + chunk.getZ(); - } + private static String getChunkIdentifyString(final Chunk chunk) { + return chunk.getWorld().getName() + "@@" + chunk.getX() + "@@" + chunk.getZ(); + } - private static int getFakeEntityId() { - return lastId--; - } + private static int getFakeEntityId() { + return lastId--; + } - private static int getNormalizedDistance(final double value) { - return (int) Math.floor(value * 32.0D); - } + private static int getNormalizedDistance(final double value) { + return (int) Math.floor(value * 32.0D); + } - public FakeItem(final ContainerShop containerShop, final ItemStack item) { - this.itemStack = item; - this.location = containerShop.getLocation().add(0.5, 1, 0.5); - this.eid = getFakeEntityId(); - } + public FakeItem(final ContainerShop containerShop, final ItemStack item) { + this.itemStack = item; + this.location = containerShop.getLocation().clone().add(0.5, 1, 0.5); + this.eid = getFakeEntityId(); + } - public FakeItem(final ItemStack itemStack, final Location loc) { - this.itemStack = itemStack; - this.location = loc; - this.eid = getFakeEntityId(); - } + public FakeItem(final ItemStack itemStack, final Location loc) { + this.itemStack = itemStack; + this.location = loc; + this.eid = getFakeEntityId(); + } - @Override - public Location getDisplayLocation() { - return location; - } + @Override + public Location getDisplayLocation() { + return location; + } - @Override - public Item getItem() { - return null; - } + @Override + public Item getItem() { + return null; + } - @Override - public void remove() { - destory(); - } + @Override + public void remove() { + destory(); + } - @Override - public boolean removeDupe() { - return true; - } + @Override + public boolean removeDupe() { + return true; + } - @Override - public void respawn() { - destory(); - create(); - } + @Override + public void respawn() { + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getDestoryPacket()); + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getSpawnPacket()); + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getVelocityPacket()); + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getMetadataPacket()); + } - @Override - public void spawn() { - create(); - } + @Override + public void spawn() { + create(); + } - private void create() { - if (!registered) { - throw new IllegalStateException("You have to call the register method first."); - } - if (created) { - return; - } - ProtocolLibrary.getProtocolManager().broadcastServerPacket(getSpawnPacket()); - ProtocolLibrary.getProtocolManager().broadcastServerPacket(getVelocityPacket()); - ProtocolLibrary.getProtocolManager().broadcastServerPacket(getMetadataPacket()); + private void create() { + if (!registered) { + throw new IllegalStateException("You have to call the register method first."); + } + if (created) { + return; + } + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getSpawnPacket()); + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getVelocityPacket()); + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getMetadataPacket()); - final String chunkId = getChunkIdentifyString(location.getChunk()); - List fakesInChunk = fakes.get(chunkId); - if (fakesInChunk == null) { - fakesInChunk = new ArrayList(); - } - fakesInChunk.add(this); - fakes.put(chunkId, fakesInChunk); - created = true; - } + final String chunkId = getChunkIdentifyString(location.getChunk()); + List fakesInChunk = fakes.get(chunkId); + if (fakesInChunk == null) { + fakesInChunk = new ArrayList(); + } + fakesInChunk.add(this); + fakes.put(chunkId, fakesInChunk); + created = true; + } - private void destory() { - if (!created) { - return; - } - ProtocolLibrary.getProtocolManager().broadcastServerPacket(getDestoryPacket()); + private void destory() { + if (!created) { + return; + } + ProtocolLibrary.getProtocolManager().broadcastServerPacket(getDestoryPacket()); - final String chunkId = getChunkIdentifyString(location.getChunk()); - final List fakesInChunk = fakes.get(chunkId); - if (fakesInChunk == null) { - // NOTE: This is what should not happens if everything is correct. - created = false; - return; - } - fakesInChunk.remove(this); - fakes.put(chunkId, fakesInChunk); - created = false; - } + final String chunkId = getChunkIdentifyString(location.getChunk()); + final List fakesInChunk = fakes.get(chunkId); + if (fakesInChunk == null) { + // NOTE: This is what should not happens if everything is correct. + created = false; + return; + } + fakesInChunk.remove(this); + fakes.put(chunkId, fakesInChunk); + created = false; + } - private PacketContainer getDestoryPacket() { - final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY, true); - fakePacket.getIntegerArrays().write(0, new int[] { eid }); - return fakePacket; - } + private PacketContainer getDestoryPacket() { + final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY, true); + fakePacket.getIntegerArrays().write(0, new int[] { eid }); + return fakePacket; + } - private PacketContainer getMetadataPacket() { - final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - fakePacket.getIntegers().write(0, eid); - final WrappedWatchableObject itemMeta = new WrappedWatchableObject(10, itemStack); - final List entityMetaList = new ArrayList(1); - entityMetaList.add(itemMeta); - fakePacket.getWatchableCollectionModifier().write(0, entityMetaList); - return fakePacket; - } + private PacketContainer getMetadataPacket() { + final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + fakePacket.getIntegers().write(0, eid); + final WrappedWatchableObject itemMeta = new WrappedWatchableObject(10, itemStack); + final List entityMetaList = new ArrayList(1); + entityMetaList.add(itemMeta); + fakePacket.getWatchableCollectionModifier().write(0, entityMetaList); + return fakePacket; + } - private PacketContainer getSpawnPacket() { - final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); - fakePacket.getIntegers().write(0, eid); - fakePacket.getIntegers().write(1, getNormalizedDistance(location.getX())); - fakePacket.getIntegers().write(2, getNormalizedDistance(location.getY())); - fakePacket.getIntegers().write(3, getNormalizedDistance(location.getZ())); - fakePacket.getIntegers().write(9, 2); - return fakePacket; - } + private PacketContainer getSpawnPacket() { + final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); + fakePacket.getIntegers().write(0, eid); + fakePacket.getIntegers().write(1, getNormalizedDistance(location.getX())); + fakePacket.getIntegers().write(2, getNormalizedDistance(location.getY())); + fakePacket.getIntegers().write(3, getNormalizedDistance(location.getZ())); + fakePacket.getIntegers().write(9, 2); + return fakePacket; + } - private PacketContainer getVelocityPacket() { - final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); - fakePacket.getIntegers().write(0, eid); - return fakePacket; - } + private PacketContainer getVelocityPacket() { + final PacketContainer fakePacket = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); + fakePacket.getIntegers().write(0, eid); + return fakePacket; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/Info.java b/src/main/java/org/maxgamer/QuickShop/Shop/Info.java index 1325881..7b82597 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/Info.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/Info.java @@ -5,94 +5,94 @@ import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; public class Info { - private Location loc; - private ShopAction action; - private ItemStack item; - private Block last; - private Shop shop; + private Location loc; + private ShopAction action; + private ItemStack item; + private Block last; + private Shop shop; - /** - * Stores info for the players last shop interact. - * - * @param loc - * The location they clicked (Block.getLocation()) - * @param action - * The action (ShopAction.*) - * @param material - * The material they were holding - * @param data - * The data value of the material - */ - public Info(Location loc, ShopAction action, ItemStack item, Block last) { - this.loc = loc; - this.action = action; - this.last = last; - if (item != null) - this.item = item.clone(); - } + /** + * Stores info for the players last shop interact. + * + * @param loc + * The location they clicked (Block.getLocation()) + * @param action + * The action (ShopAction.*) + * @param material + * The material they were holding + * @param data + * The data value of the material + */ + public Info(Location loc, ShopAction action, ItemStack item, Block last) { + this.loc = loc; + this.action = action; + this.last = last; + if (item != null) + this.item = item.clone(); + } - /** - * Stores info for the players last shop interact. - * - * @param loc - * The location they clicked (Block.getLocation()) - * @param action - * The action (ShopAction.*) - * @param material - * The material they were holding - * @param data - * The data value of the material - * @param shop - * The shop they interacted with, or null if none - */ - public Info(Location loc, ShopAction action, ItemStack item, Block last, Shop shop) { - this.loc = loc; - this.action = action; - this.last = last; - if (item != null) - this.item = item.clone(); - if (shop != null) { - this.shop = shop.clone(); - } - } + /** + * Stores info for the players last shop interact. + * + * @param loc + * The location they clicked (Block.getLocation()) + * @param action + * The action (ShopAction.*) + * @param material + * The material they were holding + * @param data + * The data value of the material + * @param shop + * The shop they interacted with, or null if none + */ + public Info(Location loc, ShopAction action, ItemStack item, Block last, Shop shop) { + this.loc = loc; + this.action = action; + this.last = last; + if (item != null) + this.item = item.clone(); + if (shop != null) { + this.shop = shop.clone(); + } + } - public boolean hasChanged(Shop shop) { - if (this.shop.isUnlimited() != shop.isUnlimited()) - return true; - if (this.shop.getShopType() != shop.getShopType()) - return true; - if (!this.shop.getOwner().equals(shop.getOwner())) - return true; - if (this.shop.getPrice() != shop.getPrice()) - return true; - if (!this.shop.getLocation().equals(shop.getLocation())) - return true; - if (!this.shop.matches(shop.getItem())) - return true; - return false; - } + public boolean hasChanged(Shop shop) { + if (this.shop.isUnlimited() != shop.isUnlimited()) + return true; + if (this.shop.getShopType() != shop.getShopType()) + return true; + if (!this.shop.getOwner().equals(shop.getOwner())) + return true; + if (this.shop.getPrice() != shop.getPrice()) + return true; + if (!this.shop.getLocation().equals(shop.getLocation())) + return true; + if (!this.shop.matches(shop.getItem())) + return true; + return false; + } - public ShopAction getAction() { - return this.action; - } + public ShopAction getAction() { + return this.action; + } - public Location getLocation() { - return this.loc; - } + public Location getLocation() { + return this.loc; + } - /* - * public Material getMaterial(){ return this.item.getType(); } public byte - * getData(){ return this.getData(); } - */ - public ItemStack getItem() { - return this.item; - } + /* + * public Material getMaterial(){ return this.item.getType(); } public byte + * getData(){ return this.getData(); } + */ + public ItemStack getItem() { + return this.item; + } - public void setAction(ShopAction action) { - this.action = action; - } + public void setAction(ShopAction action) { + this.action = action; + } - public Block getSignBlock() { - return this.last; - } + public Block getSignBlock() { + return this.last; + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/NormalItem.java b/src/main/java/org/maxgamer/QuickShop/Shop/NormalItem.java index 274406e..2eeb145 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/NormalItem.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/NormalItem.java @@ -13,104 +13,104 @@ import org.maxgamer.QuickShop.Util.NMS; * cannot be interacted with. */ public class NormalItem implements DisplayItem { - private final ItemStack iStack; - private Item item; - private final Shop shop; + private final ItemStack iStack; + private Item item; + private final Shop shop; - // private Location displayLoc; - /** - * Creates a new display item. - * - * @param shop - * The shop (See Shop) - * @param iStack - * The item stack to clone properties of the display item from. - */ - public NormalItem(final Shop shop, final ItemStack iStack) { - this.shop = shop; - this.iStack = iStack.clone(); - // this.displayLoc = shop.getLocation().clone().add(0.5, 1.2, 0.5); - } + // private Location displayLoc; + /** + * Creates a new display item. + * + * @param shop + * The shop (See Shop) + * @param iStack + * The item stack to clone properties of the display item from. + */ + public NormalItem(final Shop shop, final ItemStack iStack) { + this.shop = shop; + this.iStack = iStack.clone(); + // this.displayLoc = shop.getLocation().clone().add(0.5, 1.2, 0.5); + } - /** - * @return Returns the exact location of the display item. (1 above shop - * block, in the center) - */ - @Override - public Location getDisplayLocation() { - return this.shop.getLocation().clone().add(0.5, 1.2, 0.5); - } + /** + * @return Returns the exact location of the display item. (1 above shop + * block, in the center) + */ + @Override + public Location getDisplayLocation() { + return this.shop.getLocation().clone().add(0.5, 1.2, 0.5); + } - /** - * Returns the reference to this shops item. Do not modify. - */ - @Override - public Item getItem() { - return this.item; - } + /** + * Returns the reference to this shops item. Do not modify. + */ + @Override + public Item getItem() { + return this.item; + } - /** - * Removes the display item. - */ - @Override - public void remove() { - if (this.item == null) { - return; - } - this.item.remove(); - } + /** + * Removes the display item. + */ + @Override + public void remove() { + if (this.item == null) { + return; + } + this.item.remove(); + } - /** - * Removes all items floating ontop of the chest that aren't the display - * item. - */ - @Override - public boolean removeDupe() { - if (shop.getLocation().getWorld() == null) { - return false; - } - final Location displayLoc = shop.getLocation().getBlock().getRelative(0, 1, 0).getLocation(); - boolean removed = false; - final Chunk c = displayLoc.getChunk(); - for (final Entity e : c.getEntities()) { - if (!(e instanceof Item)) { - continue; - } - if (this.item != null && e.getEntityId() == this.item.getEntityId()) { - continue; - } - final Location eLoc = e.getLocation().getBlock().getLocation(); - if (eLoc.equals(displayLoc) || eLoc.equals(shop.getLocation())) { - e.remove(); - removed = true; - } - } - return removed; - } + /** + * Removes all items floating ontop of the chest that aren't the display + * item. + */ + @Override + public boolean removeDupe() { + if (shop.getLocation().getWorld() == null) { + return false; + } + final Location displayLoc = shop.getLocation().getBlock().getRelative(0, 1, 0).getLocation(); + boolean removed = false; + final Chunk c = displayLoc.getChunk(); + for (final Entity e : c.getEntities()) { + if (!(e instanceof Item)) { + continue; + } + if (this.item != null && e.getEntityId() == this.item.getEntityId()) { + continue; + } + final Location eLoc = e.getLocation().getBlock().getLocation(); + if (eLoc.equals(displayLoc) || eLoc.equals(shop.getLocation())) { + e.remove(); + removed = true; + } + } + return removed; + } - /** - * Spawns the new display item. Does not remove duplicate items. - */ - @Override - public void respawn() { - remove(); - spawn(); - } + /** + * Spawns the new display item. Does not remove duplicate items. + */ + @Override + public void respawn() { + remove(); + spawn(); + } - /** - * Spawns the dummy item on top of the shop. - */ - @Override - public void spawn() { - if (shop.getLocation().getWorld() == null) { - return; - } - final Location dispLoc = this.getDisplayLocation(); - try { - this.item = shop.getLocation().getWorld().dropItem(dispLoc, this.iStack); - this.item.setVelocity(new Vector(0, 0.1, 0)); - NMS.safeGuard(this.item); - } catch (final Exception e) { - } - } + /** + * Spawns the dummy item on top of the shop. + */ + @Override + public void spawn() { + if (shop.getLocation().getWorld() == null) { + return; + } + final Location dispLoc = this.getDisplayLocation(); + try { + this.item = shop.getLocation().getWorld().dropItem(dispLoc, this.iStack); + this.item.setVelocity(new Vector(0, 0.1, 0)); + NMS.safeGuard(this.item); + } catch (final Exception e) { + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/Shop.java b/src/main/java/org/maxgamer/QuickShop/Shop/Shop.java index f1827fa..a6b89f9 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/Shop.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/Shop.java @@ -9,69 +9,69 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public abstract interface Shop { - public abstract void add(ItemStack paramItemStack, int paramInt); + public abstract void add(ItemStack paramItemStack, int paramInt); - public abstract void buy(Player paramPlayer, int paramInt); + public abstract void buy(Player paramPlayer, int paramInt); - public abstract Shop clone(); + public abstract Shop clone(); - public abstract void delete(); + public abstract void delete(); - public abstract void delete(boolean paramBoolean); + public abstract void delete(boolean paramBoolean); - public abstract String getDataName(); + public abstract String getDataName(); - public abstract short getDurability(); + public abstract short getDurability(); - public abstract ItemStack getItem(); + public abstract ItemStack getItem(); - public abstract Location getLocation(); + public abstract Location getLocation(); - public abstract String getOwner(); + public abstract String getOwner(); - public abstract double getPrice(); + public abstract double getPrice(); - public abstract int getRemainingSpace(); + public abstract int getRemainingSpace(); - public abstract int getRemainingStock(); + public abstract int getRemainingStock(); - public abstract ShopType getShopType(); + public abstract ShopType getShopType(); - public abstract List getSigns(); + public abstract List getSigns(); - public abstract boolean isAttached(Block paramBlock); + public abstract boolean isAttached(Block paramBlock); - public abstract boolean isBuying(); + public abstract boolean isBuying(); - public abstract boolean isSelling(); + public abstract boolean isSelling(); - public abstract boolean isUnlimited(); + public abstract boolean isUnlimited(); - public abstract boolean isValid(); + public abstract boolean isValid(); - public abstract boolean matches(ItemStack paramItemStack); + public abstract boolean matches(ItemStack paramItemStack); - public abstract void onClick(); + public abstract void onClick(); - public abstract void onLoad(); + public abstract void onLoad(); - public abstract void onUnload(); + public abstract void onUnload(); - public abstract void remove(ItemStack paramItemStack, int paramInt); + public abstract void remove(ItemStack paramItemStack, int paramInt); - public abstract void sell(Player paramPlayer, int paramInt); + public abstract void sell(Player paramPlayer, int paramInt); - public abstract void setOwner(String paramString); + public abstract void setOwner(String paramString); - public abstract void setPrice(double paramDouble); + public abstract void setPrice(double paramDouble); - public abstract void setShopType(ShopType paramShopType); + public abstract void setShopType(ShopType paramShopType); - public abstract void setSignText(); + public abstract void setSignText(); - public abstract void setSignText(String[] paramArrayOfString); + public abstract void setSignText(String[] paramArrayOfString); - public abstract void setUnlimited(boolean paramBoolean); + public abstract void setUnlimited(boolean paramBoolean); - public abstract void update(); + public abstract void update(); } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopAction.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopAction.java index a9c5079..7a4d593 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopAction.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopAction.java @@ -1,5 +1,7 @@ package org.maxgamer.QuickShop.Shop; public enum ShopAction { - BUY(), CREATE(), CANCELLED(); + BUY(), + CREATE(), + CANCELLED(); } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopChunk.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopChunk.java index c413928..cc89ecd 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopChunk.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopChunk.java @@ -1,43 +1,43 @@ package org.maxgamer.QuickShop.Shop; public class ShopChunk { - private final String world; - private final int x; - private final int z; - private int hash = 0; + private final String world; + private final int x; + private final int z; + private int hash = 0; - public ShopChunk(final String world, final int x, final int z) { - this.world = world; - this.x = x; - this.z = z; - this.hash = this.x * this.z; // We don't need to use the world's hash, - // as these are seperated by world in - // memory - } + public ShopChunk(final String world, final int x, final int z) { + this.world = world; + this.x = x; + this.z = z; + this.hash = this.x * this.z; // We don't need to use the world's hash, + // as these are seperated by world in + // memory + } - @Override - public boolean equals(final Object obj) { - if (obj.getClass() != this.getClass()) { - return false; - } - final ShopChunk shopChunk = (ShopChunk) obj; - return (this.getWorld().equals(shopChunk.getWorld()) && this.getX() == shopChunk.getX() && this.getZ() == shopChunk.getZ()); - } + @Override + public boolean equals(final Object obj) { + if (obj.getClass() != this.getClass()) { + return false; + } + final ShopChunk shopChunk = (ShopChunk) obj; + return (this.getWorld().equals(shopChunk.getWorld()) && this.getX() == shopChunk.getX() && this.getZ() == shopChunk.getZ()); + } - public String getWorld() { - return this.world; - } + public String getWorld() { + return this.world; + } - public int getX() { - return this.x; - } + public int getX() { + return this.x; + } - public int getZ() { - return this.z; - } + public int getZ() { + return this.z; + } - @Override - public int hashCode() { - return hash; - } + @Override + public int hashCode() { + return hash; + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopCreateEvent.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopCreateEvent.java index 06bcbda..41d64e3 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopCreateEvent.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopCreateEvent.java @@ -6,50 +6,50 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class ShopCreateEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private Shop shop; - private boolean cancelled; - private Player p; + private static final HandlerList handlers = new HandlerList(); + private Shop shop; + private boolean cancelled; + private Player p; - public ShopCreateEvent(Shop shop, Player p) { - this.shop = shop; - this.p = p; - } + public ShopCreateEvent(Shop shop, Player p) { + this.shop = shop; + this.p = p; + } - /** - * The shop to be created - * - * @return The shop to be created - */ - public Shop getShop() { - return this.shop; - } + /** + * The shop to be created + * + * @return The shop to be created + */ + public Shop getShop() { + return this.shop; + } - /** - * The player who is creating this shop - * - * @return The player who is creating this shop - */ - public Player getPlayer() { - return p; - } + /** + * The player who is creating this shop + * + * @return The player who is creating this shop + */ + public Player getPlayer() { + return p; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopManager.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopManager.java index 953144d..5996a9d 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopManager.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopManager.java @@ -25,595 +25,595 @@ import org.maxgamer.QuickShop.Util.MsgUtil; import org.maxgamer.QuickShop.Util.Util; public class ShopManager { - private final HashMap actions = new HashMap(); + private final HashMap actions = new HashMap(); - private final QuickShop plugin; - private final HashMap>> shops = new HashMap>>(); + private final QuickShop plugin; + private final HashMap>> shops = new HashMap>>(); - public ShopManager(final QuickShop plugin) { - this.plugin = plugin; - } + public ShopManager(final QuickShop plugin) { + this.plugin = plugin; + } - /** - * Checks other plugins to make sure they can use the chest they're making a - * shop. - * - * @param p - * The player to check - * @param b - * The block to check - * @return True if they're allowed to place a shop there. - */ - public boolean canBuildShop(final Player p, final Block b, final BlockFace bf) { - if (plugin.getConfigManager().isLimit()) { - int owned = 0; - final Iterator it = getShopIterator(); - while (it.hasNext()) { - if (it.next().getOwner().equals(p.getName())) { - owned++; - } - } - final int max = plugin.getShopLimit(p); - if (owned + 1 > max) { - p.sendMessage(MsgUtil.p("you-cant-create-more-shop", owned)); - return false; - } - } - final PlayerInteractEvent pie = new PlayerInteractEvent(p, Action.RIGHT_CLICK_BLOCK, new ItemStack(Material.AIR), b, bf); // PIE = PlayerInteractEvent - What else? - Bukkit.getPluginManager().callEvent(pie); - pie.getPlayer().closeInventory(); // If the player has chat open, this will close their chat. - if (pie.isCancelled()) { - return false; - } - final ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation()); - Bukkit.getPluginManager().callEvent(spce); - if (spce.isCancelled()) { - return false; - } - return true; - } + /** + * Checks other plugins to make sure they can use the chest they're making a + * shop. + * + * @param p + * The player to check + * @param b + * The block to check + * @return True if they're allowed to place a shop there. + */ + public boolean canBuildShop(final Player p, final Block b, final BlockFace bf) { + if (plugin.getConfigManager().isLimit()) { + int owned = 0; + final Iterator it = getShopIterator(); + while (it.hasNext()) { + if (it.next().getOwner().equals(p.getName())) { + owned++; + } + } + final int max = plugin.getShopLimit(p); + if (owned + 1 > max) { + p.sendMessage(MsgUtil.p("you-cant-create-more-shop", owned)); + return false; + } + } + final PlayerInteractEvent pie = new PlayerInteractEvent(p, Action.RIGHT_CLICK_BLOCK, new ItemStack(Material.AIR), b, bf); // PIE = PlayerInteractEvent - What else? + Bukkit.getPluginManager().callEvent(pie); + pie.getPlayer().closeInventory(); // If the player has chat open, this will close their chat. + if (pie.isCancelled()) { + return false; + } + final ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation()); + Bukkit.getPluginManager().callEvent(spce); + if (spce.isCancelled()) { + return false; + } + return true; + } - /** - * Removes all shops from memory and the world. Does not delete them from - * the database. Call this on plugin disable ONLY. - */ - public void clear() { - if (plugin.getConfigManager().isDisplay()) { - for (final World world : Bukkit.getWorlds()) { - for (final Chunk chunk : world.getLoadedChunks()) { - final HashMap inChunk = this.getShops(chunk); - if (inChunk == null) { - continue; - } - for (final Shop shop : inChunk.values()) { - shop.onUnload(); - } - } - } - } - this.actions.clear(); - this.shops.clear(); - } + /** + * Removes all shops from memory and the world. Does not delete them from + * the database. Call this on plugin disable ONLY. + */ + public void clear() { + if (plugin.getConfigManager().isDisplay()) { + for (final World world : Bukkit.getWorlds()) { + for (final Chunk chunk : world.getLoadedChunks()) { + final HashMap inChunk = this.getShops(chunk); + if (inChunk == null) { + continue; + } + for (final Shop shop : inChunk.values()) { + shop.onUnload(); + } + } + } + } + this.actions.clear(); + this.shops.clear(); + } - public void createShop(final Shop shop) { - final Location loc = shop.getLocation(); - final ItemStack item = shop.getItem(); - try { - // Write it to the database - final String q = "INSERT INTO shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; - plugin.getDB().execute(q, - shop.getOwner().toString(), - shop.getPrice(), - Util.serialize(item), - loc.getBlockX(), - loc.getBlockY(), - loc.getBlockZ(), - loc.getWorld().getName(), - (shop.isUnlimited() ? 1 : 0), - shop.getShopType().toID()); - // Add it to the world - addShop(loc.getWorld().getName(), shop); - } catch (final Exception e) { - plugin.getLogger().warning("无法保存商店到数据库! 下次重启商店将会消失!"); - plugin.getLogger().warning("错误信息: " + e.getMessage()); - e.printStackTrace(); - } - } + public void createShop(final Shop shop) { + final Location loc = shop.getLocation(); + final ItemStack item = shop.getItem(); + try { + // Write it to the database + final String q = "INSERT INTO shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + plugin.getDB().execute(q, + shop.getOwner().toString(), + shop.getPrice(), + Util.serialize(item), + loc.getBlockX(), + loc.getBlockY(), + loc.getBlockZ(), + loc.getWorld().getName(), + (shop.isUnlimited() ? 1 : 0), + shop.getShopType().toID()); + // Add it to the world + addShop(loc.getWorld().getName(), shop); + } catch (final Exception e) { + plugin.getLogger().warning("无法保存商店到数据库! 下次重启商店将会消失!"); + plugin.getLogger().warning("错误信息: " + e.getMessage()); + e.printStackTrace(); + } + } - public String format(final double d) { - return plugin.getEcon().format(d); - } + public String format(final double d) { + return plugin.getEcon().format(d); + } - /** - * @return Returns the HashMap. Info contains what - * their last question etc was. - */ - public HashMap getActions() { - return this.actions; - } + /** + * @return Returns the HashMap. Info contains what + * their last question etc was. + */ + public HashMap getActions() { + return this.actions; + } - public Database getDatabase() { - return plugin.getDB(); - } + public Database getDatabase() { + return plugin.getDB(); + } - /** - * Gets a shop in a specific location - * - * @param loc - * The location to get the shop from - * @return The shop at that location - */ - public Shop getShop(final Location loc) { - final HashMap inChunk = getShops(loc.getChunk()); - if (inChunk == null) { - return null; - } - // We can do this because WorldListener updates the world reference so - // the world in loc is the same as world in inChunk.get(loc) - return inChunk.get(loc); - } + /** + * Gets a shop in a specific location + * + * @param loc + * The location to get the shop from + * @return The shop at that location + */ + public Shop getShop(final Location loc) { + final HashMap inChunk = getShops(loc.getChunk()); + if (inChunk == null) { + return null; + } + // We can do this because WorldListener updates the world reference so + // the world in loc is the same as world in inChunk.get(loc) + return inChunk.get(loc); + } - /** - * Returns a new shop iterator object, allowing iteration over shops easily, - * instead of sorting through a 3D hashmap. - * - * @return a new shop iterator object. - */ - public Iterator getShopIterator() { - return new ShopIterator(); - } + /** + * Returns a new shop iterator object, allowing iteration over shops easily, + * instead of sorting through a 3D hashmap. + * + * @return a new shop iterator object. + */ + public Iterator getShopIterator() { + return new ShopIterator(); + } - /** - * Returns a hashmap of World -> Chunk -> Shop - * - * @return a hashmap of World -> Chunk -> Shop - */ - public HashMap>> getShops() { - return this.shops; - } + /** + * Returns a hashmap of World -> Chunk -> Shop + * + * @return a hashmap of World -> Chunk -> Shop + */ + public HashMap>> getShops() { + return this.shops; + } - /** - * Returns a hashmap of Shops - * - * @param c - * The chunk to search. Referencing doesn't matter, only - * coordinates and world are used. - * @return - */ - public HashMap getShops(final Chunk c) { - // long start = System.nanoTime(); - final HashMap shops = getShops(c.getWorld().getName(), c.getX(), c.getZ()); - // long end = System.nanoTime(); - // System.out.println("Chunk lookup in " + ((end - start)/1000000.0) + - // "ms."); - return shops; - } + /** + * Returns a hashmap of Shops + * + * @param c + * The chunk to search. Referencing doesn't matter, only + * coordinates and world are used. + * @return + */ + public HashMap getShops(final Chunk c) { + // long start = System.nanoTime(); + final HashMap shops = getShops(c.getWorld().getName(), c.getX(), c.getZ()); + // long end = System.nanoTime(); + // System.out.println("Chunk lookup in " + ((end - start)/1000000.0) + + // "ms."); + return shops; + } - /** - * Returns a hashmap of Chunk -> Shop - * - * @param world - * The name of the world (case sensitive) to get the list of - * shops from - * @return a hashmap of Chunk -> Shop - */ - public HashMap> getShops(final String world) { - return this.shops.get(world); - } + /** + * Returns a hashmap of Chunk -> Shop + * + * @param world + * The name of the world (case sensitive) to get the list of + * shops from + * @return a hashmap of Chunk -> Shop + */ + public HashMap> getShops(final String world) { + return this.shops.get(world); + } - public HashMap getShops(final String world, final int chunkX, final int chunkZ) { - final HashMap> inWorld = this.getShops(world); - if (inWorld == null) { - return null; - } - final ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ); - return inWorld.get(shopChunk); - } + public HashMap getShops(final String world, final int chunkX, final int chunkZ) { + final HashMap> inWorld = this.getShops(world); + if (inWorld == null) { + return null; + } + final ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ); + return inWorld.get(shopChunk); + } - public void handleChat(final Player p, final String msg) { - final String message = ChatColor.stripColor(msg); - // Use from the main thread, because Bukkit hates life - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @SuppressWarnings("deprecation") - @Override - public void run() { - final HashMap actions = getActions(); - // They wanted to do something. - final Info info = actions.remove(p.getName()); - if (info == null) { - return; // multithreaded means this can happen - } - if (info.getLocation().getWorld() != p.getLocation().getWorld()) { - p.sendMessage(MsgUtil.p("shop-creation-cancelled")); - return; - } - if (info.getLocation().distanceSquared(p.getLocation()) > 25) { - p.sendMessage(MsgUtil.p("shop-creation-cancelled")); - return; - } - /* Creation handling */ - if (info.getAction() == ShopAction.CREATE) { - try { - // Checking the shop can be created - if (plugin.getShopManager().getShop(info.getLocation()) != null) { - p.sendMessage(MsgUtil.p("shop-already-owned")); - return; - } - if (Util.getSecondHalf(info.getLocation().getBlock()) != null && !p.hasPermission("quickshop.create.double")) { - p.sendMessage(MsgUtil.p("no-double-chests")); - return; - } - if (Util.canBeShop(info.getLocation().getBlock()) == false) { - p.sendMessage(MsgUtil.p("chest-was-removed")); - return; - } - // Price per item - double price; - if (plugin.getConfig().getBoolean("whole-number-prices-only")) { - price = Integer.parseInt(message); - } else { - price = Double.parseDouble(message); - } - if (price < 0.01) { - p.sendMessage(MsgUtil.p("price-too-cheap")); - return; - } - final double tax = plugin.getConfig().getDouble("shop.cost"); - // Tax refers to the cost to create a shop. Not actual - // tax, that would be silly - if (tax != 0 && plugin.getEcon().getBalance(p.getName()) < tax) { - p.sendMessage(MsgUtil.p("you-cant-afford-a-new-shop", format(tax))); - return; - } - // Create the sample shop. - final Shop shop = new ContainerShop(info.getLocation(), price, info.getItem(), p.getName()); - // This must be called after the event has been called. - // Else, if the event is cancelled, they won't get their - // money back. - if (tax != 0) { - if (!plugin.getEcon().withdraw(p.getName(), tax)) { - p.sendMessage(MsgUtil.p("you-cant-afford-a-new-shop", format(tax))); - return; - } - plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), tax); - } - final ShopCreateEvent e = new ShopCreateEvent(shop, p); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) { - return; - } - shop.onLoad(); - /* The shop has hereforth been successfully created */ - createShop(shop); - p.sendMessage(MsgUtil.p("success-created-shop")); - final Location loc = shop.getLocation(); - plugin.log(String.format("玩家: %s 创建了一个 %s 商店 在 (%s - %s, %s, %s)", p.getName(), shop.getDataName(), loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ())); - if (!plugin.getConfig().getBoolean("shop.lock")) { - // Warn them if they haven't been warned since - // reboot - final HashSet warings = plugin.getConfigManager().getWarnings(); - if (!warings.contains(p.getName())) { - p.sendMessage(MsgUtil.p("shops-arent-locked")); - warings.add(p.getName()); - } - } - // Figures out which way we should put the sign on and - // sets its text. - if (info.getSignBlock() != null && info.getSignBlock().getType() == Material.AIR && plugin.getConfig().getBoolean("shop.auto-sign")) { - final BlockState bs = info.getSignBlock().getState(); - final BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); - bs.setType(Material.WALL_SIGN); - final Sign sign = (Sign) bs.getData(); - if (sign != null && bf != null) { - sign.setFacingDirection(bf); - bs.update(true); - shop.setSignText(); - } - } - if (shop instanceof ContainerShop) { - final ContainerShop cs = (ContainerShop) shop; - if (cs.isDoubleShop()) { - final Shop nextTo = cs.getAttachedShop(); - if (nextTo.getPrice() > shop.getPrice()) { - // The one next to it must always be a - // buying shop. - p.sendMessage(MsgUtil.p("buying-more-than-selling")); - } - } - } - } - /* They didn't enter a number. */ - catch (final NumberFormatException ex) { - p.sendMessage(MsgUtil.p("shop-creation-cancelled")); - return; - } - } - /* Purchase Handling */ - else if (info.getAction() == ShopAction.BUY) { - int amount = 0; - try { - amount = Integer.parseInt(message); - } catch (final NumberFormatException e) { - p.sendMessage(MsgUtil.p("shop-purchase-cancelled")); - return; - } - // Get the shop they interacted with - final Shop shop = plugin.getShopManager().getShop(info.getLocation()); - // It's not valid anymore - if (shop == null || Util.canBeShop(info.getLocation().getBlock()) == false) { - p.sendMessage(MsgUtil.p("chest-was-removed")); - return; - } - if (info.hasChanged(shop)) { - p.sendMessage(MsgUtil.p("shop-has-changed")); - return; - } - if (shop.isSelling()) { - final int stock = shop.getRemainingStock(); - if (stock < amount) { - p.sendMessage(MsgUtil.p("shop-stock-too-low", "" + shop.getRemainingStock(), shop.getDataName())); - return; - } - if (amount == 0) { - // Dumb. - MsgUtil.sendPurchaseSuccess(p, shop, amount); - return; - } else if (amount < 0) { - // & Dumber - p.sendMessage(MsgUtil.p("negative-amount")); - return; - } - final int pSpace = Util.countSpace(p.getInventory(), shop.getItem()); - if (amount > pSpace) { - p.sendMessage(MsgUtil.p("not-enough-space", "" + pSpace)); - return; - } - final ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) { - return; // Cancelled - } - // Money handling - if (!p.getName().equals(shop.getOwner())) { - // Check their balance. Works with *most* economy - // plugins* - if (plugin.getEcon().getBalance(p.getName()) < amount * shop.getPrice()) { - p.sendMessage(MsgUtil.p("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getName())))); - return; - } - // Don't tax them if they're purchasing from - // themselves. - // Do charge an amount of tax though. - final double tax = plugin.getConfigManager().getTax(); - final double total = amount * shop.getPrice(); - if (!plugin.getEcon().withdraw(p.getName(), total)) { - p.sendMessage(MsgUtil.p("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getName())))); - return; - } - if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { - plugin.getEcon().deposit(shop.getOwner(), total * (1 - tax)); - if (tax != 0) { - plugin.getEcon().deposit(plugin.getConfigManager().getTaxAccount(), total * tax); - } - } - // Notify the shop owner - if (plugin.getConfigManager().isShowTax()) { - String msg = MsgUtil.p("player-bought-from-your-store-tax", p.getName(), "" + amount, shop.getDataName(), Util.format((tax * total))); - if (stock == amount) { - msg += "\n" + MsgUtil.p("shop-out-of-stock", - "" + shop.getLocation().getBlockX(), - "" + shop.getLocation().getBlockY(), - "" + shop.getLocation().getBlockZ(), - shop.getDataName()); - } - MsgUtil.send(shop.getOwner(), msg); - } else { - String msg = MsgUtil.p("player-bought-from-your-store", p.getName(), "" + amount, shop.getDataName()); - if (stock == amount) { - msg += "\n" + MsgUtil.p("shop-out-of-stock", - "" + shop.getLocation().getBlockX(), - "" + shop.getLocation().getBlockY(), - "" + shop.getLocation().getBlockZ(), - shop.getDataName()); - } - MsgUtil.send(shop.getOwner(), msg); - } - } - // Transfers the item from A to B - shop.sell(p, amount); - MsgUtil.sendPurchaseSuccess(p, shop, amount); - plugin.log(String.format("玩家: %s 从 %s 购买了 %s 件商品 花费 %s", p.getName(), shop.toString(), amount, shop.getPrice() * amount)); - } else if (shop.isBuying()) { - final int space = shop.getRemainingSpace(); - if (space < amount) { - p.sendMessage(MsgUtil.p("shop-has-no-space", "" + space, shop.getDataName())); - return; - } - final int count = Util.countItems(p.getInventory(), shop.getItem()); - // Not enough items - if (amount > count) { - p.sendMessage(MsgUtil.p("you-dont-have-that-many-items", "" + count, shop.getDataName())); - return; - } - if (amount == 0) { - // Dumb. - MsgUtil.sendPurchaseSuccess(p, shop, amount); - return; - } else if (amount < 0) { - // & Dumber - p.sendMessage(MsgUtil.p("negative-amount")); - return; - } - // Money handling - if (!p.getName().equals(shop.getOwner())) { - // Don't tax them if they're purchasing from - // themselves. - // Do charge an amount of tax though. - final double tax = plugin.getConfigManager().getTax(); - final double total = amount * shop.getPrice(); - if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { - // Tries to check their balance nicely to see if - // they can afford it. - if (plugin.getEcon().getBalance(shop.getOwner()) < amount * shop.getPrice()) { - p.sendMessage(MsgUtil.p("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); - return; - } - // Check for plugins faking econ.has(amount) - if (!plugin.getEcon().withdraw(shop.getOwner(), total)) { - p.sendMessage(MsgUtil.p("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); - return; - } - if (tax != 0) { - plugin.getEcon().deposit(plugin.getConfigManager().getTaxAccount(), total * tax); - } - } - // Give them the money after we know we succeeded - plugin.getEcon().deposit(p.getName(), total * (1 - tax)); - // Notify the owner of the purchase. - String msg = MsgUtil.p("player-sold-to-your-store", p.getName(), "" + amount, shop.getDataName()); - if (space == amount) { - msg += "\n" + MsgUtil.p("shop-out-of-space", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ()); - } - MsgUtil.send(shop.getOwner(), msg); - } - shop.buy(p, amount); - MsgUtil.sendSellSuccess(p, shop, amount); - plugin.log(String.format("玩家: %s 出售了 %s 件商品 到 %s 获得 %s", p.getName(), amount, shop.toString(), shop.getPrice() * amount)); - } - shop.setSignText(); // Update the signs count - } - /* If it was already cancelled (from destroyed) */ - else { - return; // It was cancelled, go away. - } - } - }); - } + public void handleChat(final Player p, final String msg) { + final String message = ChatColor.stripColor(msg); + // Use from the main thread, because Bukkit hates life + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + @SuppressWarnings("deprecation") + @Override + public void run() { + final HashMap actions = getActions(); + // They wanted to do something. + final Info info = actions.remove(p.getName()); + if (info == null) { + return; // multithreaded means this can happen + } + if (info.getLocation().getWorld() != p.getLocation().getWorld()) { + p.sendMessage(MsgUtil.p("shop-creation-cancelled")); + return; + } + if (info.getLocation().distanceSquared(p.getLocation()) > 25) { + p.sendMessage(MsgUtil.p("shop-creation-cancelled")); + return; + } + /* Creation handling */ + if (info.getAction() == ShopAction.CREATE) { + try { + // Checking the shop can be created + if (plugin.getShopManager().getShop(info.getLocation()) != null) { + p.sendMessage(MsgUtil.p("shop-already-owned")); + return; + } + if (Util.getSecondHalf(info.getLocation().getBlock()) != null && !p.hasPermission("quickshop.create.double")) { + p.sendMessage(MsgUtil.p("no-double-chests")); + return; + } + if (Util.canBeShop(info.getLocation().getBlock()) == false) { + p.sendMessage(MsgUtil.p("chest-was-removed")); + return; + } + // Price per item + double price; + if (plugin.getConfig().getBoolean("whole-number-prices-only")) { + price = Integer.parseInt(message); + } else { + price = Double.parseDouble(message); + } + if (price < 0.01) { + p.sendMessage(MsgUtil.p("price-too-cheap")); + return; + } + final double tax = plugin.getConfig().getDouble("shop.cost"); + // Tax refers to the cost to create a shop. Not actual + // tax, that would be silly + if (tax != 0 && plugin.getEcon().getBalance(p.getName()) < tax) { + p.sendMessage(MsgUtil.p("you-cant-afford-a-new-shop", format(tax))); + return; + } + // Create the sample shop. + final Shop shop = new ContainerShop(info.getLocation(), price, info.getItem(), p.getName()); + // This must be called after the event has been called. + // Else, if the event is cancelled, they won't get their + // money back. + if (tax != 0) { + if (!plugin.getEcon().withdraw(p.getName(), tax)) { + p.sendMessage(MsgUtil.p("you-cant-afford-a-new-shop", format(tax))); + return; + } + plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), tax); + } + final ShopCreateEvent e = new ShopCreateEvent(shop, p); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) { + return; + } + shop.onLoad(); + /* The shop has hereforth been successfully created */ + createShop(shop); + p.sendMessage(MsgUtil.p("success-created-shop")); + final Location loc = shop.getLocation(); + plugin.log(String.format("玩家: %s 创建了一个 %s 商店 在 (%s - %s, %s, %s)", p.getName(), shop.getDataName(), loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ())); + if (!plugin.getConfig().getBoolean("shop.lock")) { + // Warn them if they haven't been warned since + // reboot + final HashSet warings = plugin.getConfigManager().getWarnings(); + if (!warings.contains(p.getName())) { + p.sendMessage(MsgUtil.p("shops-arent-locked")); + warings.add(p.getName()); + } + } + // Figures out which way we should put the sign on and + // sets its text. + if (info.getSignBlock() != null && info.getSignBlock().getType() == Material.AIR && plugin.getConfig().getBoolean("shop.auto-sign")) { + final BlockState bs = info.getSignBlock().getState(); + final BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); + bs.setType(Material.WALL_SIGN); + final Sign sign = (Sign) bs.getData(); + if (sign != null && bf != null) { + sign.setFacingDirection(bf); + bs.update(true); + shop.setSignText(); + } + } + if (shop instanceof ContainerShop) { + final ContainerShop cs = (ContainerShop) shop; + if (cs.isDoubleShop()) { + final Shop nextTo = cs.getAttachedShop(); + if (nextTo.getPrice() > shop.getPrice()) { + // The one next to it must always be a + // buying shop. + p.sendMessage(MsgUtil.p("buying-more-than-selling")); + } + } + } + } + /* They didn't enter a number. */ + catch (final NumberFormatException ex) { + p.sendMessage(MsgUtil.p("shop-creation-cancelled")); + return; + } + } + /* Purchase Handling */ + else if (info.getAction() == ShopAction.BUY) { + int amount = 0; + try { + amount = Integer.parseInt(message); + } catch (final NumberFormatException e) { + p.sendMessage(MsgUtil.p("shop-purchase-cancelled")); + return; + } + // Get the shop they interacted with + final Shop shop = plugin.getShopManager().getShop(info.getLocation()); + // It's not valid anymore + if (shop == null || Util.canBeShop(info.getLocation().getBlock()) == false) { + p.sendMessage(MsgUtil.p("chest-was-removed")); + return; + } + if (info.hasChanged(shop)) { + p.sendMessage(MsgUtil.p("shop-has-changed")); + return; + } + if (shop.isSelling()) { + final int stock = shop.getRemainingStock(); + if (stock < amount) { + p.sendMessage(MsgUtil.p("shop-stock-too-low", "" + shop.getRemainingStock(), shop.getDataName())); + return; + } + if (amount == 0) { + // Dumb. + MsgUtil.sendPurchaseSuccess(p, shop, amount); + return; + } else if (amount < 0) { + // & Dumber + p.sendMessage(MsgUtil.p("negative-amount")); + return; + } + final int pSpace = Util.countSpace(p.getInventory(), shop.getItem()); + if (amount > pSpace) { + p.sendMessage(MsgUtil.p("not-enough-space", "" + pSpace)); + return; + } + final ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) { + return; // Cancelled + } + // Money handling + if (!p.getName().equals(shop.getOwner())) { + // Check their balance. Works with *most* economy + // plugins* + if (plugin.getEcon().getBalance(p.getName()) < amount * shop.getPrice()) { + p.sendMessage(MsgUtil.p("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getName())))); + return; + } + // Don't tax them if they're purchasing from + // themselves. + // Do charge an amount of tax though. + final double tax = plugin.getConfigManager().getTax(); + final double total = amount * shop.getPrice(); + if (!plugin.getEcon().withdraw(p.getName(), total)) { + p.sendMessage(MsgUtil.p("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getName())))); + return; + } + if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { + plugin.getEcon().deposit(shop.getOwner(), total * (1 - tax)); + if (tax != 0) { + plugin.getEcon().deposit(plugin.getConfigManager().getTaxAccount(), total * tax); + } + } + // Notify the shop owner + if (plugin.getConfigManager().isShowTax()) { + String msg = MsgUtil.p("player-bought-from-your-store-tax", p.getName(), "" + amount, shop.getDataName(), Util.format((tax * total))); + if (stock == amount) { + msg += "\n" + MsgUtil.p("shop-out-of-stock", + "" + shop.getLocation().getBlockX(), + "" + shop.getLocation().getBlockY(), + "" + shop.getLocation().getBlockZ(), + shop.getDataName()); + } + MsgUtil.send(shop.getOwner(), msg); + } else { + String msg = MsgUtil.p("player-bought-from-your-store", p.getName(), "" + amount, shop.getDataName()); + if (stock == amount) { + msg += "\n" + MsgUtil.p("shop-out-of-stock", + "" + shop.getLocation().getBlockX(), + "" + shop.getLocation().getBlockY(), + "" + shop.getLocation().getBlockZ(), + shop.getDataName()); + } + MsgUtil.send(shop.getOwner(), msg); + } + } + // Transfers the item from A to B + shop.sell(p, amount); + MsgUtil.sendPurchaseSuccess(p, shop, amount); + plugin.log(String.format("玩家: %s 从 %s 购买了 %s 件商品 花费 %s", p.getName(), shop.toString(), amount, shop.getPrice() * amount)); + } else if (shop.isBuying()) { + final int space = shop.getRemainingSpace(); + if (space < amount) { + p.sendMessage(MsgUtil.p("shop-has-no-space", "" + space, shop.getDataName())); + return; + } + final int count = Util.countItems(p.getInventory(), shop.getItem()); + // Not enough items + if (amount > count) { + p.sendMessage(MsgUtil.p("you-dont-have-that-many-items", "" + count, shop.getDataName())); + return; + } + if (amount == 0) { + // Dumb. + MsgUtil.sendPurchaseSuccess(p, shop, amount); + return; + } else if (amount < 0) { + // & Dumber + p.sendMessage(MsgUtil.p("negative-amount")); + return; + } + // Money handling + if (!p.getName().equals(shop.getOwner())) { + // Don't tax them if they're purchasing from + // themselves. + // Do charge an amount of tax though. + final double tax = plugin.getConfigManager().getTax(); + final double total = amount * shop.getPrice(); + if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { + // Tries to check their balance nicely to see if + // they can afford it. + if (plugin.getEcon().getBalance(shop.getOwner()) < amount * shop.getPrice()) { + p.sendMessage(MsgUtil.p("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); + return; + } + // Check for plugins faking econ.has(amount) + if (!plugin.getEcon().withdraw(shop.getOwner(), total)) { + p.sendMessage(MsgUtil.p("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); + return; + } + if (tax != 0) { + plugin.getEcon().deposit(plugin.getConfigManager().getTaxAccount(), total * tax); + } + } + // Give them the money after we know we succeeded + plugin.getEcon().deposit(p.getName(), total * (1 - tax)); + // Notify the owner of the purchase. + String msg = MsgUtil.p("player-sold-to-your-store", p.getName(), "" + amount, shop.getDataName()); + if (space == amount) { + msg += "\n" + MsgUtil.p("shop-out-of-space", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ()); + } + MsgUtil.send(shop.getOwner(), msg); + } + shop.buy(p, amount); + MsgUtil.sendSellSuccess(p, shop, amount); + plugin.log(String.format("玩家: %s 出售了 %s 件商品 到 %s 获得 %s", p.getName(), amount, shop.toString(), shop.getPrice() * amount)); + } + shop.setSignText(); // Update the signs count + } + /* If it was already cancelled (from destroyed) */ + else { + return; // It was cancelled, go away. + } + } + }); + } - /** - * Loads the given shop into storage. This method is used for loading data - * from the database. Do not use this method to create a shop. - * - * @param world - * The world the shop is in - * @param shop - * The shop to load - */ - public void loadShop(final String world, final Shop shop) { - this.addShop(world, shop); - } + /** + * Loads the given shop into storage. This method is used for loading data + * from the database. Do not use this method to create a shop. + * + * @param world + * The world the shop is in + * @param shop + * The shop to load + */ + public void loadShop(final String world, final Shop shop) { + this.addShop(world, shop); + } - /** - * Removes a shop from the world. Does NOT remove it from the database. * - * REQUIRES * the world to be loaded - * - * @param shop - * The shop to remove - */ - public void removeShop(final Shop shop) { - final Location loc = shop.getLocation(); - final String world = loc.getWorld().getName(); - final HashMap> inWorld = this.getShops().get(world); - final int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); - final int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); - final ShopChunk shopChunk = new ShopChunk(world, x, z); - final HashMap inChunk = inWorld.get(shopChunk); - inChunk.remove(loc); - } + /** + * Removes a shop from the world. Does NOT remove it from the database. * + * REQUIRES * the world to be loaded + * + * @param shop + * The shop to remove + */ + public void removeShop(final Shop shop) { + final Location loc = shop.getLocation(); + final String world = loc.getWorld().getName(); + final HashMap> inWorld = this.getShops().get(world); + final int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); + final int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); + final ShopChunk shopChunk = new ShopChunk(world, x, z); + final HashMap inChunk = inWorld.get(shopChunk); + inChunk.remove(loc); + } - /** - * Adds a shop to the world. Does NOT require the chunk or world to be - * loaded - * - * @param world - * The name of the world - * @param shop - * The shop to add - */ - private void addShop(final String world, final Shop shop) { - HashMap> inWorld = this.getShops().get(world); - // There's no world storage yet. We need to create that hashmap. - if (inWorld == null) { - inWorld = new HashMap>(3); - // Put it in the data universe - this.getShops().put(world, inWorld); - } - // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT - // location rounded to the nearest 16. - final int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); - final int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); - // Get the chunk set from the world info - final ShopChunk shopChunk = new ShopChunk(world, x, z); - HashMap inChunk = inWorld.get(shopChunk); - // That chunk data hasn't been created yet - Create it! - if (inChunk == null) { - inChunk = new HashMap(1); - // Put it in the world - inWorld.put(shopChunk, inChunk); - } - // Put the shop in its location in the chunk list. - inChunk.put(shop.getLocation(), shop); - } + /** + * Adds a shop to the world. Does NOT require the chunk or world to be + * loaded + * + * @param world + * The name of the world + * @param shop + * The shop to add + */ + private void addShop(final String world, final Shop shop) { + HashMap> inWorld = this.getShops().get(world); + // There's no world storage yet. We need to create that hashmap. + if (inWorld == null) { + inWorld = new HashMap>(3); + // Put it in the data universe + this.getShops().put(world, inWorld); + } + // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT + // location rounded to the nearest 16. + final int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); + final int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); + // Get the chunk set from the world info + final ShopChunk shopChunk = new ShopChunk(world, x, z); + HashMap inChunk = inWorld.get(shopChunk); + // That chunk data hasn't been created yet - Create it! + if (inChunk == null) { + inChunk = new HashMap(1); + // Put it in the world + inWorld.put(shopChunk, inChunk); + } + // Put the shop in its location in the chunk list. + inChunk.put(shop.getLocation(), shop); + } - public class ShopIterator implements Iterator { - private Iterator> chunks; - private Shop current; - private Iterator shops; - private final Iterator>> worlds; + public class ShopIterator implements Iterator { + private Iterator> chunks; + private Shop current; + private Iterator shops; + private final Iterator>> worlds; - public ShopIterator() { - worlds = getShops().values().iterator(); - } + public ShopIterator() { + worlds = getShops().values().iterator(); + } - /** - * Returns true if there is still more shops to iterate over. - */ - @Override - public boolean hasNext() { - if (shops == null || !shops.hasNext()) { - if (chunks == null || !chunks.hasNext()) { - if (!worlds.hasNext()) { - return false; - } - chunks = worlds.next().values().iterator(); - return hasNext(); - } - shops = chunks.next().values().iterator(); - return hasNext(); - } - return true; - } + /** + * Returns true if there is still more shops to iterate over. + */ + @Override + public boolean hasNext() { + if (shops == null || !shops.hasNext()) { + if (chunks == null || !chunks.hasNext()) { + if (!worlds.hasNext()) { + return false; + } + chunks = worlds.next().values().iterator(); + return hasNext(); + } + shops = chunks.next().values().iterator(); + return hasNext(); + } + return true; + } - /** - * Fetches the next shop. Throws NoSuchElementException if there are no - * more shops. - */ - @Override - public Shop next() { - if (shops == null || !shops.hasNext()) { - if (chunks == null || !chunks.hasNext()) { - if (!worlds.hasNext()) { - throw new NoSuchElementException("No more shops to iterate over!"); - } - chunks = worlds.next().values().iterator(); - } - shops = chunks.next().values().iterator(); - } - if (!shops.hasNext()) { - return this.next(); // Skip to the next one (Empty iterator?) - } - current = shops.next(); - return current; - } + /** + * Fetches the next shop. Throws NoSuchElementException if there are no + * more shops. + */ + @Override + public Shop next() { + if (shops == null || !shops.hasNext()) { + if (chunks == null || !chunks.hasNext()) { + if (!worlds.hasNext()) { + throw new NoSuchElementException("No more shops to iterate over!"); + } + chunks = worlds.next().values().iterator(); + } + shops = chunks.next().values().iterator(); + } + if (!shops.hasNext()) { + return this.next(); // Skip to the next one (Empty iterator?) + } + current = shops.next(); + return current; + } - /** - * Removes the current shop. This method will delete the shop from - * memory and the database. - */ - @Override - public void remove() { - current.delete(false); - shops.remove(); - } - } + /** + * Removes the current shop. This method will delete the shop from + * memory and the database. + */ + @Override + public void remove() { + current.delete(false); + shops.remove(); + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopPreCreateEvent.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopPreCreateEvent.java index e9b34ea..6c72f1f 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopPreCreateEvent.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopPreCreateEvent.java @@ -12,50 +12,50 @@ import org.bukkit.event.HandlerList; * much they wish to trade for. */ public class ShopPreCreateEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private Player p; - private Location loc; + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private Player p; + private Location loc; - public ShopPreCreateEvent(Player p, Location loc) { - this.loc = loc; - this.p = p; - } + public ShopPreCreateEvent(Player p, Location loc) { + this.loc = loc; + this.p = p; + } - /** - * The location of the shop that will be created. - * - * @return The location of the shop that will be created. - */ - public Location getLocation() { - return loc; - } + /** + * The location of the shop that will be created. + * + * @return The location of the shop that will be created. + */ + public Location getLocation() { + return loc; + } - /** - * The player who is creating this shop - * - * @return The player who is creating this shop - */ - public Player getPlayer() { - return p; - } + /** + * The player who is creating this shop + * + * @return The player who is creating this shop + */ + public Player getPlayer() { + return p; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopPurchaseEvent.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopPurchaseEvent.java index 831aba3..b70898d 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopPurchaseEvent.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopPurchaseEvent.java @@ -6,71 +6,71 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class ShopPurchaseEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private Shop shop; - private Player p; - private int amount; - private boolean cancelled; + private static final HandlerList handlers = new HandlerList(); + private Shop shop; + private Player p; + private int amount; + private boolean cancelled; - /** - * Builds a new shop purchase event - * - * @param shop - * The shop bought from - * @param p - * The player buying - * @param amount - * The amount they're buying - */ - public ShopPurchaseEvent(Shop shop, Player p, int amount) { - this.shop = shop; - this.p = p; - this.amount = amount; - } + /** + * Builds a new shop purchase event + * + * @param shop + * The shop bought from + * @param p + * The player buying + * @param amount + * The amount they're buying + */ + public ShopPurchaseEvent(Shop shop, Player p, int amount) { + this.shop = shop; + this.p = p; + this.amount = amount; + } - /** - * The shop used in this event - * - * @return The shop used in this event - */ - public Shop getShop() { - return this.shop; - } + /** + * The shop used in this event + * + * @return The shop used in this event + */ + public Shop getShop() { + return this.shop; + } - /** - * The player trading with the shop - * - * @return The player trading with the shop - */ - public Player getPlayer() { - return this.p; - } + /** + * The player trading with the shop + * + * @return The player trading with the shop + */ + public Player getPlayer() { + return this.p; + } - /** - * The amount the purchase was for - * - * @return The amount the purchase was for - */ - public int getAmount() { - return this.amount; - } + /** + * The amount the purchase was for + * + * @return The amount the purchase was for + */ + public int getAmount() { + return this.amount; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Shop/ShopType.java b/src/main/java/org/maxgamer/QuickShop/Shop/ShopType.java index 7f7b693..4f3cca6 100644 --- a/src/main/java/org/maxgamer/QuickShop/Shop/ShopType.java +++ b/src/main/java/org/maxgamer/QuickShop/Shop/ShopType.java @@ -1,26 +1,28 @@ package org.maxgamer.QuickShop.Shop; public enum ShopType { - SELLING(0), BUYING(1); - private int id; - private ShopType(int id){ - this.id = id; - } - - public static ShopType fromID(int id) { - for(ShopType type:ShopType.values()){ - if(type.id==id){ - return type; - } - } - return null; - } + SELLING(0), + BUYING(1); + private int id; - public static int toID(ShopType shopType) { - return shopType.id; - } + private ShopType(int id) { + this.id = id; + } - public int toID() { - return id; - } + public static ShopType fromID(int id) { + for (ShopType type : ShopType.values()) { + if (type.id == id) { + return type; + } + } + return null; + } + + public static int toID(ShopType shopType) { + return shopType.id; + } + + public int toID() { + return id; + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Util/MarkUtil.java b/src/main/java/org/maxgamer/QuickShop/Util/MarkUtil.java index 73b9879..d0c39bc 100644 --- a/src/main/java/org/maxgamer/QuickShop/Util/MarkUtil.java +++ b/src/main/java/org/maxgamer/QuickShop/Util/MarkUtil.java @@ -4,20 +4,20 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class MarkUtil { - static String mark = "§q§s§6[§b快捷商店§6] §c悬浮物品§r "; - static int conut = 0; + static String mark = "§q§s§6[§b快捷商店§6] §c悬浮物品§r "; + static int conut = 0; - public static void addMark(final ItemStack ci) { - final ItemMeta meta = ci.getItemMeta(); - meta.setDisplayName(mark + " " + Util.getName(ci) + " " + conut++); - ci.setItemMeta(meta); - } + public static void addMark(final ItemStack ci) { + final ItemMeta meta = ci.getItemMeta(); + meta.setDisplayName(mark + " " + Util.getName(ci) + " " + conut++); + ci.setItemMeta(meta); + } - public static boolean hasMark(final ItemStack ci) { - try { - return ci.getItemMeta().getDisplayName().startsWith(mark); - } catch (final Exception e) { - return false; - } - } + public static boolean hasMark(final ItemStack ci) { + try { + return ci.getItemMeta().getDisplayName().startsWith(mark); + } catch (final Exception e) { + return false; + } + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Util/MsgUtil.java b/src/main/java/org/maxgamer/QuickShop/Util/MsgUtil.java index 34f8e97..a916a20 100644 --- a/src/main/java/org/maxgamer/QuickShop/Util/MsgUtil.java +++ b/src/main/java/org/maxgamer/QuickShop/Util/MsgUtil.java @@ -17,192 +17,192 @@ import cn.citycraft.PluginHelper.config.FileConfig; import cn.citycraft.PluginHelper.tellraw.FancyMessage; public class MsgUtil { - private static FileConfig messages; - private static HashMap> player_messages = new HashMap>(); - private static QuickShop plugin; + private static FileConfig messages; + private static HashMap> player_messages = new HashMap>(); + private static QuickShop plugin; - /** - * Deletes any messages that are older than a week in the database, to save - * on space. - */ - public static void clean() { - plugin.getLogger().info("清理超过 一周 的 商店交易记录..."); - // 604800,000 msec = 1 week. - final long weekAgo = System.currentTimeMillis() - 604800000; - plugin.getDB().execute("DELETE FROM messages WHERE time < ?", weekAgo); - } + /** + * Deletes any messages that are older than a week in the database, to save + * on space. + */ + public static void clean() { + plugin.getLogger().info("清理超过 一周 的 商店交易记录..."); + // 604800,000 msec = 1 week. + final long weekAgo = System.currentTimeMillis() - 604800000; + plugin.getDB().execute("DELETE FROM messages WHERE time < ?", weekAgo); + } - /** - * Empties the queue of messages a player has and sends them to the player. - * - * @param p - * The player to message - * @return true if success, false if the player is offline or null - */ - public static boolean flush(final OfflinePlayer p) { - if (p != null && p.isOnline()) { - final String pName = p.getName(); - final LinkedList msgs = player_messages.get(pName); - if (msgs != null) { - for (final String msg : msgs) { - p.getPlayer().sendMessage(msg); - } - plugin.getDB().execute("DELETE FROM messages WHERE owner = ?", pName); - msgs.clear(); - } - return true; - } - return false; - } + /** + * Empties the queue of messages a player has and sends them to the player. + * + * @param p + * The player to message + * @return true if success, false if the player is offline or null + */ + public static boolean flush(final OfflinePlayer p) { + if (p != null && p.isOnline()) { + final String pName = p.getName(); + final LinkedList msgs = player_messages.get(pName); + if (msgs != null) { + for (final String msg : msgs) { + p.getPlayer().sendMessage(msg); + } + plugin.getDB().execute("DELETE FROM messages WHERE owner = ?", pName); + msgs.clear(); + } + return true; + } + return false; + } - public static void init(final QuickShop plugin) { - MsgUtil.plugin = plugin; - // Load messages.yml - messages = new FileConfig(plugin, "messages.yml"); - // Parse colour codes - Util.parseColours(messages); - } + public static void init(final QuickShop plugin) { + MsgUtil.plugin = plugin; + // Load messages.yml + messages = new FileConfig(plugin, "messages.yml"); + // Parse colour codes + Util.parseColours(messages); + } - /** - * loads all player purchase messages from the database. - */ - public static void loadTransactionMessages() { - player_messages.clear(); // Delete old messages - try { - final ResultSet rs = plugin.getDB().getConnection().prepareStatement("SELECT * FROM messages").executeQuery(); - while (rs.next()) { - final String owner = rs.getString("owner"); - final String message = rs.getString("message"); - LinkedList msgs = player_messages.get(owner); - if (msgs == null) { - msgs = new LinkedList(); - player_messages.put(owner, msgs); - } - msgs.add(message); - } - } catch (final SQLException e) { - e.printStackTrace(); - plugin.getLogger().warning("无法从数据库获得玩家的交易记录 跳过..."); - } - } + /** + * loads all player purchase messages from the database. + */ + public static void loadTransactionMessages() { + player_messages.clear(); // Delete old messages + try { + final ResultSet rs = plugin.getDB().getConnection().prepareStatement("SELECT * FROM messages").executeQuery(); + while (rs.next()) { + final String owner = rs.getString("owner"); + final String message = rs.getString("message"); + LinkedList msgs = player_messages.get(owner); + if (msgs == null) { + msgs = new LinkedList(); + player_messages.put(owner, msgs); + } + msgs.add(message); + } + } catch (final SQLException e) { + e.printStackTrace(); + plugin.getLogger().warning("无法从数据库获得玩家的交易记录 跳过..."); + } + } - public static String p(final String loc, final Object... args) { - String raw = messages.getString(loc); - if (raw == null || raw.isEmpty()) { - return ChatColor.RED + "语言文件词条丢失: " + loc; - } - if (args == null) { - return raw; - } - for (int i = 0; i < args.length; i++) { - raw = raw.replace("{" + i + "}", args[i] == null ? "null" : args[i].toString()); - } - return raw; - } + public static String p(final String loc, final Object... args) { + String raw = messages.getString(loc); + if (raw == null || raw.isEmpty()) { + return ChatColor.RED + "语言文件词条丢失: " + loc; + } + if (args == null) { + return raw; + } + for (int i = 0; i < args.length; i++) { + raw = raw.replace("{" + i + "}", args[i] == null ? "null" : args[i].toString()); + } + return raw; + } - public static void reload() { - messages.reload(); - Util.parseColours(messages); - } + public static void reload() { + messages.reload(); + Util.parseColours(messages); + } - /** - * @param player - * The name of the player to message - * @param message - * The message to send them Sends the given player a message if - * they're online. Else, if they're not online, queues it for - * them in the database. - */ - public static void send(final String player, final String message) { - @SuppressWarnings("deprecation") - final OfflinePlayer p = Bukkit.getOfflinePlayer(player); - if (p == null || !p.isOnline()) { - LinkedList msgs = player_messages.get(player); - if (msgs == null) { - msgs = new LinkedList(); - player_messages.put(player, msgs); - } - msgs.add(message); - final String q = "INSERT INTO messages (owner, message, time) VALUES (?, ?, ?)"; - plugin.getDB().execute(q, player.toString(), message, System.currentTimeMillis()); - } else { - p.getPlayer().sendMessage(message); - } - } + /** + * @param player + * The name of the player to message + * @param message + * The message to send them Sends the given player a message if + * they're online. Else, if they're not online, queues it for + * them in the database. + */ + public static void send(final String player, final String message) { + @SuppressWarnings("deprecation") + final OfflinePlayer p = Bukkit.getOfflinePlayer(player); + if (p == null || !p.isOnline()) { + LinkedList msgs = player_messages.get(player); + if (msgs == null) { + msgs = new LinkedList(); + player_messages.put(player, msgs); + } + msgs.add(message); + final String q = "INSERT INTO messages (owner, message, time) VALUES (?, ?, ?)"; + plugin.getDB().execute(q, player.toString(), message, System.currentTimeMillis()); + } else { + p.getPlayer().sendMessage(message); + } + } - public static void sendItemMessage(final Player p, final ItemStack is, final String msg) { - try { - final FancyMessage fm = FancyMessage.newFM(); - fm.text(msg).itemTooltip(is).send(p); - } catch (Exception | NoClassDefFoundError | NoSuchMethodError e) { - plugin.getConfigManager().setEnableMagicLib(false); - p.sendMessage(msg); - } - } + public static void sendItemMessage(final Player p, final ItemStack is, final String msg) { + try { + final FancyMessage fm = FancyMessage.newFM(); + fm.text(msg).itemTooltip(is).send(p); + } catch (Exception | NoClassDefFoundError | NoSuchMethodError e) { + plugin.getConfigManager().setEnableMagicLib(false); + p.sendMessage(msg); + } + } - public static void sendPurchaseSuccess(final Player p, final Shop shop, final int amount) { - p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.successful-purchase")); - final String msg = ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.item-name-and-price", "" + amount, shop.getDataName(), Util.format((amount * shop.getPrice()))); - sendItemMessage(p, shop.getItem(), msg); - p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); - } + public static void sendPurchaseSuccess(final Player p, final Shop shop, final int amount) { + p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.successful-purchase")); + final String msg = ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.item-name-and-price", "" + amount, shop.getDataName(), Util.format((amount * shop.getPrice()))); + sendItemMessage(p, shop.getItem(), msg); + p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); + } - public static void sendSellSuccess(final Player p, final Shop shop, final int amount) { - p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.successfully-sold")); - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.item-name-and-price", "" + amount, shop.getDataName(), Util.format((amount * shop.getPrice())))); - if (plugin.getConfig().getBoolean("show-tax")) { - final double tax = plugin.getConfig().getDouble("tax"); - final double total = amount * shop.getPrice(); - if (tax != 0) { - if (!p.getName().equals(shop.getOwner())) { - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.sell-tax", "" + Util.format((tax * total)))); - } else { - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.sell-tax-self")); - } - } - } - p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); - } + public static void sendSellSuccess(final Player p, final Shop shop, final int amount) { + p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.successfully-sold")); + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.item-name-and-price", "" + amount, shop.getDataName(), Util.format((amount * shop.getPrice())))); + if (plugin.getConfig().getBoolean("show-tax")) { + final double tax = plugin.getConfig().getDouble("tax"); + final double total = amount * shop.getPrice(); + if (tax != 0) { + if (!p.getName().equals(shop.getOwner())) { + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.sell-tax", "" + Util.format((tax * total)))); + } else { + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.sell-tax-self")); + } + } + } + p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); + } - public static void sendShopInfo(final Player p, final Shop shop) { - sendShopInfo(p, shop, shop.getRemainingStock()); - } + public static void sendShopInfo(final Player p, final Shop shop) { + sendShopInfo(p, shop, shop.getRemainingStock()); + } - @SuppressWarnings("deprecation") - public static void sendShopInfo(final Player p, final Shop shop, final int stock) { - // Potentially faster with an array? - final ItemStack item = shop.getItem(); - p.sendMessage(""); - p.sendMessage(""); - p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.shop-information")); - p.sendMessage(ChatColor.DARK_PURPLE + "| " - + MsgUtil.p("menu.owner", Bukkit.getOfflinePlayer(shop.getOwner()).getName() == null ? (shop.isUnlimited() ? "系统商店" : "未知") : Bukkit.getOfflinePlayer(shop.getOwner()).getName())); - final String msg = ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.item", shop.getDataName()); - sendItemMessage(p, shop.getItem(), msg); - if (Util.isTool(item.getType())) { - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.damage-percent-remaining", Util.getToolPercentage(item))); - } - if (shop.isSelling()) { - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.stock", "" + (stock == 10000 ? "无限" : stock))); - } else { - final int space = shop.getRemainingSpace(); - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.space", "" + (space == 10000 ? "无限" : space))); - } - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.price-per", shop.getDataName(), Util.format(shop.getPrice()))); - if (shop.isBuying()) { - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.this-shop-is-buying")); - } else { - p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.this-shop-is-selling")); - } - p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); - if (shop.isSelling()) { - p.sendMessage(MsgUtil.p("how-many-buy")); - } else { - final int items = Util.countItems(p.getInventory(), shop.getItem()); - p.sendMessage(MsgUtil.p("how-many-sell", items)); - } - } + @SuppressWarnings("deprecation") + public static void sendShopInfo(final Player p, final Shop shop, final int stock) { + // Potentially faster with an array? + final ItemStack item = shop.getItem(); + p.sendMessage(""); + p.sendMessage(""); + p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.shop-information")); + p.sendMessage(ChatColor.DARK_PURPLE + "| " + + MsgUtil.p("menu.owner", Bukkit.getOfflinePlayer(shop.getOwner()).getName() == null ? (shop.isUnlimited() ? "系统商店" : "未知") : Bukkit.getOfflinePlayer(shop.getOwner()).getName())); + final String msg = ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.item", shop.getDataName()); + sendItemMessage(p, shop.getItem(), msg); + if (Util.isTool(item.getType())) { + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.damage-percent-remaining", Util.getToolPercentage(item))); + } + if (shop.isSelling()) { + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.stock", "" + (stock == 10000 ? "无限" : stock))); + } else { + final int space = shop.getRemainingSpace(); + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.space", "" + (space == 10000 ? "无限" : space))); + } + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.price-per", shop.getDataName(), Util.format(shop.getPrice()))); + if (shop.isBuying()) { + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.this-shop-is-buying")); + } else { + p.sendMessage(ChatColor.DARK_PURPLE + "| " + MsgUtil.p("menu.this-shop-is-selling")); + } + p.sendMessage(ChatColor.DARK_PURPLE + "+---------------------------------------------------+"); + if (shop.isSelling()) { + p.sendMessage(MsgUtil.p("how-many-buy")); + } else { + final int items = Util.countItems(p.getInventory(), shop.getItem()); + p.sendMessage(MsgUtil.p("how-many-sell", items)); + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Util/NMS.java b/src/main/java/org/maxgamer/QuickShop/Util/NMS.java index 45d4016..9bc6d8f 100644 --- a/src/main/java/org/maxgamer/QuickShop/Util/NMS.java +++ b/src/main/java/org/maxgamer/QuickShop/Util/NMS.java @@ -5,12 +5,12 @@ import org.bukkit.inventory.ItemStack; public class NMS { - public static void safeGuard(final Item item) throws ClassNotFoundException { - rename(item.getItemStack()); - item.setPickupDelay(2147483647); - } + public static void safeGuard(final Item item) throws ClassNotFoundException { + rename(item.getItemStack()); + item.setPickupDelay(2147483647); + } - private static void rename(final ItemStack iStack) { - MarkUtil.addMark(iStack); - } + private static void rename(final ItemStack iStack) { + MarkUtil.addMark(iStack); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Util/Util.java b/src/main/java/org/maxgamer/QuickShop/Util/Util.java index 798fac2..60ea6a5 100644 --- a/src/main/java/org/maxgamer/QuickShop/Util/Util.java +++ b/src/main/java/org/maxgamer/QuickShop/Util/Util.java @@ -27,511 +27,511 @@ import cn.citycraft.PluginHelper.utils.LocalUtil; @SuppressWarnings("deprecation") public class Util { - private static HashSet blacklist = new HashSet(); - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#.##"); - private static QuickShop plugin; - private static HashSet shoppables = new HashSet(); - private static HashSet tools = new HashSet(); - private static HashSet transparent = new HashSet(); + private static HashSet blacklist = new HashSet(); + private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#.##"); + private static QuickShop plugin; + private static HashSet shoppables = new HashSet(); + private static HashSet tools = new HashSet(); + private static HashSet transparent = new HashSet(); - public static void addTransparentBlock(final Material m) { - if (transparent.add(m) == false) { - System.out.println("已添加透明方块: " + m.toString()); - } - if (!m.isBlock()) { - System.out.println(m + " 不是一个方块!"); - } - } + public static void addTransparentBlock(final Material m) { + if (transparent.add(m) == false) { + System.out.println("已添加透明方块: " + m.toString()); + } + if (!m.isBlock()) { + System.out.println(m + " 不是一个方块!"); + } + } - /** - * Returns true if the given block could be used to make a shop out of. - * - * @param b - * The block to check. Possibly a chest, dispenser, etc. - * @return True if it can be made into a shop, otherwise false. - */ - public static boolean canBeShop(final Block b) { - try { - final BlockState bs = b.getState(); - if (bs instanceof InventoryHolder == false) { - return false; - } - return shoppables.contains(bs.getType()); - } catch (final Exception e) { - return false; - } - } + /** + * Returns true if the given block could be used to make a shop out of. + * + * @param b + * The block to check. Possibly a chest, dispenser, etc. + * @return True if it can be made into a shop, otherwise false. + */ + public static boolean canBeShop(final Block b) { + try { + final BlockState bs = b.getState(); + if (bs instanceof InventoryHolder == false) { + return false; + } + return shoppables.contains(bs.getType()); + } catch (final Exception e) { + return false; + } + } - /** - * Counts the number of items in the given inventory where - * Util.matches(inventory item, item) is true. - * - * @param inv - * The inventory to search - * @param item - * The ItemStack to search for - * @return The number of items that match in this inventory. - */ - public static int countItems(final Inventory inv, final ItemStack item) { - int items = 0; - for (final ItemStack iStack : inv.getContents()) { - if (iStack == null) { - continue; - } - if (Util.matches(item, iStack)) { - items += iStack.getAmount(); - } - } - return items; - } + /** + * Counts the number of items in the given inventory where + * Util.matches(inventory item, item) is true. + * + * @param inv + * The inventory to search + * @param item + * The ItemStack to search for + * @return The number of items that match in this inventory. + */ + public static int countItems(final Inventory inv, final ItemStack item) { + int items = 0; + for (final ItemStack iStack : inv.getContents()) { + if (iStack == null) { + continue; + } + if (Util.matches(item, iStack)) { + items += iStack.getAmount(); + } + } + return items; + } - /** - * Returns the number of items that can be given to the inventory safely. - * - * @param inv - * The inventory to count - * @param item - * The item prototype. Material, durabiltiy and enchants must - * match for 'stackability' to occur. - * @return The number of items that can be given to the inventory safely. - */ - public static int countSpace(final Inventory inv, final ItemStack item) { - int space = 0; - for (final ItemStack iStack : inv.getContents()) { - if (iStack == null || iStack.getType() == Material.AIR) { - space += item.getMaxStackSize(); - } else if (matches(item, iStack)) { - space += item.getMaxStackSize() - iStack.getAmount(); - } - } - return space; - } + /** + * Returns the number of items that can be given to the inventory safely. + * + * @param inv + * The inventory to count + * @param item + * The item prototype. Material, durabiltiy and enchants must + * match for 'stackability' to occur. + * @return The number of items that can be given to the inventory safely. + */ + public static int countSpace(final Inventory inv, final ItemStack item) { + int space = 0; + for (final ItemStack iStack : inv.getContents()) { + if (iStack == null || iStack.getType() == Material.AIR) { + space += item.getMaxStackSize(); + } else if (matches(item, iStack)) { + space += item.getMaxStackSize() - iStack.getAmount(); + } + } + return space; + } - public static ItemStack deserialize(final String config) throws InvalidConfigurationException { - final YamlConfiguration cfg = new YamlConfiguration(); - cfg.loadFromString(config); - final ItemStack stack = cfg.getItemStack("item"); - return stack; - } + public static ItemStack deserialize(final String config) throws InvalidConfigurationException { + final YamlConfiguration cfg = new YamlConfiguration(); + cfg.loadFromString(config); + final ItemStack stack = cfg.getItemStack("item"); + return stack; + } - public static String firstUppercase(final String string) { - if (string.length() > 1) { - return Character.toUpperCase(string.charAt(0)) + string.substring(1).toLowerCase(); - } - return string.toUpperCase(); - } + public static String firstUppercase(final String string) { + if (string.length() > 1) { + return Character.toUpperCase(string.charAt(0)) + string.substring(1).toLowerCase(); + } + return string.toUpperCase(); + } - /** - * Formats the given number according to how vault would like it. E.g. $50 - * or 5 dollars. - * - * @return The formatted string. - */ - public static String format(final double n) { - try { - return DECIMAL_FORMAT.format(n) + plugin.getEcon().currencyNamePlural(); - } catch (final NumberFormatException e) { - return n + "元"; - } - } + /** + * Formats the given number according to how vault would like it. E.g. $50 + * or 5 dollars. + * + * @return The formatted string. + */ + public static String format(final double n) { + try { + return DECIMAL_FORMAT.format(n) + plugin.getEcon().currencyNamePlural(); + } catch (final NumberFormatException e) { + return n + "元"; + } + } - /** - * Fetches the block which the given sign is attached to - * - * @param sign - * The sign which is attached - * @return The block the sign is attached to - */ - public static Block getAttached(final Block b) { - try { - final Sign sign = (Sign) b.getState().getData(); // Throws a NPE - // sometimes?? - final BlockFace attached = sign.getAttachedFace(); - return attached == null ? null : b.getRelative(attached); - } catch (final NullPointerException e) { - return null; // /Not sure what causes this. - } - } + /** + * Fetches the block which the given sign is attached to + * + * @param sign + * The sign which is attached + * @return The block the sign is attached to + */ + public static Block getAttached(final Block b) { + try { + final Sign sign = (Sign) b.getState().getData(); // Throws a NPE + // sometimes?? + final BlockFace attached = sign.getAttachedFace(); + return attached == null ? null : b.getRelative(attached); + } catch (final NullPointerException e) { + return null; // /Not sure what causes this. + } + } - /** - * Fetches an ItemStack's name - For example, converting INK_SAC:11 to - * Dandellion Yellow, or WOOL:14 to Red Wool - * - * @param i - * The itemstack to fetch the name of - * @return The human readable item name. - */ - public static String getName(final ItemStack i) { - final String vanillaName = LocalUtil.getItemFullName(i); - return vanillaName; - } + /** + * Fetches an ItemStack's name - For example, converting INK_SAC:11 to + * Dandellion Yellow, or WOOL:14 to Red Wool + * + * @param i + * The itemstack to fetch the name of + * @return The human readable item name. + */ + public static String getName(final ItemStack i) { + final String vanillaName = LocalUtil.getItemFullName(i); + return vanillaName; + } - // Let's make very long names shorter for our sign - public static String getNameForSign(final ItemStack itemStack) { - String name = getName(itemStack); - if (name.length() > 16) { - name = name.substring(0, 16); - } - return name; - } + // Let's make very long names shorter for our sign + public static String getNameForSign(final ItemStack itemStack) { + String name = getName(itemStack); + if (name.length() > 16) { + name = name.substring(0, 16); + } + return name; + } - /** - * Returns the chest attached to the given chest. The given block must be a - * chest. - * - * @param b - * The chest to check. - * @return the block which is also a chest and connected to b. - */ - public static Block getSecondHalf(final Block b) { - if (b.getType().toString().contains("CHEST") == false) { - return null; - } - final Block[] blocks = new Block[4]; - blocks[0] = b.getRelative(1, 0, 0); - blocks[1] = b.getRelative(-1, 0, 0); - blocks[2] = b.getRelative(0, 0, 1); - blocks[3] = b.getRelative(0, 0, -1); - for (final Block c : blocks) { - if (c.getType() == b.getType()) { - return c; - } - } - return null; - } + /** + * Returns the chest attached to the given chest. The given block must be a + * chest. + * + * @param b + * The chest to check. + * @return the block which is also a chest and connected to b. + */ + public static Block getSecondHalf(final Block b) { + if (b.getType().toString().contains("CHEST") == false) { + return null; + } + final Block[] blocks = new Block[4]; + blocks[0] = b.getRelative(1, 0, 0); + blocks[1] = b.getRelative(-1, 0, 0); + blocks[2] = b.getRelative(0, 0, 1); + blocks[3] = b.getRelative(0, 0, -1); + for (final Block c : blocks) { + if (c.getType() == b.getType()) { + return c; + } + } + return null; + } - /** - * Gets the percentage (Without trailing %) damage on a tool. - * - * @param item - * The ItemStack of tools to check - * @return The percentage 'health' the tool has. (Opposite of total damage) - */ - public static String getToolPercentage(final ItemStack item) { - final double dura = item.getDurability(); - final double max = item.getType().getMaxDurability(); - return String.format("%.2f%%(剩余耐久%s/总耐久%s)", (1 - dura / max) * 100.0, max - dura, max); - } + /** + * Gets the percentage (Without trailing %) damage on a tool. + * + * @param item + * The ItemStack of tools to check + * @return The percentage 'health' the tool has. (Opposite of total damage) + */ + public static String getToolPercentage(final ItemStack item) { + final double dura = item.getDurability(); + final double max = item.getType().getMaxDurability(); + return String.format("%.2f%%(剩余耐久%s/总耐久%s)", (1 - dura / max) * 100.0, max - dura, max); + } - public static void initialize() { - tools.clear(); - blacklist.clear(); - shoppables.clear(); - transparent.clear(); + public static void initialize() { + tools.clear(); + blacklist.clear(); + shoppables.clear(); + transparent.clear(); - plugin = QuickShop.instance; - for (final String s : plugin.getConfig().getStringList("shop-blocks")) { - Material mat = Material.getMaterial(s.toUpperCase()); - if (mat == null) { - try { - mat = Material.getMaterial(Integer.parseInt(s)); - } catch (final NumberFormatException e) { - } - } - if (mat == null) { - plugin.getLogger().info("Invalid shop-block: " + s); - } else { - shoppables.add(mat); - } - } - tools.add(Material.BOW); - tools.add(Material.SHEARS); - tools.add(Material.FISHING_ROD); - tools.add(Material.FLINT_AND_STEEL); - tools.add(Material.CHAINMAIL_BOOTS); - tools.add(Material.CHAINMAIL_CHESTPLATE); - tools.add(Material.CHAINMAIL_HELMET); - tools.add(Material.CHAINMAIL_LEGGINGS); - tools.add(Material.WOOD_AXE); - tools.add(Material.WOOD_HOE); - tools.add(Material.WOOD_PICKAXE); - tools.add(Material.WOOD_SPADE); - tools.add(Material.WOOD_SWORD); - tools.add(Material.LEATHER_BOOTS); - tools.add(Material.LEATHER_CHESTPLATE); - tools.add(Material.LEATHER_HELMET); - tools.add(Material.LEATHER_LEGGINGS); - tools.add(Material.DIAMOND_AXE); - tools.add(Material.DIAMOND_HOE); - tools.add(Material.DIAMOND_PICKAXE); - tools.add(Material.DIAMOND_SPADE); - tools.add(Material.DIAMOND_SWORD); - tools.add(Material.DIAMOND_BOOTS); - tools.add(Material.DIAMOND_CHESTPLATE); - tools.add(Material.DIAMOND_HELMET); - tools.add(Material.DIAMOND_LEGGINGS); - tools.add(Material.STONE_AXE); - tools.add(Material.STONE_HOE); - tools.add(Material.STONE_PICKAXE); - tools.add(Material.STONE_SPADE); - tools.add(Material.STONE_SWORD); - tools.add(Material.GOLD_AXE); - tools.add(Material.GOLD_HOE); - tools.add(Material.GOLD_PICKAXE); - tools.add(Material.GOLD_SPADE); - tools.add(Material.GOLD_SWORD); - tools.add(Material.GOLD_BOOTS); - tools.add(Material.GOLD_CHESTPLATE); - tools.add(Material.GOLD_HELMET); - tools.add(Material.GOLD_LEGGINGS); - tools.add(Material.IRON_AXE); - tools.add(Material.IRON_HOE); - tools.add(Material.IRON_PICKAXE); - tools.add(Material.IRON_SPADE); - tools.add(Material.IRON_SWORD); - tools.add(Material.IRON_BOOTS); - tools.add(Material.IRON_CHESTPLATE); - tools.add(Material.IRON_HELMET); - tools.add(Material.IRON_LEGGINGS); - final List configBlacklist = plugin.getConfig().getStringList("blacklist"); - for (final String s : configBlacklist) { - Material mat = Material.getMaterial(s.toUpperCase()); - if (mat == null) { - mat = Material.getMaterial(Integer.parseInt(s)); - if (mat == null) { - plugin.getLogger().info(s + " is not a valid material. Check your spelling or ID"); - continue; - } - } - blacklist.add(mat); - } + plugin = QuickShop.instance; + for (final String s : plugin.getConfig().getStringList("shop-blocks")) { + Material mat = Material.getMaterial(s.toUpperCase()); + if (mat == null) { + try { + mat = Material.getMaterial(Integer.parseInt(s)); + } catch (final NumberFormatException e) { + } + } + if (mat == null) { + plugin.getLogger().info("Invalid shop-block: " + s); + } else { + shoppables.add(mat); + } + } + tools.add(Material.BOW); + tools.add(Material.SHEARS); + tools.add(Material.FISHING_ROD); + tools.add(Material.FLINT_AND_STEEL); + tools.add(Material.CHAINMAIL_BOOTS); + tools.add(Material.CHAINMAIL_CHESTPLATE); + tools.add(Material.CHAINMAIL_HELMET); + tools.add(Material.CHAINMAIL_LEGGINGS); + tools.add(Material.WOOD_AXE); + tools.add(Material.WOOD_HOE); + tools.add(Material.WOOD_PICKAXE); + tools.add(Material.WOOD_SPADE); + tools.add(Material.WOOD_SWORD); + tools.add(Material.LEATHER_BOOTS); + tools.add(Material.LEATHER_CHESTPLATE); + tools.add(Material.LEATHER_HELMET); + tools.add(Material.LEATHER_LEGGINGS); + tools.add(Material.DIAMOND_AXE); + tools.add(Material.DIAMOND_HOE); + tools.add(Material.DIAMOND_PICKAXE); + tools.add(Material.DIAMOND_SPADE); + tools.add(Material.DIAMOND_SWORD); + tools.add(Material.DIAMOND_BOOTS); + tools.add(Material.DIAMOND_CHESTPLATE); + tools.add(Material.DIAMOND_HELMET); + tools.add(Material.DIAMOND_LEGGINGS); + tools.add(Material.STONE_AXE); + tools.add(Material.STONE_HOE); + tools.add(Material.STONE_PICKAXE); + tools.add(Material.STONE_SPADE); + tools.add(Material.STONE_SWORD); + tools.add(Material.GOLD_AXE); + tools.add(Material.GOLD_HOE); + tools.add(Material.GOLD_PICKAXE); + tools.add(Material.GOLD_SPADE); + tools.add(Material.GOLD_SWORD); + tools.add(Material.GOLD_BOOTS); + tools.add(Material.GOLD_CHESTPLATE); + tools.add(Material.GOLD_HELMET); + tools.add(Material.GOLD_LEGGINGS); + tools.add(Material.IRON_AXE); + tools.add(Material.IRON_HOE); + tools.add(Material.IRON_PICKAXE); + tools.add(Material.IRON_SPADE); + tools.add(Material.IRON_SWORD); + tools.add(Material.IRON_BOOTS); + tools.add(Material.IRON_CHESTPLATE); + tools.add(Material.IRON_HELMET); + tools.add(Material.IRON_LEGGINGS); + final List configBlacklist = plugin.getConfig().getStringList("blacklist"); + for (final String s : configBlacklist) { + Material mat = Material.getMaterial(s.toUpperCase()); + if (mat == null) { + mat = Material.getMaterial(Integer.parseInt(s)); + if (mat == null) { + plugin.getLogger().info(s + " is not a valid material. Check your spelling or ID"); + continue; + } + } + blacklist.add(mat); + } - // ToDo: add extras to config file - addTransparentBlock(Material.AIR); - /* Misc */ - addTransparentBlock(Material.CAKE_BLOCK); - /* Redstone Material */ - addTransparentBlock(Material.REDSTONE_WIRE); - /* Redstone Torches */ - addTransparentBlock(Material.REDSTONE_TORCH_OFF); - addTransparentBlock(Material.REDSTONE_TORCH_ON); - /* Diodes (Repeaters) */ - addTransparentBlock(Material.DIODE_BLOCK_OFF); - addTransparentBlock(Material.DIODE_BLOCK_ON); - /* Power Sources */ - addTransparentBlock(Material.DETECTOR_RAIL); - addTransparentBlock(Material.LEVER); - addTransparentBlock(Material.STONE_BUTTON); - addTransparentBlock(Material.WOOD_BUTTON); - addTransparentBlock(Material.STONE_PLATE); - addTransparentBlock(Material.WOOD_PLATE); - /* Nature Material */ - addTransparentBlock(Material.RED_MUSHROOM); - addTransparentBlock(Material.BROWN_MUSHROOM); - addTransparentBlock(Material.RED_ROSE); - addTransparentBlock(Material.YELLOW_FLOWER); - addTransparentBlock(Material.FLOWER_POT); - /* Greens */ - addTransparentBlock(Material.LONG_GRASS); - addTransparentBlock(Material.VINE); - addTransparentBlock(Material.WATER_LILY); - /* Seedy things */ - addTransparentBlock(Material.MELON_STEM); - addTransparentBlock(Material.PUMPKIN_STEM); - addTransparentBlock(Material.CROPS); - addTransparentBlock(Material.NETHER_WARTS); - /* Semi-nature */ - addTransparentBlock(Material.SNOW); - addTransparentBlock(Material.FIRE); - addTransparentBlock(Material.WEB); - addTransparentBlock(Material.TRIPWIRE); - addTransparentBlock(Material.TRIPWIRE_HOOK); - /* Stairs */ - addTransparentBlock(Material.COBBLESTONE_STAIRS); - addTransparentBlock(Material.BRICK_STAIRS); - addTransparentBlock(Material.SANDSTONE_STAIRS); - addTransparentBlock(Material.NETHER_BRICK_STAIRS); - addTransparentBlock(Material.SMOOTH_STAIRS); - /* Wood Stairs */ - addTransparentBlock(Material.BIRCH_WOOD_STAIRS); - addTransparentBlock(Material.WOOD_STAIRS); - addTransparentBlock(Material.JUNGLE_WOOD_STAIRS); - addTransparentBlock(Material.SPRUCE_WOOD_STAIRS); - /* Lava & Water */ - addTransparentBlock(Material.LAVA); - addTransparentBlock(Material.STATIONARY_LAVA); - addTransparentBlock(Material.WATER); - addTransparentBlock(Material.STATIONARY_WATER); - /* Saplings and bushes */ - addTransparentBlock(Material.SAPLING); - addTransparentBlock(Material.DEAD_BUSH); - /* Construction Material */ - /* Fences */ - addTransparentBlock(Material.FENCE); - addTransparentBlock(Material.FENCE_GATE); - addTransparentBlock(Material.IRON_FENCE); - addTransparentBlock(Material.NETHER_FENCE); - /* Ladders, Signs */ - addTransparentBlock(Material.LADDER); - addTransparentBlock(Material.SIGN_POST); - addTransparentBlock(Material.WALL_SIGN); - /* Bed */ - addTransparentBlock(Material.BED_BLOCK); - /* Pistons */ - addTransparentBlock(Material.PISTON_EXTENSION); - addTransparentBlock(Material.PISTON_MOVING_PIECE); - addTransparentBlock(Material.RAILS); - /* Torch & Trapdoor */ - addTransparentBlock(Material.TORCH); - addTransparentBlock(Material.TRAP_DOOR); - /* New */ - addTransparentBlock(Material.BREWING_STAND); - addTransparentBlock(Material.WOODEN_DOOR); - addTransparentBlock(Material.WOOD_STEP); - } + // ToDo: add extras to config file + addTransparentBlock(Material.AIR); + /* Misc */ + addTransparentBlock(Material.CAKE_BLOCK); + /* Redstone Material */ + addTransparentBlock(Material.REDSTONE_WIRE); + /* Redstone Torches */ + addTransparentBlock(Material.REDSTONE_TORCH_OFF); + addTransparentBlock(Material.REDSTONE_TORCH_ON); + /* Diodes (Repeaters) */ + addTransparentBlock(Material.DIODE_BLOCK_OFF); + addTransparentBlock(Material.DIODE_BLOCK_ON); + /* Power Sources */ + addTransparentBlock(Material.DETECTOR_RAIL); + addTransparentBlock(Material.LEVER); + addTransparentBlock(Material.STONE_BUTTON); + addTransparentBlock(Material.WOOD_BUTTON); + addTransparentBlock(Material.STONE_PLATE); + addTransparentBlock(Material.WOOD_PLATE); + /* Nature Material */ + addTransparentBlock(Material.RED_MUSHROOM); + addTransparentBlock(Material.BROWN_MUSHROOM); + addTransparentBlock(Material.RED_ROSE); + addTransparentBlock(Material.YELLOW_FLOWER); + addTransparentBlock(Material.FLOWER_POT); + /* Greens */ + addTransparentBlock(Material.LONG_GRASS); + addTransparentBlock(Material.VINE); + addTransparentBlock(Material.WATER_LILY); + /* Seedy things */ + addTransparentBlock(Material.MELON_STEM); + addTransparentBlock(Material.PUMPKIN_STEM); + addTransparentBlock(Material.CROPS); + addTransparentBlock(Material.NETHER_WARTS); + /* Semi-nature */ + addTransparentBlock(Material.SNOW); + addTransparentBlock(Material.FIRE); + addTransparentBlock(Material.WEB); + addTransparentBlock(Material.TRIPWIRE); + addTransparentBlock(Material.TRIPWIRE_HOOK); + /* Stairs */ + addTransparentBlock(Material.COBBLESTONE_STAIRS); + addTransparentBlock(Material.BRICK_STAIRS); + addTransparentBlock(Material.SANDSTONE_STAIRS); + addTransparentBlock(Material.NETHER_BRICK_STAIRS); + addTransparentBlock(Material.SMOOTH_STAIRS); + /* Wood Stairs */ + addTransparentBlock(Material.BIRCH_WOOD_STAIRS); + addTransparentBlock(Material.WOOD_STAIRS); + addTransparentBlock(Material.JUNGLE_WOOD_STAIRS); + addTransparentBlock(Material.SPRUCE_WOOD_STAIRS); + /* Lava & Water */ + addTransparentBlock(Material.LAVA); + addTransparentBlock(Material.STATIONARY_LAVA); + addTransparentBlock(Material.WATER); + addTransparentBlock(Material.STATIONARY_WATER); + /* Saplings and bushes */ + addTransparentBlock(Material.SAPLING); + addTransparentBlock(Material.DEAD_BUSH); + /* Construction Material */ + /* Fences */ + addTransparentBlock(Material.FENCE); + addTransparentBlock(Material.FENCE_GATE); + addTransparentBlock(Material.IRON_FENCE); + addTransparentBlock(Material.NETHER_FENCE); + /* Ladders, Signs */ + addTransparentBlock(Material.LADDER); + addTransparentBlock(Material.SIGN_POST); + addTransparentBlock(Material.WALL_SIGN); + /* Bed */ + addTransparentBlock(Material.BED_BLOCK); + /* Pistons */ + addTransparentBlock(Material.PISTON_EXTENSION); + addTransparentBlock(Material.PISTON_MOVING_PIECE); + addTransparentBlock(Material.RAILS); + /* Torch & Trapdoor */ + addTransparentBlock(Material.TORCH); + addTransparentBlock(Material.TRAP_DOOR); + /* New */ + addTransparentBlock(Material.BREWING_STAND); + addTransparentBlock(Material.WOODEN_DOOR); + addTransparentBlock(Material.WOOD_STEP); + } - /** - * @param m - * The material to check if it is blacklisted - * @return true if the material is black listed. False if not. - */ - public static boolean isBlacklisted(final Material m) { - return blacklist.contains(m); - } + /** + * @param m + * The material to check if it is blacklisted + * @return true if the material is black listed. False if not. + */ + public static boolean isBlacklisted(final Material m) { + return blacklist.contains(m); + } - /** - * Returns true if the given location is loaded or not. - * - * @param loc - * The location - * @return true if the given location is loaded or not. - */ - public static boolean isLoaded(final Location loc) { - // System.out.println("Checking isLoaded(Location loc)"); - if (loc.getWorld() == null) { - // System.out.println("Is not loaded. (No world)"); - return false; - } - // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT - // location rounded to the nearest 16. - final int x = (int) Math.floor((loc.getBlockX()) / 16.0); - final int z = (int) Math.floor((loc.getBlockZ()) / 16.0); - if (loc.getWorld().isChunkLoaded(x, z)) { - // System.out.println("Chunk is loaded " + x + ", " + z); - return true; - } - // System.out.println("Chunk is NOT loaded " + x + ", " + z); - return false; - } + /** + * Returns true if the given location is loaded or not. + * + * @param loc + * The location + * @return true if the given location is loaded or not. + */ + public static boolean isLoaded(final Location loc) { + // System.out.println("Checking isLoaded(Location loc)"); + if (loc.getWorld() == null) { + // System.out.println("Is not loaded. (No world)"); + return false; + } + // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT + // location rounded to the nearest 16. + final int x = (int) Math.floor((loc.getBlockX()) / 16.0); + final int z = (int) Math.floor((loc.getBlockZ()) / 16.0); + if (loc.getWorld().isChunkLoaded(x, z)) { + // System.out.println("Chunk is loaded " + x + ", " + z); + return true; + } + // System.out.println("Chunk is NOT loaded " + x + ", " + z); + return false; + } - /** - * @param mat - * The material to check - * @return Returns true if the item is a tool (Has durability) or false if - * it doesn't. - */ - public static boolean isTool(final Material mat) { - return tools.contains(mat); - } + /** + * @param mat + * The material to check + * @return Returns true if the item is a tool (Has durability) or false if + * it doesn't. + */ + public static boolean isTool(final Material mat) { + return tools.contains(mat); + } - public static boolean isTransparent(final Material m) { - final boolean trans = transparent.contains(m); - return trans; - } + public static boolean isTransparent(final Material m) { + final boolean trans = transparent.contains(m); + return trans; + } - /** - * Converts a string into an item from the database. - * - * @param itemString - * The database string. Is the result of makeString(ItemStack - * item). - * @return A new itemstack, with the properties given in the string - */ - public static ItemStack makeItem(final String itemString) { - final String[] itemInfo = itemString.split(":"); - final ItemStack item = new ItemStack(Material.getMaterial(itemInfo[0])); - final MaterialData data = new MaterialData(Integer.parseInt(itemInfo[1])); - item.setData(data); - item.setDurability(Short.parseShort(itemInfo[2])); - item.setAmount(Integer.parseInt(itemInfo[3])); - for (int i = 4; i < itemInfo.length; i = i + 2) { - int level = Integer.parseInt(itemInfo[i + 1]); - final Enchantment ench = Enchantment.getByName(itemInfo[i]); - if (ench == null) { - continue; // Invalid - } - if (ench.canEnchantItem(item)) { - if (level <= 0) { - continue; - } - level = Math.min(ench.getMaxLevel(), level); - item.addEnchantment(ench, level); - } - } - return item; - } + /** + * Converts a string into an item from the database. + * + * @param itemString + * The database string. Is the result of makeString(ItemStack + * item). + * @return A new itemstack, with the properties given in the string + */ + public static ItemStack makeItem(final String itemString) { + final String[] itemInfo = itemString.split(":"); + final ItemStack item = new ItemStack(Material.getMaterial(itemInfo[0])); + final MaterialData data = new MaterialData(Integer.parseInt(itemInfo[1])); + item.setData(data); + item.setDurability(Short.parseShort(itemInfo[2])); + item.setAmount(Integer.parseInt(itemInfo[3])); + for (int i = 4; i < itemInfo.length; i = i + 2) { + int level = Integer.parseInt(itemInfo[i + 1]); + final Enchantment ench = Enchantment.getByName(itemInfo[i]); + if (ench == null) { + continue; // Invalid + } + if (ench.canEnchantItem(item)) { + if (level <= 0) { + continue; + } + level = Math.min(ench.getMaxLevel(), level); + item.addEnchantment(ench, level); + } + } + return item; + } - /** - * Compares two items to each other. Returns true if they match. - * - * @param stack1 - * The first item stack - * @param stack2 - * The second item stack - * @return true if the itemstacks match. (Material, durability, enchants, name) - */ - public static boolean matches(final ItemStack stack1, final ItemStack stack2) { - if (stack1 == stack2) { - return true; // Referring to the same thing, or both are null. - } - if (stack1 == null || stack2 == null) { - return false; // One of them is null (Can't be both, see above) - } - if (stack1.getType() != stack2.getType()) { - return false; // Not the same material - } - if (stack1.getDurability() != stack2.getDurability()) { - return false; // Not the same durability - } - if (!stack1.getEnchantments().equals(stack2.getEnchantments())) { - return false; // They have the same enchants - } - if (stack1.getItemMeta().hasDisplayName() || stack2.getItemMeta().hasDisplayName()) { - if (stack1.getItemMeta().hasDisplayName() && stack2.getItemMeta().hasDisplayName()) { - if (!stack1.getItemMeta().getDisplayName().equals(stack2.getItemMeta().getDisplayName())) { - return false; // items have different display name - } - } else { - return false; // one of the item stacks have a display name - } - } - try { - Class.forName("org.bukkit.inventory.meta.EnchantmentStorageMeta"); - final boolean book1 = stack1.getItemMeta() instanceof EnchantmentStorageMeta; - final boolean book2 = stack2.getItemMeta() instanceof EnchantmentStorageMeta; - if (book1 != book2) { - return false;// One has enchantment meta, the other does not. - } - if (book1 == true) { // They are the same here (both true or both - // false). So if one is true, the other is - // true. - final Map ench1 = ((EnchantmentStorageMeta) stack1.getItemMeta()).getStoredEnchants(); - final Map ench2 = ((EnchantmentStorageMeta) stack2.getItemMeta()).getStoredEnchants(); - if (!ench1.equals(ench2)) { - return false; // Enchants aren't the same. - } - } - } catch (final ClassNotFoundException e) { - // Nothing. They dont have a build high enough to support this. - } - return true; - } + /** + * Compares two items to each other. Returns true if they match. + * + * @param stack1 + * The first item stack + * @param stack2 + * The second item stack + * @return true if the itemstacks match. (Material, durability, enchants, name) + */ + public static boolean matches(final ItemStack stack1, final ItemStack stack2) { + if (stack1 == stack2) { + return true; // Referring to the same thing, or both are null. + } + if (stack1 == null || stack2 == null) { + return false; // One of them is null (Can't be both, see above) + } + if (stack1.getType() != stack2.getType()) { + return false; // Not the same material + } + if (stack1.getDurability() != stack2.getDurability()) { + return false; // Not the same durability + } + if (!stack1.getEnchantments().equals(stack2.getEnchantments())) { + return false; // They have the same enchants + } + if (stack1.getItemMeta().hasDisplayName() || stack2.getItemMeta().hasDisplayName()) { + if (stack1.getItemMeta().hasDisplayName() && stack2.getItemMeta().hasDisplayName()) { + if (!stack1.getItemMeta().getDisplayName().equals(stack2.getItemMeta().getDisplayName())) { + return false; // items have different display name + } + } else { + return false; // one of the item stacks have a display name + } + } + try { + Class.forName("org.bukkit.inventory.meta.EnchantmentStorageMeta"); + final boolean book1 = stack1.getItemMeta() instanceof EnchantmentStorageMeta; + final boolean book2 = stack2.getItemMeta() instanceof EnchantmentStorageMeta; + if (book1 != book2) { + return false;// One has enchantment meta, the other does not. + } + if (book1 == true) { // They are the same here (both true or both + // false). So if one is true, the other is + // true. + final Map ench1 = ((EnchantmentStorageMeta) stack1.getItemMeta()).getStoredEnchants(); + final Map ench2 = ((EnchantmentStorageMeta) stack2.getItemMeta()).getStoredEnchants(); + if (!ench1.equals(ench2)) { + return false; // Enchants aren't the same. + } + } + } catch (final ClassNotFoundException e) { + // Nothing. They dont have a build high enough to support this. + } + return true; + } - public static void parseColours(final YamlConfiguration config) { - final Set keys = config.getKeys(true); - for (final String key : keys) { - String filtered = config.getString(key); - if (filtered.startsWith("MemorySection")) { - continue; - } - filtered = ChatColor.translateAlternateColorCodes('&', filtered); - config.set(key, filtered); - } - } + public static void parseColours(final YamlConfiguration config) { + final Set keys = config.getKeys(true); + for (final String key : keys) { + String filtered = config.getString(key); + if (filtered.startsWith("MemorySection")) { + continue; + } + filtered = ChatColor.translateAlternateColorCodes('&', filtered); + config.set(key, filtered); + } + } - public static String serialize(final ItemStack iStack) { - final YamlConfiguration cfg = new YamlConfiguration(); - cfg.set("item", iStack); - return cfg.saveToString(); - } + public static String serialize(final ItemStack iStack) { + final YamlConfiguration cfg = new YamlConfiguration(); + cfg.set("item", iStack); + return cfg.saveToString(); + } } diff --git a/src/main/java/org/maxgamer/QuickShop/Watcher/ItemWatcher.java b/src/main/java/org/maxgamer/QuickShop/Watcher/ItemWatcher.java index 2f39bf7..fdb2a63 100644 --- a/src/main/java/org/maxgamer/QuickShop/Watcher/ItemWatcher.java +++ b/src/main/java/org/maxgamer/QuickShop/Watcher/ItemWatcher.java @@ -17,36 +17,36 @@ import org.maxgamer.QuickShop.Shop.ShopChunk; * Also deletes invalid items. */ public class ItemWatcher implements Runnable { - private QuickShop plugin; + private QuickShop plugin; - public ItemWatcher(QuickShop plugin) { - this.plugin = plugin; - } + public ItemWatcher(QuickShop plugin) { + this.plugin = plugin; + } - public void run() { - List toRemove = new ArrayList(1); - for (Entry>> inWorld : plugin.getShopManager().getShops().entrySet()) { - // This world - World world = Bukkit.getWorld(inWorld.getKey()); - if (world == null) - continue; // world not loaded. - for (Entry> inChunk : inWorld.getValue().entrySet()) { - if (!world.isChunkLoaded(inChunk.getKey().getX(), inChunk.getKey().getZ())) { - // If the chunk is not loaded, next chunk! - continue; - } - for (Shop shop : inChunk.getValue().values()) { - // Validate the shop. - if (!shop.isValid()) { - toRemove.add(shop); - continue; - } - } - } - } - // Now we can remove it. - for (Shop shop : toRemove) { - shop.delete(); - } - } + public void run() { + List toRemove = new ArrayList(1); + for (Entry>> inWorld : plugin.getShopManager().getShops().entrySet()) { + // This world + World world = Bukkit.getWorld(inWorld.getKey()); + if (world == null) + continue; // world not loaded. + for (Entry> inChunk : inWorld.getValue().entrySet()) { + if (!world.isChunkLoaded(inChunk.getKey().getX(), inChunk.getKey().getZ())) { + // If the chunk is not loaded, next chunk! + continue; + } + for (Shop shop : inChunk.getValue().values()) { + // Validate the shop. + if (!shop.isValid()) { + toRemove.add(shop); + continue; + } + } + } + } + // Now we can remove it. + for (Shop shop : toRemove) { + shop.delete(); + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/QuickShop/Watcher/LogWatcher.java b/src/main/java/org/maxgamer/QuickShop/Watcher/LogWatcher.java index 117e275..f1529c5 100644 --- a/src/main/java/org/maxgamer/QuickShop/Watcher/LogWatcher.java +++ b/src/main/java/org/maxgamer/QuickShop/Watcher/LogWatcher.java @@ -11,43 +11,43 @@ import org.bukkit.scheduler.BukkitTask; import org.maxgamer.QuickShop.QuickShop; public class LogWatcher implements Runnable { - private PrintStream ps; - private ArrayList logs = new ArrayList(5); - public BukkitTask task; + private PrintStream ps; + private ArrayList logs = new ArrayList(5); + public BukkitTask task; - public LogWatcher(QuickShop plugin, File log) { - try { - if (!log.exists()) { - log.createNewFile(); - } - FileOutputStream fos = new FileOutputStream(log, true); - this.ps = new PrintStream(fos); - } catch (FileNotFoundException e) { - e.printStackTrace(); - plugin.getLogger().severe("日志文件未找到!"); - } catch (IOException e) { - e.printStackTrace(); - plugin.getLogger().severe("无法创建日志文件!"); - } - } - - @Override - public void run() { - synchronized (logs) { - for (String s : logs) { - ps.println(s); - } - logs.clear(); - } - } + public LogWatcher(QuickShop plugin, File log) { + try { + if (!log.exists()) { + log.createNewFile(); + } + FileOutputStream fos = new FileOutputStream(log, true); + this.ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + e.printStackTrace(); + plugin.getLogger().severe("日志文件未找到!"); + } catch (IOException e) { + e.printStackTrace(); + plugin.getLogger().severe("无法创建日志文件!"); + } + } - public void add(String s) { - synchronized (logs) { - logs.add(s); - } - } + @Override + public void run() { + synchronized (logs) { + for (String s : logs) { + ps.println(s); + } + logs.clear(); + } + } - public void close() { - this.ps.close(); - } + public void add(String s) { + synchronized (logs) { + logs.add(s); + } + } + + public void close() { + this.ps.close(); + } } \ No newline at end of file