From 88dc80f02df0405294c5d420539a25fcbe37c43d Mon Sep 17 00:00:00 2001 From: Ghost_chu <2908803755@qq.com> Date: Tue, 16 Jul 2019 22:19:01 +0800 Subject: [PATCH] Code sort Former-commit-id: 9cfc97eb7f247f12e688776d879be05a83bc188e [formerly 60194df8646944c7e1a4d05358abdbcfbf3d8f74] Former-commit-id: 15842b30f5298431b75778c6cd75d822e1192f9e --- .../org/maxgamer/quickshop/BootError.java | 8 +- .../maxgamer/quickshop/BuiltInSolution.java | 19 +- .../quickshop/Command/CommandContainer.java | 6 +- .../quickshop/Command/CommandManager.java | 88 +- .../quickshop/Command/CommandProcesser.java | 34 +- .../quickshop/Database/BufferStatement.java | 2 +- .../maxgamer/quickshop/Database/Database.java | 176 +- .../quickshop/Database/DatabaseCore.java | 8 +- .../quickshop/Database/DatabaseHelper.java | 152 +- .../quickshop/Database/DatabaseManager.java | 40 +- .../quickshop/Database/MySQLCore.java | 68 +- .../quickshop/Database/SQLiteCore.java | 74 +- .../maxgamer/quickshop/Economy/Economy.java | 136 +- .../quickshop/Economy/EconomyCore.java | 44 +- .../quickshop/Economy/EconomyType.java | 12 +- .../quickshop/Economy/Economy_Reserve.java | 20 +- .../quickshop/Economy/Economy_Vault.java | 70 +- .../quickshop/Event/ShopCreateEvent.java | 6 +- .../quickshop/Event/ShopDeleteEvent.java | 4 +- .../Event/ShopDisplayItemSpawnEvent.java | 4 +- .../Event/ShopInventoryPreviewEvent.java | 4 +- .../quickshop/Event/ShopLoadEvent.java | 7 +- .../Event/ShopModeratorChangedEvent.java | 4 +- .../quickshop/Event/ShopPreCreateEvent.java | 4 +- .../Event/ShopPriceChangedEvent.java | 4 +- .../Event/ShopSuccessPurchaseEvent.java | 20 +- .../quickshop/Event/ShopUpdateEvent.java | 11 +- .../InternalListener/InternalListener.java | 14 +- .../quickshop/Listeners/BlockListener.java | 63 +- .../quickshop/Listeners/LockListener.java | 172 +- .../quickshop/Listeners/PlayerListener.java | 80 +- .../Listeners/ShopProtectionListener.java | 150 +- .../java/org/maxgamer/quickshop/Metrics.java | 1276 +++++++------- .../org/maxgamer/quickshop/QuickShop.java | 535 +++--- .../quickshop/Shop/ArmorStandDisplayItem.java | 109 +- .../quickshop/Shop/ContainerShop.java | 363 ++-- .../maxgamer/quickshop/Shop/DisplayItem.java | 215 +-- .../maxgamer/quickshop/Shop/DisplayType.java | 20 +- .../org/maxgamer/quickshop/Shop/Info.java | 16 +- .../quickshop/Shop/InventoryPreview.java | 47 +- .../quickshop/Shop/RealDisplayItem.java | 190 +-- .../org/maxgamer/quickshop/Shop/Shop.java | 375 +++-- .../maxgamer/quickshop/Shop/ShopLoader.java | 167 +- .../maxgamer/quickshop/Shop/ShopManager.java | 920 +++++------ .../quickshop/Shop/ShopModerator.java | 114 +- .../quickshop/Shop/ShopProtectionFlag.java | 2 +- .../org/maxgamer/quickshop/Shop/ShopType.java | 12 +- .../quickshop/Util/ChatSheetPrinter.java | 36 +- .../quickshop/Util/Compatibility.java | 5 +- .../quickshop/Util/IncompatibleChecker.java | 32 +- .../maxgamer/quickshop/Util/ItemMatcher.java | 218 +-- .../org/maxgamer/quickshop/Util/ItemNMS.java | 108 +- .../org/maxgamer/quickshop/Util/MsgUtil.java | 1225 +++++++------- .../quickshop/Util/SentryErrorReporter.java | 194 +-- .../org/maxgamer/quickshop/Util/Timer.java | 42 +- .../quickshop/Util/UpdateInfomation.java | 7 +- .../org/maxgamer/quickshop/Util/Updater.java | 68 +- .../org/maxgamer/quickshop/Util/Util.java | 1460 ++++++++--------- .../quickshop/Watcher/DisplayWatcher.java | 28 +- .../quickshop/Watcher/LogWatcher.java | 43 +- .../quickshop/Watcher/SyncTaskWatcher.java | 4 +- .../quickshop/Watcher/UpdateWatcher.java | 274 ++-- 62 files changed, 4817 insertions(+), 4792 deletions(-) diff --git a/src/main/java/org/maxgamer/quickshop/BootError.java b/src/main/java/org/maxgamer/quickshop/BootError.java index c9b5cdd3a..7901e0067 100644 --- a/src/main/java/org/maxgamer/quickshop/BootError.java +++ b/src/main/java/org/maxgamer/quickshop/BootError.java @@ -21,10 +21,6 @@ public class BootError { } } - public String[] getErrors() { - return errors; - } - /** * Print the errors. * ##################################################### @@ -46,4 +42,8 @@ public class BootError { } + public String[] getErrors() { + return errors; + } + } diff --git a/src/main/java/org/maxgamer/quickshop/BuiltInSolution.java b/src/main/java/org/maxgamer/quickshop/BuiltInSolution.java index 7d496b413..ae47cfaed 100644 --- a/src/main/java/org/maxgamer/quickshop/BuiltInSolution.java +++ b/src/main/java/org/maxgamer/quickshop/BuiltInSolution.java @@ -8,6 +8,16 @@ import org.bukkit.ChatColor; */ class BuiltInSolution { private static QuickShop plugin = QuickShop.instance; + + /** + * Call when failed load database, and use this to check the reason. + * + * @return The reason of error. + */ + static BootError databaseError() { + return new BootError("Error connecting to the database", "Make sure your database service is running.", "Or check the configuration in your config.yml"); + } + /** * Call when failed load economy system, and use this to check the reason. * @@ -31,13 +41,4 @@ class BuiltInSolution { return new BootError("No Economy plugin detected, did you installed and loaded them? Make sure they loaded before QuickShop.", "Install an economy plugin to get Vault or Reserve working."); } - - /** - * Call when failed load database, and use this to check the reason. - * - * @return The reason of error. - */ - static BootError databaseError() { - return new BootError("Error connecting to the database", "Make sure your database service is running.", "Or check the configuration in your config.yml"); - } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Command/CommandContainer.java b/src/main/java/org/maxgamer/quickshop/Command/CommandContainer.java index 6bca68522..6e0e86bc7 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/CommandContainer.java +++ b/src/main/java/org/maxgamer/quickshop/Command/CommandContainer.java @@ -7,8 +7,8 @@ import lombok.*; @Data @Builder public class CommandContainer { - private String prefix; // E.g /qs - @Singular private List permissions; // E.g quickshop.unlimited - private boolean hidden; // Hide from help, tabcomplete private CommandProcesser executor; + private boolean hidden; // Hide from help, tabcomplete + @Singular private List permissions; // E.g quickshop.unlimited + private String prefix; // E.g /qs } diff --git a/src/main/java/org/maxgamer/quickshop/Command/CommandManager.java b/src/main/java/org/maxgamer/quickshop/Command/CommandManager.java index 8793fea52..65a8e0278 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/CommandManager.java +++ b/src/main/java/org/maxgamer/quickshop/Command/CommandManager.java @@ -87,50 +87,6 @@ public class CommandManager implements TabCompleter, CommandExecutor { .build()); } - private void registerCmd(CommandContainer container) { - if (!cmds.contains(container)) - cmds.add(container); - } - - @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] cmdArg) { - //No args, it shouldn't happend - if (sender instanceof Player) { - if (QuickShop.instance.getConfig().getBoolean("effect.sound.ontabcomplete")) { - Player player = (Player) sender; - ((Player) sender).playSound(player.getLocation(), Sound.BLOCK_DISPENSER_FAIL, 80.0F, 1.0F); - } - } - if (cmdArg.length == 0 || cmdArg.length == 1) { - //No args - return getRootContainer().getExecutor().onTabComplete(sender, commandLabel, cmdArg); - } - //Main args/more args - String[] passthroughArgs; - passthroughArgs = new String[cmdArg.length - 1]; - System.arraycopy(cmdArg, 1, passthroughArgs, 0, passthroughArgs.length); - for (CommandContainer container : cmds) { - Util.debugLog("Checking prefix with container: " + container.getPrefix() + " - " + cmdArg[0]); - if (!container.getPrefix().toLowerCase().startsWith(cmdArg[0])) - continue; - Util.debugLog("Checking permission with container: " + container.getPrefix() + " - " + cmdArg[0]); - List requirePermissions = container.getPermissions(); - if (container.getPermissions() != null) - for (String requirePermission : requirePermissions) { - if (requirePermission != null && !requirePermission.isEmpty() && !sender.hasPermission(requirePermission)) { - Util.debugLog("Sender " + sender - .getName() + " trying tab-complete the command: " + commandLabel + " " + Util - .array2String(cmdArg) + ", but no permission " + requirePermission); - return null; - } - } - Util.debugLog("Execute container: " + container.getPrefix()); - return container.getExecutor().onTabComplete(sender, commandLabel, passthroughArgs); - } - - return null; - } - @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] cmdArg) { if (QuickShop.instance.getBootError() != null) { @@ -181,4 +137,48 @@ public class CommandManager implements TabCompleter, CommandExecutor { rootContainer.getExecutor().onCommand(sender, commandLabel, passthroughArgs); return true; } + + @Override + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] cmdArg) { + //No args, it shouldn't happend + if (sender instanceof Player) { + if (QuickShop.instance.getConfig().getBoolean("effect.sound.ontabcomplete")) { + Player player = (Player) sender; + ((Player) sender).playSound(player.getLocation(), Sound.BLOCK_DISPENSER_FAIL, 80.0F, 1.0F); + } + } + if (cmdArg.length == 0 || cmdArg.length == 1) { + //No args + return getRootContainer().getExecutor().onTabComplete(sender, commandLabel, cmdArg); + } + //Main args/more args + String[] passthroughArgs; + passthroughArgs = new String[cmdArg.length - 1]; + System.arraycopy(cmdArg, 1, passthroughArgs, 0, passthroughArgs.length); + for (CommandContainer container : cmds) { + Util.debugLog("Checking prefix with container: " + container.getPrefix() + " - " + cmdArg[0]); + if (!container.getPrefix().toLowerCase().startsWith(cmdArg[0])) + continue; + Util.debugLog("Checking permission with container: " + container.getPrefix() + " - " + cmdArg[0]); + List requirePermissions = container.getPermissions(); + if (container.getPermissions() != null) + for (String requirePermission : requirePermissions) { + if (requirePermission != null && !requirePermission.isEmpty() && !sender.hasPermission(requirePermission)) { + Util.debugLog("Sender " + sender + .getName() + " trying tab-complete the command: " + commandLabel + " " + Util + .array2String(cmdArg) + ", but no permission " + requirePermission); + return null; + } + } + Util.debugLog("Execute container: " + container.getPrefix()); + return container.getExecutor().onTabComplete(sender, commandLabel, passthroughArgs); + } + + return null; + } + + private void registerCmd(CommandContainer container) { + if (!cmds.contains(container)) + cmds.add(container); + } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/CommandProcesser.java b/src/main/java/org/maxgamer/quickshop/Command/CommandProcesser.java index 8049a2ad3..9ce8af2ea 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/CommandProcesser.java +++ b/src/main/java/org/maxgamer/quickshop/Command/CommandProcesser.java @@ -6,6 +6,23 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.*; public interface CommandProcesser { + /** + * Accept the onCommand, it will call when have Command Event + * cmdArg not contains CommandContainer's prefix. + * E.g: + * Register the CommandContainer with + * Prefix: unlimited + * Permission: quickshop.unlimited + *

+ * When player type /qs unlimited 123 + * cmdArg's content is 123 + * + * @param sender Sender + * @param cmdArg Args + * @param commandLabel The command prefix /qs is qs + */ + void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg); + /** * Accept the onTabComplete, it will call when have Tab Event * cmdArg not contains CommandContainer's prefix. @@ -23,21 +40,4 @@ public interface CommandProcesser { * @return The result for tab-complete lists */ @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg); - - /** - * Accept the onCommand, it will call when have Command Event - * cmdArg not contains CommandContainer's prefix. - * E.g: - * Register the CommandContainer with - * Prefix: unlimited - * Permission: quickshop.unlimited - *

- * When player type /qs unlimited 123 - * cmdArg's content is 123 - * - * @param sender Sender - * @param cmdArg Args - * @param commandLabel The command prefix /qs is qs - */ - void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg); } diff --git a/src/main/java/org/maxgamer/quickshop/Database/BufferStatement.java b/src/main/java/org/maxgamer/quickshop/Database/BufferStatement.java index 3f3352490..6b62f4d7e 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/BufferStatement.java +++ b/src/main/java/org/maxgamer/quickshop/Database/BufferStatement.java @@ -10,8 +10,8 @@ import org.maxgamer.quickshop.Util.Util; public class BufferStatement { - private Object[] values; private String query; + private Object[] values; /** * Represents a PreparedStatement in a state before preparing it (E.g. No diff --git a/src/main/java/org/maxgamer/quickshop/Database/Database.java b/src/main/java/org/maxgamer/quickshop/Database/Database.java index 24aed4041..743c1846f 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/Database.java +++ b/src/main/java/org/maxgamer/quickshop/Database/Database.java @@ -40,57 +40,6 @@ public class Database { 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; - } - - /** - * 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(@NotNull String query, @NotNull Object... objs) { - Util.debugLog(query); - 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 - * @throws SQLException Throw exception when failed execute somethins on SQL - */ - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - boolean hasTable(@NotNull 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 */ @@ -98,43 +47,6 @@ public class Database { 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(@NotNull String table, @NotNull 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()) { - if (rs.getString(column) != null) - 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; - - private 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 @@ -206,4 +118,92 @@ public class Database { db.getConnection().close(); this.getConnection().close(); } + + /** + * 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(@NotNull String query, @NotNull Object... objs) { + Util.debugLog(query); + BufferStatement bs = new BufferStatement(query, objs); + core.queue(bs); + } + + /** + * 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(@NotNull String table, @NotNull 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()) { + if (rs.getString(column) != null) + return true; + } + } catch (SQLException e) { + return false; + } + return false; // Uh, wtf. + } + + /** + * Returns true if the table exists + * + * @param table The table to check for + * @return True if the table is found + * @throws SQLException Throw exception when failed execute somethins on SQL + */ + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + boolean hasTable(@NotNull 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; + } + + /** + * 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(); + } + + /** + * 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; + } + + /** + * 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; + + private ConnectionException(String msg) { + super(msg); + } + } } \ 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 d9bd3de68..bb4898494 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 { - Connection getConnection(); - - void queue(BufferStatement bs); + void close(); void flush(); - void close(); + void queue(BufferStatement bs); + + Connection getConnection(); } \ 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 a00b8be35..f2ba8df60 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/DatabaseHelper.java +++ b/src/main/java/org/maxgamer/quickshop/Database/DatabaseHelper.java @@ -60,17 +60,29 @@ public class DatabaseHelper { } } - /** - * Creates the database table 'shops'. - * - * @param db The database you want create at. - * @throws SQLException If the connection is invalid. - */ - private void createShopsTable(@NotNull Database db) throws SQLException { - Statement st = db.getConnection().createStatement(); - String createTable = "CREATE TABLE " + QuickShop.instance - .getDbPrefix() + "shops (owner VARCHAR(255) 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); + public void cleanMessage(@NotNull Database db, long weekAgo) { + try { + //QuickShop.instance.getDB().execute("DELETE FROM " + QuickShop.instance + // .getDbPrefix() + "messages WHERE time < ?", weekAgo); + String sqlString = "DELETE FROM " + QuickShop.instance + .getDbPrefix() + "messages WHERE time < ?"; + PreparedStatement ps = db.getConnection().prepareStatement(sqlString); + ps.setLong(1, weekAgo); + plugin.getDatabaseManager().add(ps); + } catch (SQLException sqle) { + sqle.printStackTrace(); + } + } + + public void cleanMessageForPlayer(@NotNull Database db, @NotNull UUID player) { + try { + String sqlString = "DELETE FROM " + QuickShop.instance.getDbPrefix() + "messages WHERE owner = ?"; + PreparedStatement ps = db.getConnection().prepareStatement(sqlString); + ps.setString(1, player.toString()); + plugin.getDatabaseManager().add(ps); + } catch (SQLException sqle) { + sqle.printStackTrace(); + } } /** @@ -87,16 +99,35 @@ public class DatabaseHelper { return st.execute(createTable); } - public ResultSet selectAllShops(Database db) throws SQLException { - Statement st = db.getConnection().createStatement(); - String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "shops"; - return st.executeQuery(selectAllShops); + public void createShop(@NotNull Database db, @NotNull String owner, double price, @NotNull ItemStack item, int unlimited, int shopType, @NotNull String world, int x, int y, int z) + throws SQLException { + String sqlString = "INSERT INTO " + QuickShop.instance + .getDbPrefix() + "shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + //QuickShop.instance.getDB().execute(q, owner, price, Util.serialize(item), x, y, z, world, unlimited, shopType); + PreparedStatement ps = db.getConnection().prepareStatement(sqlString); + ps.setString(1, owner); + ps.setDouble(2, price); + ps.setString(3, Util.serialize(item)); + ps.setInt(4, x); + ps.setInt(5, y); + ps.setInt(6, z); + ps.setString(7, world); + ps.setInt(8, unlimited); + ps.setInt(9, shopType); + plugin.getDatabaseManager().add(ps); } - public ResultSet selectAllMessages(Database db) throws SQLException { + /** + * Creates the database table 'shops'. + * + * @param db The database you want create at. + * @throws SQLException If the connection is invalid. + */ + private void createShopsTable(@NotNull Database db) throws SQLException { Statement st = db.getConnection().createStatement(); - String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "messages"; - return st.executeQuery(selectAllShops); + String createTable = "CREATE TABLE " + QuickShop.instance + .getDbPrefix() + "shops (owner VARCHAR(255) 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); } public boolean removeShop(@NotNull Database db, int x, int y, int z, @NotNull String worldName) throws SQLException { @@ -117,6 +148,33 @@ public class DatabaseHelper { return ps.execute(); } + public ResultSet selectAllMessages(Database db) throws SQLException { + Statement st = db.getConnection().createStatement(); + String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "messages"; + return st.executeQuery(selectAllShops); + } + + public ResultSet selectAllShops(Database db) throws SQLException { + Statement st = db.getConnection().createStatement(); + String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "shops"; + return st.executeQuery(selectAllShops); + } + + public void sendMessage(@NotNull Database db, @NotNull UUID player, @NotNull String message, long time) { + try { + String sqlString = "INSERT INTO " + QuickShop.instance + .getDbPrefix() + "messages (owner, message, time) VALUES (?, ?, ?)"; + //QuickShop.instance.getDB().execute(q, player.toString(), message, System.currentTimeMillis()); + PreparedStatement ps = db.getConnection().prepareStatement(sqlString); + ps.setString(1, player.toString()); + ps.setString(2, message); + ps.setLong(3, time); + plugin.getDatabaseManager().add(ps); + } catch (SQLException sqle) { + sqle.printStackTrace(); + } + } + public void updateOwner2UUID(@NotNull Database db, @NotNull String ownerUUID, int x, int y, int z, @NotNull String worldName) throws SQLException { //QuickShop.instance.getDB().getConnection().createStatement() @@ -157,62 +215,4 @@ public class DatabaseHelper { } } - - public void createShop(@NotNull Database db, @NotNull String owner, double price, @NotNull ItemStack item, int unlimited, int shopType, @NotNull String world, int x, int y, int z) - throws SQLException { - String sqlString = "INSERT INTO " + QuickShop.instance - .getDbPrefix() + "shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; - //QuickShop.instance.getDB().execute(q, owner, price, Util.serialize(item), x, y, z, world, unlimited, shopType); - PreparedStatement ps = db.getConnection().prepareStatement(sqlString); - ps.setString(1, owner); - ps.setDouble(2, price); - ps.setString(3, Util.serialize(item)); - ps.setInt(4, x); - ps.setInt(5, y); - ps.setInt(6, z); - ps.setString(7, world); - ps.setInt(8, unlimited); - ps.setInt(9, shopType); - plugin.getDatabaseManager().add(ps); - } - - public void sendMessage(@NotNull Database db, @NotNull UUID player, @NotNull String message, long time) { - try { - String sqlString = "INSERT INTO " + QuickShop.instance - .getDbPrefix() + "messages (owner, message, time) VALUES (?, ?, ?)"; - //QuickShop.instance.getDB().execute(q, player.toString(), message, System.currentTimeMillis()); - PreparedStatement ps = db.getConnection().prepareStatement(sqlString); - ps.setString(1, player.toString()); - ps.setString(2, message); - ps.setLong(3, time); - plugin.getDatabaseManager().add(ps); - } catch (SQLException sqle) { - sqle.printStackTrace(); - } - } - - public void cleanMessage(@NotNull Database db, long weekAgo) { - try { - //QuickShop.instance.getDB().execute("DELETE FROM " + QuickShop.instance - // .getDbPrefix() + "messages WHERE time < ?", weekAgo); - String sqlString = "DELETE FROM " + QuickShop.instance - .getDbPrefix() + "messages WHERE time < ?"; - PreparedStatement ps = db.getConnection().prepareStatement(sqlString); - ps.setLong(1, weekAgo); - plugin.getDatabaseManager().add(ps); - } catch (SQLException sqle) { - sqle.printStackTrace(); - } - } - - public void cleanMessageForPlayer(@NotNull Database db, @NotNull UUID player) { - try { - String sqlString = "DELETE FROM " + QuickShop.instance.getDbPrefix() + "messages WHERE owner = ?"; - PreparedStatement ps = db.getConnection().prepareStatement(sqlString); - ps.setString(1, player.toString()); - plugin.getDatabaseManager().add(ps); - } catch (SQLException sqle) { - sqle.printStackTrace(); - } - } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java b/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java index fdf94f9b0..194c73b20 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java +++ b/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java @@ -18,11 +18,11 @@ import org.maxgamer.quickshop.Util.WarningSender; * Use queue to solve run SQL make server lagg issue. */ public class DatabaseManager { - private QuickShop plugin; private Database database; - private boolean useQueue; + private QuickShop plugin; private Queue sqlQueue = new LinkedBlockingQueue<>(); private BukkitTask task; + private boolean useQueue; private WarningSender warningSender; /** @@ -48,13 +48,19 @@ public class DatabaseManager { } /** - * Unload the DatabaseManager, run at onDisable() + * Add preparedStatement to queue waiting flush to database, + * @param ps The ps you want add in queue. */ - public void uninit() { - if (task != null && !task.isCancelled()) - task.cancel(); - plugin.getLogger().info("Please wait for the data to flush its data..."); - runTask(); + public void add(@NotNull PreparedStatement ps) { + if (useQueue) { + sqlQueue.offer(ps); + } else { + try { + ps.execute(); + } catch (SQLException sqle) { + sqle.printStackTrace(); + } + } } /** @@ -98,18 +104,12 @@ public class DatabaseManager { } /** - * Add preparedStatement to queue waiting flush to database, - * @param ps The ps you want add in queue. + * Unload the DatabaseManager, run at onDisable() */ - public void add(@NotNull PreparedStatement ps) { - if (useQueue) { - sqlQueue.offer(ps); - } else { - try { - ps.execute(); - } catch (SQLException sqle) { - sqle.printStackTrace(); - } - } + public void uninit() { + if (task != null && !task.isCancelled()) + task.cancel(); + plugin.getLogger().info("Please wait for the data to flush its data..."); + runTask(); } } diff --git a/src/main/java/org/maxgamer/quickshop/Database/MySQLCore.java b/src/main/java/org/maxgamer/quickshop/Database/MySQLCore.java index b3bb089ce..310079522 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/MySQLCore.java +++ b/src/main/java/org/maxgamer/quickshop/Database/MySQLCore.java @@ -10,11 +10,11 @@ import java.util.Properties; import org.jetbrains.annotations.*; 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<>(); + /** The connection properties... user, pass, autoReconnect.. */ + private Properties info; + private String url; public MySQLCore(@NotNull String host, @NotNull String user, @NotNull String pass, @NotNull String database, @NotNull String port, boolean useSSL) { info = new Properties(); @@ -29,6 +29,37 @@ public class MySQLCore implements DatabaseCore { pool.add(null); } + @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 queue(@NotNull BufferStatement bs) { + try { + Connection con = this.getConnection(); + while (con == null) { + try { + Thread.sleep(15); + } catch (InterruptedException e) { + //ignore + } + // Try again + con = this.getConnection(); + } + PreparedStatement ps = bs.prepareStatement(con); + ps.execute(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + /** * Gets the database connection for executing queries on. * @@ -54,35 +85,4 @@ public class MySQLCore implements DatabaseCore { } return null; } - - @Override - public void queue(@NotNull BufferStatement bs) { - try { - Connection con = this.getConnection(); - while (con == null) { - try { - Thread.sleep(15); - } catch (InterruptedException e) { - //ignore - } - // Try again - con = this.getConnection(); - } - PreparedStatement ps = bs.prepareStatement(con); - ps.execute(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void close() { - // 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 814fe2b95..0a3b68376 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/SQLiteCore.java +++ b/src/main/java/org/maxgamer/quickshop/Database/SQLiteCore.java @@ -11,15 +11,50 @@ import java.util.LinkedList; import org.jetbrains.annotations.*; public class SQLiteCore implements DatabaseCore { - private Connection connection; private final File dbFile; - private volatile Thread watcher; private final LinkedList queue = new LinkedList<>(); + private Connection connection; + private volatile Thread watcher; public SQLiteCore(@NotNull File dbFile) { this.dbFile = dbFile; } + @Override + public void close() { + flush(); + } + + @Override + public void flush() { + while (!queue.isEmpty()) { + BufferStatement bs; + synchronized (queue) { + bs = queue.removeFirst(); + } + synchronized (dbFile) { + try { + PreparedStatement ps = bs.prepareStatement(getConnection()); + ps.execute(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + + } + } + } + } + + @Override + public void queue(@NotNull BufferStatement bs) { + synchronized (queue) { + queue.add(bs); + } + if (watcher == null || !watcher.isAlive()) { + startWatcher(); + } + } + /** * Gets the database connection for executing queries on. * @@ -59,41 +94,6 @@ public class SQLiteCore implements DatabaseCore { } } - @Override - public void queue(@NotNull BufferStatement bs) { - synchronized (queue) { - queue.add(bs); - } - if (watcher == null || !watcher.isAlive()) { - startWatcher(); - } - } - - @Override - public void flush() { - while (!queue.isEmpty()) { - BufferStatement bs; - synchronized (queue) { - bs = queue.removeFirst(); - } - synchronized (dbFile) { - try { - PreparedStatement ps = bs.prepareStatement(getConnection()); - ps.execute(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - - } - } - } - } - - @Override - public void close() { - flush(); - } - private void startWatcher() { watcher = new Thread(() -> { try { diff --git a/src/main/java/org/maxgamer/quickshop/Economy/Economy.java b/src/main/java/org/maxgamer/quickshop/Economy/Economy.java index 09e6651a7..508fdae15 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/Economy.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/Economy.java @@ -1,69 +1,69 @@ -package org.maxgamer.quickshop.Economy; - -import java.util.UUID; - -import lombok.*; -import org.jetbrains.annotations.*; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Util.Util; - -public class Economy implements EconomyCore { - @Getter - @Setter - private EconomyCore core; - private QuickShop plugin = QuickShop.instance; - - public Economy(EconomyCore core) { - this.core = core; - } - - /** - * 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() { - return core.isValid(); - } - - /** - * 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) { - return Util.parseColours(core.format(balance)); - //Fix color issue from some stupid economy plugin.... - } - - @Override - public String toString() { - return core.getClass().getName().split("_")[1]; - } - - @Override - public boolean deposit(@NotNull UUID name, double amount) { - return core.deposit(name, amount); - } - - @Override - public boolean withdraw(@NotNull UUID name, double amount) { - return core.withdraw(name, amount); - } - - @Override - public boolean transfer(@NotNull UUID from, UUID to, double amount) { - return core.transfer(from, to, amount); - } - - @Override - public double getBalance(@NotNull UUID name) { - return core.getBalance(name); - } - - public EconomyType getNowUsing() { - return EconomyType.fromID(plugin.getConfig().getInt("economy-type")); - } +package org.maxgamer.quickshop.Economy; + +import java.util.UUID; + +import lombok.*; +import org.jetbrains.annotations.*; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Util.Util; + +public class Economy implements EconomyCore { + @Getter + @Setter + private EconomyCore core; + private QuickShop plugin = QuickShop.instance; + + public Economy(EconomyCore core) { + this.core = core; + } + + @Override + public String toString() { + return core.getClass().getName().split("_")[1]; + } + + public EconomyType getNowUsing() { + return EconomyType.fromID(plugin.getConfig().getInt("economy-type")); + } + + /** + * 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() { + return core.isValid(); + } + + /** + * 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) { + return Util.parseColours(core.format(balance)); + //Fix color issue from some stupid economy plugin.... + } + + @Override + public boolean deposit(@NotNull UUID name, double amount) { + return core.deposit(name, amount); + } + + @Override + public boolean withdraw(@NotNull UUID name, double amount) { + return core.withdraw(name, amount); + } + + @Override + public boolean transfer(@NotNull UUID from, UUID to, double amount) { + return core.transfer(from, to, amount); + } + + @Override + public double getBalance(@NotNull UUID name) { + return core.getBalance(name); + } } \ 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 7a41195a2..ae56d78c0 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/EconomyCore.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/EconomyCore.java @@ -7,11 +7,13 @@ import java.util.UUID; */ public interface EconomyCore { /** - * Checks that this economy is valid. Returns false if it is not valid. + * Deposits a given amount of money from thin air to the given username. * - * @return True if this economy will work, false if it will not. + * @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) */ - boolean isValid(); + boolean deposit(UUID name, double amount); /** * Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50 @@ -23,23 +25,12 @@ public interface EconomyCore { String format(double balance); /** - * Deposits a given amount of money from thin air to the given username. + * Fetches the balance of the given account name * - * @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) + * @param name The name of the account + * @return Their current balance. */ - boolean deposit(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 - */ - boolean withdraw(UUID name, double amount); + double getBalance(UUID name); /** * Transfers the given amount of money from Player1 to Player2 @@ -53,11 +44,20 @@ public interface EconomyCore { boolean transfer(UUID from, UUID to, double amount); /** - * Fetches the balance of the given account name + * Withdraws a given amount of money from the given username and turns it to + * thin air. * - * @param name The name of the account - * @return Their current balance. + * @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 */ - double getBalance(UUID name); + boolean withdraw(UUID name, double 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. + */ + boolean isValid(); } diff --git a/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java b/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java index 433d766e3..dadbc85ff 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java @@ -4,12 +4,6 @@ import org.jetbrains.annotations.*; public enum EconomyType { UNKNOWN(-1), VAULT(0), RESERVE(1); - private int id; - - EconomyType(int id) { - this.id = id; - } - public static EconomyType fromID(int id) { for (EconomyType type : EconomyType.values()) { if (type.id == id) { @@ -23,6 +17,12 @@ public enum EconomyType { return economyType.id; } + private int id; + + EconomyType(int id) { + this.id = id; + } + public int toID() { return id; } diff --git a/src/main/java/org/maxgamer/quickshop/Economy/Economy_Reserve.java b/src/main/java/org/maxgamer/quickshop/Economy/Economy_Reserve.java index a908c6cc5..6dfb6ff46 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/Economy_Reserve.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/Economy_Reserve.java @@ -13,16 +13,24 @@ import org.maxgamer.quickshop.QuickShop; * @author creatorfromhell */ public class Economy_Reserve implements EconomyCore { + final private String errorMsg = "QuickShop got an error when calling your Economy system, this is NOT a QuickShop error, please do not report this issue to the QuickShop's Issue tracker, ask your Economy plugin's author."; + private QuickShop plugin = QuickShop.instance; @Getter @Setter private EconomyAPI reserve = null; - private QuickShop plugin = QuickShop.instance; - final private String errorMsg = "QuickShop got an error when calling your Economy system, this is NOT a QuickShop error, please do not report this issue to the QuickShop's Issue tracker, ask your Economy plugin's author."; public Economy_Reserve() { setup(); } + private String formatInternal(double balance) { + try { + return String.valueOf(QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance); + } catch (Exception e) { + return String.valueOf('$' + balance); + } + } + @SuppressWarnings("ConstantConditions") private void setup() { try { @@ -62,14 +70,6 @@ public class Economy_Reserve implements EconomyCore { } } - private String formatInternal(double balance) { - try { - return String.valueOf(QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance); - } catch (Exception e) { - return String.valueOf('$' + balance); - } - } - /** * Deposits a given amount of money from thin air to the given username. * 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 af6b3175d..de77c94fe 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/Economy_Vault.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/Economy_Vault.java @@ -16,15 +16,49 @@ import org.maxgamer.quickshop.QuickShop; import org.maxgamer.quickshop.Util.Util; public class Economy_Vault implements EconomyCore, Listener { + private QuickShop plugin = QuickShop.instance; @Getter @Setter private Economy vault; - private QuickShop plugin = QuickShop.instance; public Economy_Vault() { setupEconomy(); } + public boolean checkValid() { + if (this.vault == null) { + Bukkit.getPluginManager().disablePlugin(plugin); + plugin.getLogger().severe("FATAL: Economy system not ready."); + return false; + } else { + return true; + } + } + + private String formatInternal(double balance) { + if (!checkValid()) + return "Error"; + try { + return QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance; + } catch (Exception e) { + return String.valueOf('$' + balance); + } + } + + @EventHandler + public void onServiceRegister(ServiceRegisterEvent event) { + if (!(event.getProvider() instanceof Economy)) + return; + setupEconomy(); + } + + @EventHandler + public void onServiceRegister(ServiceUnregisterEvent event) { + if (!(event.getProvider() instanceof Economy)) + return; + setupEconomy(); + } + private boolean setupEconomy() { RegisteredServiceProvider economyProvider; try { @@ -58,35 +92,11 @@ public class Economy_Vault implements EconomyCore, Listener { return String.valueOf(this.vault.getName()); } - @EventHandler - public void onServiceRegister(ServiceRegisterEvent event) { - if (!(event.getProvider() instanceof Economy)) - return; - setupEconomy(); - } - - @EventHandler - public void onServiceRegister(ServiceUnregisterEvent event) { - if (!(event.getProvider() instanceof Economy)) - return; - setupEconomy(); - } - @Override public boolean isValid() { return this.vault != null; } - public boolean checkValid() { - if (this.vault == null) { - Bukkit.getPluginManager().disablePlugin(plugin); - plugin.getLogger().severe("FATAL: Economy system not ready."); - return false; - } else { - return true; - } - } - @Override public String format(double balance) { if (!checkValid()) @@ -102,16 +112,6 @@ public class Economy_Vault implements EconomyCore, Listener { } - private String formatInternal(double balance) { - if (!checkValid()) - return "Error"; - try { - return QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance; - } catch (Exception e) { - return String.valueOf('$' + balance); - } - } - @Override public boolean deposit(@NotNull UUID name, double amount) { if (!checkValid()) diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopCreateEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopCreateEvent.java index aadf4a8d0..b867dc190 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopCreateEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopCreateEvent.java @@ -10,13 +10,13 @@ import org.maxgamer.quickshop.Shop.Shop; public class ShopCreateEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); - @Getter - @NotNull - private Shop shop; private boolean cancelled; @Getter @NotNull private Player player; + @Getter + @NotNull + private Shop shop; /** * Call when have a new shop was createing. diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopDeleteEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopDeleteEvent.java index f6b6f54fe..092e85b0b 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopDeleteEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopDeleteEvent.java @@ -9,11 +9,11 @@ import org.maxgamer.quickshop.Shop.Shop; public class ShopDeleteEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + @Getter private boolean fromMemory; @Getter @NotNull private Shop shop; - private boolean cancelled; - @Getter private boolean fromMemory; /** * Call the event when shop is deleteing. diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemSpawnEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemSpawnEvent.java index 877cf5819..037f4544c 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemSpawnEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemSpawnEvent.java @@ -19,13 +19,13 @@ public class ShopDisplayItemSpawnEvent extends Event implements Cancellable { private boolean cancelled; @Getter @NotNull - private Shop shop; + private DisplayType displayType; @Getter @NotNull private ItemStack itemStack; @Getter @NotNull - private DisplayType displayType; + private Shop shop; /** * This event is called before the shop display item created diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopInventoryPreviewEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopInventoryPreviewEvent.java index cc26391ec..960c4a693 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopInventoryPreviewEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopInventoryPreviewEvent.java @@ -14,10 +14,10 @@ public class ShopInventoryPreviewEvent extends Event implements Cancellable { private boolean cancelled; @Getter @NotNull - private Player player; + private ItemStack itemStack; @Getter @NotNull - private ItemStack itemStack; + private Player player; /** * Build a event when player using GUI preview diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopLoadEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopLoadEvent.java index 706423e00..a520c693f 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopLoadEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopLoadEvent.java @@ -26,6 +26,9 @@ public class ShopLoadEvent extends Event implements Cancellable { this.shop = shop; } + public static HandlerList getHandlerList() { + return handlers; + } @NotNull @Override @@ -33,10 +36,6 @@ public class ShopLoadEvent extends Event implements Cancellable { return handlers; } - public static HandlerList getHandlerList() { - return handlers; - } - @Override public boolean isCancelled() { return this.cancelled; diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopModeratorChangedEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopModeratorChangedEvent.java index 4030e92c1..0957c63a0 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopModeratorChangedEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopModeratorChangedEvent.java @@ -13,10 +13,10 @@ public class ShopModeratorChangedEvent extends Event { private static final HandlerList handlers = new HandlerList(); @Getter @NotNull - private Shop shop; + private ShopModerator moderator; @Getter @NotNull - private ShopModerator moderator; + private Shop shop; /** * Will call when shop price was changed. diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopPreCreateEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopPreCreateEvent.java index 95a065dcc..f7e5d64e4 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopPreCreateEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopPreCreateEvent.java @@ -19,10 +19,10 @@ public class ShopPreCreateEvent extends Event implements Cancellable { private boolean cancelled; @Getter @NotNull - private Player player; + private Location location; @Getter @NotNull - private Location location; + private Player player; /** * Calling when shop pre-creating. diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopPriceChangedEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopPriceChangedEvent.java index 0fe15f1f5..90b98d5dc 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopPriceChangedEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopPriceChangedEvent.java @@ -10,11 +10,11 @@ import org.maxgamer.quickshop.Shop.Shop; public class ShopPriceChangedEvent extends Event { private static final HandlerList handlers = new HandlerList(); + @Getter private double newPrice; + @Getter private double oldPrice; @Getter @NotNull private Shop shop; - @Getter private double oldPrice; - @Getter private double newPrice; /** * Will call when shop price was changed. diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java index 001c283df..e571591a6 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java @@ -10,16 +10,16 @@ import org.maxgamer.quickshop.Shop.Shop; public class ShopSuccessPurchaseEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); - @Getter - @NotNull - private Shop shop; + @Getter private int amount; + private boolean cancelled; @Getter @NotNull private Player player; - @Getter private int amount; - private double total; + @Getter + @NotNull + private Shop shop; @Getter private double tax; - private boolean cancelled; + private double total; /** * Builds a new shop purchase event @@ -56,13 +56,13 @@ public class ShopSuccessPurchaseEvent extends Event implements Cancellable { */ public double getBalanceWithoutTax() {return this.total;} - @NotNull - @Override - public HandlerList getHandlers() { + public static HandlerList getHandlerList() { return handlers; } - public static HandlerList getHandlerList() { + @NotNull + @Override + public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopUpdateEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopUpdateEvent.java index 1f9ec3f97..dd3bf97c9 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopUpdateEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopUpdateEvent.java @@ -9,9 +9,9 @@ import org.maxgamer.quickshop.Shop.Shop; public class ShopUpdateEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; @Getter private @NotNull Shop shop; - private boolean cancelled; /** * Call when shop is trying updated to database @@ -21,13 +21,14 @@ public class ShopUpdateEvent extends Event implements Cancellable { public ShopUpdateEvent(@NotNull Shop shop) { this.shop = shop; } - @NotNull - @Override - public HandlerList getHandlers() { + + public static HandlerList getHandlerList() { return handlers; } - public static HandlerList getHandlerList() { + @NotNull + @Override + public HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java b/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java index 221505d0f..ce29dc358 100644 --- a/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java +++ b/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java @@ -20,10 +20,9 @@ public class InternalListener implements Listener { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void shopPurchase(ShopSuccessPurchaseEvent event) { - plugin.log("Player " + event.getPlayer().getName() + " purchased " + event.getShop().ownerName() + " shop item x" + event - .getAmount() + " for " + plugin.getEconomy().format(event.getBalance()) + " (" + plugin.getEconomy() - .format(event.getTax()) + " tax)."); + public void shopModeratorChanges(ShopModeratorChangedEvent event) { + plugin.log("Shop at location " + event.getShop().getLocation() + " moderator was changed to " + event.getModerator() + .toString()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -33,9 +32,10 @@ public class InternalListener implements Listener { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void shopModeratorChanges(ShopModeratorChangedEvent event) { - plugin.log("Shop at location " + event.getShop().getLocation() + " moderator was changed to " + event.getModerator() - .toString()); + public void shopPurchase(ShopSuccessPurchaseEvent event) { + plugin.log("Player " + event.getPlayer().getName() + " purchased " + event.getShop().ownerName() + " shop item x" + event + .getAmount() + " for " + plugin.getEconomy().format(event.getBalance()) + " (" + plugin.getEconomy() + .format(event.getTax()) + " tax)."); } } diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java index 995527f07..da5b6cba6 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java @@ -26,24 +26,18 @@ import org.maxgamer.quickshop.Util.Util; public class BlockListener implements Listener { private QuickShop plugin; - /* - * Listens for chest placement, so a doublechest shop can't be created. + /** + * Gets the shop a sign is attached to + * + * @param loc The location of the sign + * @return The shop */ - @EventHandler(ignoreCancelled = true) - public void onPlace(BlockPlaceEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - BlockState bs = e.getBlock().getState(); - if (!(bs instanceof DoubleChest)) - return; - Block b = e.getBlock(); - Player p = e.getPlayer(); - 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.getMessage("no-double-chests")); - } + private Shop getShopNextTo(Location loc) { + Block b = Util.getAttached(loc.getBlock()); + // Util.getAttached(b) + if (b == null) + return null; + return plugin.getShopManager().getShop(b.getLocation()); } /* @@ -130,21 +124,6 @@ public class BlockListener implements Listener { } } - - /** - * Gets the shop a sign is attached to - * - * @param loc The location of the sign - * @return The shop - */ - private Shop getShopNextTo(Location loc) { - Block b = Util.getAttached(loc.getBlock()); - // Util.getAttached(b) - if (b == null) - return null; - return plugin.getShopManager().getShop(b.getLocation()); - } - @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onInventoryMove(InventoryMoveItemEvent event) { if (ListenerHelper.isDisabled(event.getClass())) @@ -157,4 +136,24 @@ public class BlockListener implements Listener { return; shop.setSignText(); } + + /* + * Listens for chest placement, so a doublechest shop can't be created. + */ + @EventHandler(ignoreCancelled = true) + public void onPlace(BlockPlaceEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + BlockState bs = e.getBlock().getState(); + if (!(bs instanceof DoubleChest)) + return; + Block b = e.getBlock(); + Player p = e.getPlayer(); + 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.getMessage("no-double-chests")); + } + } } \ 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 94f8eb522..7362ed6d0 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/LockListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/LockListener.java @@ -31,57 +31,48 @@ public class LockListener implements Listener { private QuickShop plugin; @EventHandler(ignoreCancelled = true) - public void onClick(PlayerInteractEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) + public void invEvent(InventoryMoveItemEvent e) { + if (!InventoryPreview.isPreviewItem(e.getItem())) return; - Block b = e.getClickedBlock(); - if (b == null) - return; - if (!Util.canBeShop(b)) - return; - Player p = e.getPlayer(); - if (e.getAction() != Action.RIGHT_CLICK_BLOCK) - return; // Didn't right click it, we dont care. - 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.getModerator().isModerator(p.getUniqueId())) { - if (p.hasPermission("quickshop.other.open")) { - p.sendMessage(MsgUtil.getMessage("bypassing-lock")); - return; - } - p.sendMessage(MsgUtil.getMessage("that-is-locked")); + e.setCancelled(true); + } + + @EventHandler + public void invEvent(InventoryClickEvent e) { + if (InventoryPreview.isPreviewItem(e.getCursor())) { e.setCancelled(true); + e.setResult(Event.Result.DENY); + } + if (InventoryPreview.isPreviewItem(e.getCurrentItem())) { + e.setCancelled(true); + e.setResult(Event.Result.DENY); } } - /* - * Handles hopper placement - */ - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - Block b = e.getBlock(); - if (b.getType() != Material.HOPPER) - return; - Player p = e.getPlayer(); - if (!Util.isOtherShopWithinHopperReach(b, p)) - return; - - if (p.hasPermission("quickshop.other.open")) { - p.sendMessage(MsgUtil.getMessage("bypassing-lock")); - return; + @EventHandler + public void invEvent(InventoryDragEvent e) { + if (InventoryPreview.isPreviewItem(e.getCursor())) { + e.setCancelled(true); + e.setResult(Event.Result.DENY); + } + if (InventoryPreview.isPreviewItem(e.getOldCursor())) { + e.setCancelled(true); + e.setResult(Event.Result.DENY); + } + + } + + @EventHandler + public void invEvent(InventoryPickupItemEvent e) { + Inventory inventory = e.getInventory(); + ItemStack[] stacks = inventory.getContents(); + for (ItemStack itemStack : stacks) { + if (itemStack == null) + continue; + if (InventoryPreview.isPreviewItem(itemStack)) { + e.setCancelled(true); + } } - p.sendMessage(MsgUtil.getMessage("that-is-locked")); - e.setCancelled(true); } /* @@ -135,6 +126,38 @@ public class LockListener implements Listener { } } + @EventHandler(ignoreCancelled = true) + public void onClick(PlayerInteractEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + Block b = e.getClickedBlock(); + if (b == null) + return; + if (!Util.canBeShop(b)) + return; + Player p = e.getPlayer(); + if (e.getAction() != Action.RIGHT_CLICK_BLOCK) + return; // Didn't right click it, we dont care. + 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.getModerator().isModerator(p.getUniqueId())) { + if (p.hasPermission("quickshop.other.open")) { + p.sendMessage(MsgUtil.getMessage("bypassing-lock")); + return; + } + p.sendMessage(MsgUtil.getMessage("that-is-locked")); + e.setCancelled(true); + } + } + /* * Handles shops breaking through explosions */ @@ -156,48 +179,25 @@ public class LockListener implements Listener { } } - @EventHandler(ignoreCancelled = true) - public void invEvent(InventoryMoveItemEvent e) { - if (!InventoryPreview.isPreviewItem(e.getItem())) + /* + * Handles hopper placement + */ + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) return; + Block b = e.getBlock(); + if (b.getType() != Material.HOPPER) + return; + Player p = e.getPlayer(); + if (!Util.isOtherShopWithinHopperReach(b, p)) + return; + + if (p.hasPermission("quickshop.other.open")) { + p.sendMessage(MsgUtil.getMessage("bypassing-lock")); + return; + } + p.sendMessage(MsgUtil.getMessage("that-is-locked")); e.setCancelled(true); } - - @EventHandler - public void invEvent(InventoryClickEvent e) { - if (InventoryPreview.isPreviewItem(e.getCursor())) { - e.setCancelled(true); - e.setResult(Event.Result.DENY); - } - if (InventoryPreview.isPreviewItem(e.getCurrentItem())) { - e.setCancelled(true); - e.setResult(Event.Result.DENY); - } - } - - @EventHandler - public void invEvent(InventoryDragEvent e) { - if (InventoryPreview.isPreviewItem(e.getCursor())) { - e.setCancelled(true); - e.setResult(Event.Result.DENY); - } - if (InventoryPreview.isPreviewItem(e.getOldCursor())) { - e.setCancelled(true); - e.setResult(Event.Result.DENY); - } - - } - - @EventHandler - public void invEvent(InventoryPickupItemEvent e) { - Inventory inventory = e.getInventory(); - ItemStack[] stacks = inventory.getContents(); - for (ItemStack itemStack : stacks) { - if (itemStack == null) - continue; - if (InventoryPreview.isPreviewItem(itemStack)) { - e.setCancelled(true); - } - } - } } \ 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 bd047fee0..68af0f563 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java @@ -169,6 +169,42 @@ public class PlayerListener implements Listener { } } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInventoryClose(InventoryCloseEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + try { + Inventory inventory = e.getInventory(); + if (inventory == null) + return; + Location location = inventory.getLocation(); + if (location == null) + return; + Shop shop = plugin.getShopManager().getShop(location); + if (shop == null) + return; + shop.setSignText(); + } catch (Throwable t) { + //Ignore + } + } + + @EventHandler(ignoreCancelled = true) + public void onJoin(PlayerJoinEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + // Notify the player any messages they were sent + if (plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) { + new BukkitRunnable() { + @Override + public void run() { + MsgUtil.flush(e.getPlayer()); + } + }.runTaskAsynchronously(plugin); + } + + } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) /* * Waits for a player to move too far from a shop, then cancels the menu. @@ -199,30 +235,6 @@ public class PlayerListener implements Listener { } - @EventHandler(ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); - onMove(me); - } - - @EventHandler(ignoreCancelled = true) - public void onJoin(PlayerJoinEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - // Notify the player any messages they were sent - if (plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) { - new BukkitRunnable() { - @Override - public void run() { - MsgUtil.flush(e.getPlayer()); - } - }.runTaskAsynchronously(plugin); - } - - } - @EventHandler(ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent e) { if (ListenerHelper.isDisabled(e.getClass())) @@ -231,24 +243,12 @@ public class PlayerListener implements Listener { plugin.getShopManager().getActions().remove(e.getPlayer().getUniqueId()); } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClose(InventoryCloseEvent e) { + @EventHandler(ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent e) { if (ListenerHelper.isDisabled(e.getClass())) return; - try { - Inventory inventory = e.getInventory(); - if (inventory == null) - return; - Location location = inventory.getLocation(); - if (location == null) - return; - Shop shop = plugin.getShopManager().getShop(location); - if (shop == null) - return; - shop.setSignText(); - } catch (Throwable t) { - //Ignore - } + 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/ShopProtectionListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/ShopProtectionListener.java index 09c7e0b56..2ccdd4822 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/ShopProtectionListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/ShopProtectionListener.java @@ -25,6 +25,81 @@ public class ShopProtectionListener implements Listener { this.plugin = plugin; } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockExplode(BlockExplodeEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + for (int i = 0; i < e.blockList().size(); i++) { + Block b = e.blockList().get(i); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if (plugin.getConfig().getBoolean("protect.explode")) + e.setCancelled(true); + else + shop.delete(); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + if (!plugin.getConfig().getBoolean("protect.fromto")) + return; + Shop shop = plugin.getShopManager().getShop(e.getToBlock().getLocation()); + if (shop == null) + return; + e.setCancelled(true); + } + + //Protect Redstone active shop + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockRedstoneChange(BlockRedstoneEvent event) { + if (ListenerHelper.isDisabled(event.getClass())) + return; + if (!plugin.getConfig().getBoolean("protect.redstone")) + return; + Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation()); + if (shop == null) + return; + event.setNewCurrent(event.getOldCurrent()); + //plugin.getLogger().warning("[Exploit Alert] a Redstone tried to active of " + shop); + //Util.debugLog(ChatColor.RED + "[QuickShop][Exploit alert] Redstone was activated on the following shop " + shop); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockSpread(BlockSpreadEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + Block newBlock = e.getNewState().getBlock(); + Shop thisBlockShop = plugin.getShopManager().getShop(newBlock.getLocation()); + Shop underBlockShop = plugin.getShopManager().getShop(newBlock.getRelative(BlockFace.DOWN).getLocation()); + if (thisBlockShop == null && underBlockShop == null) + return; + if (plugin.getConfig().getBoolean("protect.spread")) + e.setCancelled(true); + } + + /* + * Handles shops breaking through explosions + */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onExplode(EntityExplodeEvent e) { + if (ListenerHelper.isDisabled(e.getClass())) + return; + for (int i = 0; i < e.blockList().size(); i++) { + Block b = e.blockList().get(i); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if (plugin.getConfig().getBoolean("protect.explode")) + e.setCancelled(true); + else + shop.delete(); + } + } + } + //Protect Minecart steal shop @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onInventoryMove(InventoryMoveItemEvent event) { @@ -55,21 +130,6 @@ public class ShopProtectionListener implements Listener { shop.delete(); } - //Protect Redstone active shop - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockRedstoneChange(BlockRedstoneEvent event) { - if (ListenerHelper.isDisabled(event.getClass())) - return; - if (!plugin.getConfig().getBoolean("protect.redstone")) - return; - Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation()); - if (shop == null) - return; - event.setNewCurrent(event.getOldCurrent()); - //plugin.getLogger().warning("[Exploit Alert] a Redstone tried to active of " + shop); - //Util.debugLog(ChatColor.RED + "[QuickShop][Exploit alert] Redstone was activated on the following shop " + shop); - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onStructureGrow(StructureGrowEvent event) { if (ListenerHelper.isDisabled(event.getClass())) @@ -86,64 +146,4 @@ public class ShopProtectionListener implements Listener { //Util.sendMessageToOps(ChatColor.RED + "[QuickShop][Exploit alert] A StructureGrowing tried to break the shop of " + shop); } } - - /* - * Handles shops breaking through explosions - */ - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onExplode(EntityExplodeEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - for (int i = 0; i < e.blockList().size(); i++) { - Block b = e.blockList().get(i); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if (plugin.getConfig().getBoolean("protect.explode")) - e.setCancelled(true); - else - shop.delete(); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockExplode(BlockExplodeEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - for (int i = 0; i < e.blockList().size(); i++) { - Block b = e.blockList().get(i); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if (plugin.getConfig().getBoolean("protect.explode")) - e.setCancelled(true); - else - shop.delete(); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockSpread(BlockSpreadEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - Block newBlock = e.getNewState().getBlock(); - Shop thisBlockShop = plugin.getShopManager().getShop(newBlock.getLocation()); - Shop underBlockShop = plugin.getShopManager().getShop(newBlock.getRelative(BlockFace.DOWN).getLocation()); - if (thisBlockShop == null && underBlockShop == null) - return; - if (plugin.getConfig().getBoolean("protect.spread")) - e.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockFromTo(BlockFromToEvent e) { - if (ListenerHelper.isDisabled(e.getClass())) - return; - if (!plugin.getConfig().getBoolean("protect.fromto")) - return; - Shop shop = plugin.getShopManager().getShop(e.getToBlock().getLocation()); - if (shop == null) - return; - e.setCancelled(true); - } } diff --git a/src/main/java/org/maxgamer/quickshop/Metrics.java b/src/main/java/org/maxgamer/quickshop/Metrics.java index ec7b53067..440848a0b 100644 --- a/src/main/java/org/maxgamer/quickshop/Metrics.java +++ b/src/main/java/org/maxgamer/quickshop/Metrics.java @@ -1,640 +1,638 @@ -package org.maxgamer.quickshop; - -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; -import javax.net.ssl.HttpsURLConnection; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - *

- * Edit by QSRR, Don't removed, we customed somethings! - */ -@SuppressWarnings("unchecked") -public class Metrics { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final JavaPlugin plugin; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public Metrics(JavaPlugin plugin) { - if (plugin == null) { - - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - plugin.getLogger().info("bStats module loaded."); - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - if (config.getBoolean("enabled", true)) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JSONObject getPluginData() { - JSONObject data = new JSONObject(); - - String pluginName = "QuickShop-Reremake"; - String pluginVersion = plugin.getDescription().getVersion(); - - data.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin - JSONArray customCharts = new JSONArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - public JSONObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = org.bukkit.Bukkit.getVersion(); - bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("playerAmount", playerAmount); - data.put("onlineMode", onlineMode); - data.put("bukkitVersion", bukkitVersion); - - data.put("javaVersion", javaVersion); - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - - public void submitData() { - - final JSONObject data = getServerData(); - plugin.getLogger().info("Posting stats data..."); - JSONArray pluginData = new JSONArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - } catch (NoSuchFieldException ignored) { } - } - - data.put("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(() -> { - try { - // Send the data - plugin.getLogger().info("Sending stats data..."); - sendData(data); - } catch (Throwable e) { /*Ignore*/ } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - @SuppressWarnings("unused") - private void sendData(JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - connection.setConnectTimeout(300000); - connection.setReadTimeout(300000); - connection.setDoOutput(true); - // Send data - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - String result = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine(); - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JSONObject getRequestJsonObject() { - JSONObject chart = new JSONObject(); - chart.put("chartId", chartId); - try { - JSONObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.put("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JSONObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JSONObject value = new JSONObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.put(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.put(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JSONArray categoryValues = new JSONArray(); - categoryValues.add(entry.getValue()); - values.put(entry.getKey(), categoryValues); - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JSONArray categoryValues = new JSONArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.put(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } +package org.maxgamer.quickshop; + +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.bukkit.plugin.java.JavaPlugin; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + *

+ * Edit by QSRR, Don't removed, we customed somethings! + */ +@SuppressWarnings("unchecked") +public class Metrics { + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // The uuid of the server + private static String serverUUID; + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + // A list with all custom charts + private final List charts = new ArrayList<>(); + // The plugin + private final JavaPlugin plugin; + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(JavaPlugin plugin) { + if (plugin == null) { + + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + plugin.getLogger().info("bStats module loaded."); + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + if (config.getBoolean("enabled", true)) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Sends the data to the bStats server. + * + * @param data The data to send. + * @throws Exception If the request failed. + */ + @SuppressWarnings("unused") + private void sendData(JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + connection.setConnectTimeout(300000); + connection.setReadTimeout(300000); + connection.setDoOutput(true); + // Send data + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + String result = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine(); + connection.getInputStream().close(); // We don't care about the response - Just send our data :) + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Collects the data and sends it afterwards. + */ + + public void submitData() { + + final JSONObject data = getServerData(); + plugin.getLogger().info("Posting stats data..."); + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + plugin.getLogger().info("Sending stats data..."); + sendData(data); + } catch (Throwable e) { /*Ignore*/ } + }).start(); + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = "QuickShop-Reremake"; + String pluginVersion = plugin.getDescription().getVersion(); + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + public JSONObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = org.bukkit.Bukkit.getVersion(); + bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + protected abstract JSONObject getChartData() throws Exception; + + private JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JSONObject value = new JSONObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.put(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.put(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } } \ 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 c40e75918..1a25c5218 100644 --- a/src/main/java/org/maxgamer/quickshop/QuickShop.java +++ b/src/main/java/org/maxgamer/quickshop/QuickShop.java @@ -34,84 +34,83 @@ import org.maxgamer.quickshop.Watcher.UpdateWatcher; public class QuickShop extends JavaPlugin { /** The active instance of QuickShop */ public static QuickShop instance; - /** The economy we hook into for transactions */ - private Economy economy; - /** The Shop Manager used to store shops */ - private ShopManager shopManager; - /** - * A set of players who have been warned ("Your shop isn't automatically - * locked") - */ - private HashSet warnings = new HashSet<>(); - /** The database for storing all our data for persistence */ - private Database database; - // Listeners - We decide which one to use at runtime - private ChatListener chatListener; // Listeners (These don't) private BlockListener blockListener; - private PlayerListener playerListener; - private DisplayProtectionListener inventoryListener; + /** The BootError, if it not NULL, plugin will stop loading and show setted errors when use /qs **/ + private BootError bootError; + // Listeners - We decide which one to use at runtime + private ChatListener chatListener; private ChunkListener chunkListener; - private WorldListener worldListener; - //private BukkitTask itemWatcherTask; - private LogWatcher logWatcher; - private ItemMatcher itemMatcher; + private CommandManager commandManager; + private Tab commandTabCompleter; + /** WIP **/ + private Compatibility compatibilityTool = new Compatibility(this); + private CustomInventoryListener customInventoryListener; + /** The database for storing all our data for persistence */ + private Database database; + /** Contains all SQL tasks **/ + private DatabaseHelper databaseHelper; + /** Queued database manager **/ + private DatabaseManager databaseManager; + /** Default database prefix, can overwrite by config **/ + private String dbPrefix = ""; + /** Whether we should use display items or not */ + private boolean display = true; private DisplayBugFixListener displayBugFixListener; - private LockListener lockListener; // /** Whether players are required to sneak to create/buy from a shop */ // public boolean sneak; // /** Whether players are required to sneak to create a shop */ // public boolean sneakCreate; // /** Whether players are required to sneak to trade with a shop */ // public boolean sneakTrade; - /** Whether we should use display items or not */ - private boolean display = true; +// private Metrics metrics; +private int displayItemCheckTicks; + private DisplayWatcher displayWatcher; + /** The economy we hook into for transactions */ + private Economy economy; + private DisplayProtectionListener inventoryListener; + private ItemMatcher itemMatcher; + /** Language manager, to select which language will loaded. **/ + private Language language; + /** Whether or not to limit players shop amounts */ + private boolean limit = false; + /** The shop limites. **/ + private HashMap limits = new HashMap<>(); + private LockListener lockListener; + //private BukkitTask itemWatcherTask; + private LogWatcher logWatcher; + /** bStats, good helper for metrics. **/ + private Metrics metrics; + private boolean noopDisable; + /** The plugin OpenInv (null if not present) */ + private Plugin openInvPlugin; + /** A util to call to check some actions permission **/ + private PermissionChecker permissionChecker; + private PlayerListener playerListener; /** * Whether we players are charged a fee to change the price on their shop (To * help deter endless undercutting */ private boolean priceChangeRequiresFee = false; - /** Whether or not to limit players shop amounts */ - private boolean limit = false; - - /** The plugin OpenInv (null if not present) */ - private Plugin openInvPlugin; - /** The shop limites. **/ - private HashMap limits = new HashMap<>(); - /** Use SpoutPlugin to get item / block names */ - private boolean useSpout = false; - // private Metrics metrics; - private int displayItemCheckTicks; - private boolean noopDisable; - private boolean setupDBonEnableding = false; - /** Default database prefix, can overwrite by config **/ - private String dbPrefix = ""; - private Tab commandTabCompleter; - /** bStats, good helper for metrics. **/ - private Metrics metrics; - /** Language manager, to select which language will loaded. **/ - private Language language; - /** The BootError, if it not NULL, plugin will stop loading and show setted errors when use /qs **/ - private BootError bootError; - private CustomInventoryListener customInventoryListener; - /** WIP **/ - private Compatibility compatibilityTool = new Compatibility(this); - /** Rewrited shoploader, more faster. **/ - private ShopLoader shopLoader; - /** Contains all SQL tasks **/ - private DatabaseHelper databaseHelper; - /** Queued database manager **/ - private DatabaseManager databaseManager; - /** A util to call to check some actions permission **/ - private PermissionChecker permissionChecker; - /** The server UniqueID, use to the ErrorReporter **/ - private UUID serverUniqueID; /** The error reporter to help devs report errors to Sentry.io **/ private SentryErrorReporter sentryErrorReporter; - private CommandManager commandManager; + /** The server UniqueID, use to the ErrorReporter **/ + private UUID serverUniqueID; + private boolean setupDBonEnableding = false; + /** Rewrited shoploader, more faster. **/ + private ShopLoader shopLoader; + /** The Shop Manager used to store shops */ + private ShopManager shopManager; private ShopProtectionListener shopProtectListener; - private DisplayWatcher displayWatcher; private SyncTaskWatcher syncTaskWatcher; + /** Use SpoutPlugin to get item / block names */ + private boolean useSpout = false; + /** + * A set of players who have been warned ("Your shop isn't automatically + * locked") + */ + private HashSet warnings = new HashSet<>(); + private WorldListener worldListener; /** * Get the Player's Shop limit. @@ -128,45 +127,6 @@ public class QuickShop extends JavaPlugin { return max; } - /** - * Check the env plugin running. - * - * @throws RuntimeException The error message, use this to create a BootError. - */ - private void runtimeCheck() throws RuntimeException { - try { - getServer().spigot(); - } catch (Throwable e) { - getLogger().severe("FATAL: QSRR can only be run on Spigot servers and forks of Spigot!"); - throw new RuntimeException("Server must be Spigot based, Don't use CraftBukkit!"); - } - - if (getServer().getName().toLowerCase().contains("catserver")) { - // Send FATAL ERROR TO CatServer's users. - getLogger().severe("FATAL: QSRR can't run on CatServer Community/Personal/Pro"); - throw new RuntimeException("QuickShop doen't support CatServer"); - } - - if (Util.isDevEdition()) { - getLogger().severe("WARNING: You are running QSRR in dev-mode"); - getLogger().severe("WARNING: Keep backup and DO NOT run this in a production environment!"); - getLogger().severe("WARNING: Test version may destroy everything!"); - getLogger().severe( - "WARNING: QSRR won't start without your confirmation, nothing will change before you turn on dev allowed."); - if (!getConfig().getBoolean("dev-mode")) { - getLogger().severe( - "WARNING: Set dev-mode: true in config.yml to allow qs load in dev mode(You may need add this line to the config yourself)."); - noopDisable = true; - throw new RuntimeException("Snapshot cannot run when dev-mode is false in the config"); - } - } - String nmsVersion = Util.getNMSVersion(); - IncompatibleChecker incompatibleChecker = new IncompatibleChecker(); - getLogger().info("Running QuickShop-Reremake on Minecraft version " + nmsVersion); - if (incompatibleChecker.isIncompatible(nmsVersion)) - throw new RuntimeException("Your Minecraft version is nolonger supported: " + nmsVersion); - } - /** * Load 3rdParty plugin support module. */ @@ -180,6 +140,80 @@ public class QuickShop extends JavaPlugin { } } + /** + * 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. + */ + private boolean loadEcon() { + try { + //EconomyCore core = new Economy_Vault(); + EconomyCore core = null; + switch (EconomyType.fromID(getConfig().getInt("economy-type"))) { + case UNKNOWN: + bootError = new BootError("Can't load the Economy provider, invaild value in config.yml."); + return false; + case VAULT: + core = new Economy_Vault(); + Util.debugLog("Now using the Vault economy system."); + break; + case RESERVE: + core = new Economy_Reserve(); + Util.debugLog("Now using the Reserve economy system."); + break; + } + if (!core.isValid()) { + // getLogger().severe("Economy is not valid!"); + bootError = BuiltInSolution.econError(); + // if(econ.equals("Vault")) + // getLogger().severe("(Does Vault have an Economy to hook into?!)"); + return false; + } else { + this.economy = new Economy(core); + return true; + } + } catch (Exception e) { + this.getSentryErrorReporter().ignoreThrow(); + e.printStackTrace(); + getLogger().severe("QuickShop could not hook into a economy/Not found Vault or Reserve!"); + getLogger().severe("QuickShop CANNOT start!"); + bootError = BuiltInSolution.econError(); + HandlerList.unregisterAll(this); + getLogger().severe("Plugin listeners was disabled, please fix the economy issue."); + return false; + } + } + + /** + * 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(@NotNull String s) { + if (this.getLogWatcher() == null) + return; + this.getLogWatcher().log(s); + } + + /** Reloads QuickShops config */ + @Override + public void reloadConfig() { + super.reloadConfig(); + // Load quick variables + this.display = this.getConfig().getBoolean("shop.display-items"); + this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee"); + this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks"); + language = new Language(this); //Init locale + if (this.getConfig().getBoolean("log-actions")) { + logWatcher = new LogWatcher(this, new File(getDataFolder(), "qs.log")); + } else { + logWatcher = null; + } + MsgUtil.loadCfgMessages(); + } + /** * Early than onEnable, make sure instance was loaded in first time. */ @@ -189,6 +223,51 @@ public class QuickShop extends JavaPlugin { bootError = null; } + @Override + public void onDisable() { + if (noopDisable) + return; + getLogger().info("QuickShop is finishing remaining work, this may need a while..."); + + Util.debugLog("Closing all GUIs..."); + for (Player player : Bukkit.getOnlinePlayers()) { + player.closeInventory(); + } + + Util.debugLog("Cleaning up database queues..."); + if (this.getShopManager() != null) + this.getDatabaseManager().uninit(); + + Util.debugLog("Unregistering tasks..."); + //if (itemWatcherTask != null) + // itemWatcherTask.cancel(); + if (logWatcher != null) { + logWatcher.close(); // Closes the file + } + /* Unload UpdateWatcher */ + UpdateWatcher.uninit(); + Util.debugLog("Cleaning up resources and unloading all shops..."); + /* Remove all display items, and any dupes we can find */ + if (shopManager != null) + shopManager.clear(); + /* Empty the buffer */ + if (databaseManager != null) + database.close(); + /* Close Database */ + if (database != null) + try { + this.database.getConnection().close(); + } catch (SQLException e) { + if (getSentryErrorReporter() != null) + this.getSentryErrorReporter().ignoreThrow(); + e.printStackTrace(); + } + if (warnings != null) + warnings.clear(); + //this.reloadConfig(); + Util.debugLog("All shutdown work is finished."); + } + @Override public void onEnable() { Timer enableTimer = new Timer(true); @@ -309,56 +388,43 @@ public class QuickShop extends JavaPlugin { }.runTaskLater(this, 1); } - private void submitMeritcs() { - if (!getConfig().getBoolean("disabled-metrics")) { - String serverVer = Bukkit.getVersion(); - String bukkitVer = Bukkit.getBukkitVersion(); - String serverName = Bukkit.getServer().getName(); - String vaultVer; - Plugin vault = Bukkit.getPluginManager().getPlugin("Vault"); - if (vault != null) { - vaultVer = vault.getDescription().getVersion(); - } else { - vaultVer = "Vault not found"; - } - // Use internal Metric class not Maven for solve plugin name issues - String display_Items; - if (getConfig().getBoolean("shop.display-items")) { // Maybe mod server use this plugin more? Or have big - // number items need disabled? - display_Items = "Enabled"; - } else { - display_Items = "Disabled"; - } - String locks; - if (getConfig().getBoolean("shop.lock")) { - locks = "Enabled"; - } else { - locks = "Disabled"; - } - String sneak_action; - if (getConfig().getBoolean("shop.sneak-to-create") || getConfig().getBoolean("shop.sneak-to-trade")) { - sneak_action = "Enabled"; - } else { - sneak_action = "Disabled"; - } - String shop_find_distance = getConfig().getString("shop.find-distance"); - // Version - metrics.addCustomChart(new Metrics.SimplePie("server_version", () -> serverVer)); - metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () -> bukkitVer)); - metrics.addCustomChart(new Metrics.SimplePie("vault_version", () -> vaultVer)); - metrics.addCustomChart(new Metrics.SimplePie("server_name", () -> serverName)); - metrics.addCustomChart(new Metrics.SimplePie("use_display_items", () -> display_Items)); - metrics.addCustomChart(new Metrics.SimplePie("use_locks", () -> locks)); - metrics.addCustomChart(new Metrics.SimplePie("use_sneak_action", () -> sneak_action)); - metrics.addCustomChart(new Metrics.SimplePie("shop_find_distance", () -> shop_find_distance)); - - // Exp for stats, maybe i need improve this, so i add this. - metrics.submitData(); // Submit now! - getLogger().info("Metrics submitted."); - } else { - getLogger().info("You have disabled mertics, Skipping..."); + /** + * Check the env plugin running. + * + * @throws RuntimeException The error message, use this to create a BootError. + */ + private void runtimeCheck() throws RuntimeException { + try { + getServer().spigot(); + } catch (Throwable e) { + getLogger().severe("FATAL: QSRR can only be run on Spigot servers and forks of Spigot!"); + throw new RuntimeException("Server must be Spigot based, Don't use CraftBukkit!"); } + if (getServer().getName().toLowerCase().contains("catserver")) { + // Send FATAL ERROR TO CatServer's users. + getLogger().severe("FATAL: QSRR can't run on CatServer Community/Personal/Pro"); + throw new RuntimeException("QuickShop doen't support CatServer"); + } + + if (Util.isDevEdition()) { + getLogger().severe("WARNING: You are running QSRR in dev-mode"); + getLogger().severe("WARNING: Keep backup and DO NOT run this in a production environment!"); + getLogger().severe("WARNING: Test version may destroy everything!"); + getLogger().severe( + "WARNING: QSRR won't start without your confirmation, nothing will change before you turn on dev allowed."); + if (!getConfig().getBoolean("dev-mode")) { + getLogger().severe( + "WARNING: Set dev-mode: true in config.yml to allow qs load in dev mode(You may need add this line to the config yourself)."); + noopDisable = true; + throw new RuntimeException("Snapshot cannot run when dev-mode is false in the config"); + } + } + String nmsVersion = Util.getNMSVersion(); + IncompatibleChecker incompatibleChecker = new IncompatibleChecker(); + getLogger().info("Running QuickShop-Reremake on Minecraft version " + nmsVersion); + if (incompatibleChecker.isIncompatible(nmsVersion)) + throw new RuntimeException("Your Minecraft version is nolonger supported: " + nmsVersion); } /** @@ -412,6 +478,58 @@ public class QuickShop extends JavaPlugin { return true; } + private void submitMeritcs() { + if (!getConfig().getBoolean("disabled-metrics")) { + String serverVer = Bukkit.getVersion(); + String bukkitVer = Bukkit.getBukkitVersion(); + String serverName = Bukkit.getServer().getName(); + String vaultVer; + Plugin vault = Bukkit.getPluginManager().getPlugin("Vault"); + if (vault != null) { + vaultVer = vault.getDescription().getVersion(); + } else { + vaultVer = "Vault not found"; + } + // Use internal Metric class not Maven for solve plugin name issues + String display_Items; + if (getConfig().getBoolean("shop.display-items")) { // Maybe mod server use this plugin more? Or have big + // number items need disabled? + display_Items = "Enabled"; + } else { + display_Items = "Disabled"; + } + String locks; + if (getConfig().getBoolean("shop.lock")) { + locks = "Enabled"; + } else { + locks = "Disabled"; + } + String sneak_action; + if (getConfig().getBoolean("shop.sneak-to-create") || getConfig().getBoolean("shop.sneak-to-trade")) { + sneak_action = "Enabled"; + } else { + sneak_action = "Disabled"; + } + String shop_find_distance = getConfig().getString("shop.find-distance"); + // Version + metrics.addCustomChart(new Metrics.SimplePie("server_version", () -> serverVer)); + metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () -> bukkitVer)); + metrics.addCustomChart(new Metrics.SimplePie("vault_version", () -> vaultVer)); + metrics.addCustomChart(new Metrics.SimplePie("server_name", () -> serverName)); + metrics.addCustomChart(new Metrics.SimplePie("use_display_items", () -> display_Items)); + metrics.addCustomChart(new Metrics.SimplePie("use_locks", () -> locks)); + metrics.addCustomChart(new Metrics.SimplePie("use_sneak_action", () -> sneak_action)); + metrics.addCustomChart(new Metrics.SimplePie("shop_find_distance", () -> shop_find_distance)); + + // Exp for stats, maybe i need improve this, so i add this. + metrics.submitData(); // Submit now! + getLogger().info("Metrics submitted."); + } else { + getLogger().info("You have disabled mertics, Skipping..."); + } + + } + @SuppressWarnings("UnusedAssignment") private void updateConfig(int selectedVersion) { String serverUUID = getConfig().getString("server-uuid"); @@ -675,124 +793,12 @@ public class QuickShop extends JavaPlugin { reloadConfig(); } - /** Reloads QuickShops config */ - @Override - public void reloadConfig() { - super.reloadConfig(); - // Load quick variables - this.display = this.getConfig().getBoolean("shop.display-items"); - this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee"); - this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks"); - language = new Language(this); //Init locale - if (this.getConfig().getBoolean("log-actions")) { - logWatcher = new LogWatcher(this, new File(getDataFolder(), "qs.log")); - } else { - logWatcher = null; - } - MsgUtil.loadCfgMessages(); - } - /** - * 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 the QSRR's fork edition name, you can modify this if you want create yourself fork. * - * @return true if successful, false if the core is invalid or is not found, and - * vault cannot be used. + * @return The fork name. */ - private boolean loadEcon() { - try { - //EconomyCore core = new Economy_Vault(); - EconomyCore core = null; - switch (EconomyType.fromID(getConfig().getInt("economy-type"))) { - case UNKNOWN: - bootError = new BootError("Can't load the Economy provider, invaild value in config.yml."); - return false; - case VAULT: - core = new Economy_Vault(); - Util.debugLog("Now using the Vault economy system."); - break; - case RESERVE: - core = new Economy_Reserve(); - Util.debugLog("Now using the Reserve economy system."); - break; - } - if (!core.isValid()) { - // getLogger().severe("Economy is not valid!"); - bootError = BuiltInSolution.econError(); - // if(econ.equals("Vault")) - // getLogger().severe("(Does Vault have an Economy to hook into?!)"); - return false; - } else { - this.economy = new Economy(core); - return true; - } - } catch (Exception e) { - this.getSentryErrorReporter().ignoreThrow(); - e.printStackTrace(); - getLogger().severe("QuickShop could not hook into a economy/Not found Vault or Reserve!"); - getLogger().severe("QuickShop CANNOT start!"); - bootError = BuiltInSolution.econError(); - HandlerList.unregisterAll(this); - getLogger().severe("Plugin listeners was disabled, please fix the economy issue."); - return false; - } - } - - @Override - public void onDisable() { - if (noopDisable) - return; - getLogger().info("QuickShop is finishing remaining work, this may need a while..."); - - Util.debugLog("Closing all GUIs..."); - for (Player player : Bukkit.getOnlinePlayers()) { - player.closeInventory(); - } - - Util.debugLog("Cleaning up database queues..."); - if (this.getShopManager() != null) - this.getDatabaseManager().uninit(); - - Util.debugLog("Unregistering tasks..."); - //if (itemWatcherTask != null) - // itemWatcherTask.cancel(); - if (logWatcher != null) { - logWatcher.close(); // Closes the file - } - /* Unload UpdateWatcher */ - UpdateWatcher.uninit(); - Util.debugLog("Cleaning up resources and unloading all shops..."); - /* Remove all display items, and any dupes we can find */ - if (shopManager != null) - shopManager.clear(); - /* Empty the buffer */ - if (databaseManager != null) - database.close(); - /* Close Database */ - if (database != null) - try { - this.database.getConnection().close(); - } catch (SQLException e) { - if (getSentryErrorReporter() != null) - this.getSentryErrorReporter().ignoreThrow(); - e.printStackTrace(); - } - if (warnings != null) - warnings.clear(); - //this.reloadConfig(); - Util.debugLog("All shutdown work is finished."); - } - - /** - * 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(@NotNull String s) { - if (this.getLogWatcher() == null) - return; - this.getLogWatcher().log(s); - } + public String getFork() { return "Reremake"; } /** * Returns QS version, this method only exist on QSRR forks If running other @@ -805,11 +811,4 @@ public class QuickShop extends JavaPlugin { return QuickShop.instance.getDescription().getVersion(); } - /** - * Return the QSRR's fork edition name, you can modify this if you want create yourself fork. - * - * @return The fork name. - */ - public String getFork() { return "Reremake"; } - } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java index cf12f4628..648bb40f1 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java @@ -21,10 +21,14 @@ import org.maxgamer.quickshop.Util.Util; @ToString public class ArmorStandDisplayItem implements DisplayItem { - private QuickShop plugin = QuickShop.instance; - private ItemStack originalItemStack; - private ItemStack guardedIstack; + private static boolean isTool(Material material) { + String nlc = material.name().toLowerCase(); + return nlc.contains("sword") || nlc.contains("shovel") || nlc.contains("axe"); + } private ArmorStand armorStand; + private ItemStack guardedIstack; + private ItemStack originalItemStack; + private QuickShop plugin = QuickShop.instance; private Shop shop; ArmorStandDisplayItem(@NotNull Shop shop) { @@ -33,6 +37,13 @@ public class ArmorStandDisplayItem implements DisplayItem { this.originalItemStack.setAmount(1); } + @Override + public boolean checkIsShopEntity(@NotNull Entity entity) { + if (!(entity instanceof ArmorStand)) + return false; + return DisplayItem.checkIsGuardItemStack(((ArmorStand) entity).getItemInHand()); + } + @Override public void spawn() { if (shop.getLocation().getWorld() == null) { @@ -77,6 +88,30 @@ public class ArmorStandDisplayItem implements DisplayItem { Util.debugLog("Spawned a new ArmorStand DisplayItem for a shop " + shop.getLocation().toString()); } + @Override + public boolean removeDupe() { + if (this.armorStand == null) { + Util.debugLog("Warning: Trying to removeDupe for a null display shop."); + return false; + } + boolean removed = false; + for (Entity entity : armorStand.getNearbyEntities(1, 1, 1)) { + if (!(entity instanceof ArmorStand)) + continue; + ArmorStand eArmorStand = (ArmorStand) entity; + + if (!eArmorStand.getUniqueId().equals(this.armorStand.getUniqueId())) { + if (DisplayItem.checkIsTargetShopDisplay(eArmorStand.getItemInHand(), this.shop)) { + Util.debugLog("Removing dupes ArmorEntity " + eArmorStand.getUniqueId().toString() + " at " + eArmorStand + .getLocation().toString()); + entity.remove(); + removed = true; + } + } + } + return removed; + } + @Override public void safeGuard(@NotNull Entity entity) { if (!(entity instanceof ArmorStand)) { @@ -90,11 +125,15 @@ public class ArmorStandDisplayItem implements DisplayItem { Util.debugLog("Successfully safeGuard ArmorStand: " + armorStand.getLocation().toString()); } - private void setPoseForArmorStand() { - if (this.originalItemStack.getType().isBlock()) - this.armorStand.setRightArmPose(new EulerAngle(-0.2, 0, 0)); - else - this.armorStand.setRightArmPose(new EulerAngle(-89.5, 0, 0)); + @Override + public void respawn() { + remove(); + spawn(); + } + + @Override + public Entity getDisplay() { + return this.armorStand; } @Override @@ -110,17 +149,6 @@ public class ArmorStandDisplayItem implements DisplayItem { Bukkit.getPluginManager().callEvent(shopDisplayItemDespawnEvent); } - @Override - public void respawn() { - remove(); - spawn(); - } - - @Override - public Entity getDisplay() { - return this.armorStand; - } - @Override public Location getDisplayLocation() { BlockFace containerBlockFace = BlockFace.NORTH; //Set default vaule @@ -182,6 +210,13 @@ public class ArmorStandDisplayItem implements DisplayItem { return asloc; } + private void setPoseForArmorStand() { + if (this.originalItemStack.getType().isBlock()) + this.armorStand.setRightArmPose(new EulerAngle(-0.2, 0, 0)); + else + this.armorStand.setRightArmPose(new EulerAngle(-89.5, 0, 0)); + } + @Override public boolean checkDisplayIsMoved() { if (this.armorStand == null) @@ -196,37 +231,6 @@ public class ArmorStandDisplayItem implements DisplayItem { return !this.armorStand.isValid() || this.armorStand.isDead(); } - @Override - public boolean checkIsShopEntity(@NotNull Entity entity) { - if (!(entity instanceof ArmorStand)) - return false; - return DisplayItem.checkIsGuardItemStack(((ArmorStand) entity).getItemInHand()); - } - - @Override - public boolean removeDupe() { - if (this.armorStand == null) { - Util.debugLog("Warning: Trying to removeDupe for a null display shop."); - return false; - } - boolean removed = false; - for (Entity entity : armorStand.getNearbyEntities(1, 1, 1)) { - if (!(entity instanceof ArmorStand)) - continue; - ArmorStand eArmorStand = (ArmorStand) entity; - - if (!eArmorStand.getUniqueId().equals(this.armorStand.getUniqueId())) { - if (DisplayItem.checkIsTargetShopDisplay(eArmorStand.getItemInHand(), this.shop)) { - Util.debugLog("Removing dupes ArmorEntity " + eArmorStand.getUniqueId().toString() + " at " + eArmorStand - .getLocation().toString()); - entity.remove(); - removed = true; - } - } - } - return removed; - } - @Override public void fixDisplayMoved() { for (Entity entity : this.shop.getLocation().getWorld().getEntities()) { @@ -253,9 +257,4 @@ public class ArmorStandDisplayItem implements DisplayItem { return false; return this.armorStand.isValid(); } - - private static boolean isTool(Material material) { - String nlc = material.name().toLowerCase(); - return nlc.contains("sword") || nlc.contains("shovel") || nlc.contains("axe"); - } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java index 9aa52575e..aac3247de 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java @@ -34,26 +34,15 @@ import org.maxgamer.quickshop.Util.Util; @EqualsAndHashCode @ToString public class ContainerShop implements Shop { - private Location loc; - private double price; - private ShopModerator moderator; - private ItemStack item; private DisplayItem displayItem; - private boolean unlimited; - private ShopType shopType; - private QuickShop plugin; @EqualsAndHashCode.Exclude private boolean isLoaded = false; - - /** - * 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** - */ - public ContainerShop clone() { - return new ContainerShop(this); - } + private ItemStack item; + private Location loc; + private ShopModerator moderator; + private QuickShop plugin; + private double price; + private ShopType shopType; + private boolean unlimited; private ContainerShop(@NotNull ContainerShop s) { this.displayItem = s.displayItem; @@ -110,6 +99,16 @@ public class ContainerShop implements Shop { } + @Override + public boolean addStaff(@NotNull UUID player) { + boolean result = this.moderator.addStaff(player); + update(); + if (result == false) + return result; + Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); + return result; + } + /** * Returns the number of items this shop has in stock. * @@ -142,47 +141,6 @@ public class ContainerShop implements Shop { return plugin.getItemMatcher().matches(this.item, item); } - /** - * 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() { - Block c = Util.getSecondHalf(this.getLocation().getBlock()); - if (c == null) - return null; - Shop shop = plugin.getShopManager().getShop(c.getLocation()); - return shop == null ? null : (ContainerShop) shop; - } - - /** - * 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() { - 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; - } else { - // One is buying, one is selling. - return true; - } - } else { - return false; - } - } - /** * @return The location of the shops chest */ @@ -209,13 +167,6 @@ public class ContainerShop implements Shop { update(); } - /** - * @return The ItemStack type of this shop - */ - public Material getMaterial() { - return this.item.getType(); - } - /** * Upates the shop into the database. */ @@ -249,32 +200,6 @@ public class ContainerShop implements Shop { return (short) ((Damageable) this.item.getItemMeta()).getDamage(); } - /** - * @return The chest this shop is based on. - */ - public Inventory getInventory() { - try { - if (loc.getBlock().getState().getType() == Material.ENDER_CHEST && plugin.getOpenInvPlugin() != null) { - OpenInv openInv = ((OpenInv) plugin.getOpenInvPlugin()); - return openInv.getSpecialEnderChest(openInv.loadPlayer(Bukkit.getOfflinePlayer(this.moderator.getOwner() - )), Bukkit.getOfflinePlayer((this.moderator.getOwner())).isOnline()).getBukkitInventory(); - } - } catch (Exception e) { - Util.debugLog(e.getMessage()); - return null; - } - InventoryHolder container; - try { - container = (InventoryHolder) this.loc.getBlock().getState(); - return container.getInventory(); - } catch (Exception e) { - this.onUnload(); - this.delete(); - Util.debugLog("Inventory doesn't exist anymore: " + this + " shop was removed."); - return null; - } - } - /** * @return The name of the player who owns the shop. */ @@ -282,48 +207,6 @@ public class ContainerShop implements Shop { return this.moderator.getOwner(); } - /** - * @return The list of players who can manage the shop. - */ - @Override - public ArrayList getStaffs() { - return this.moderator.getStaffs(); - } - - @Override - public boolean addStaff(@NotNull UUID player) { - boolean result = this.moderator.addStaff(player); - update(); - if (result == false) - return result; - Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); - return result; - } - - @Override - public boolean delStaff(@NotNull UUID player) { - boolean result = this.moderator.delStaff(player); - update(); - if (result == false) - return result; - Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); - return result; - } - - @Override - public void clearStaffs() { - this.moderator.clearStaffs(); - Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); - update(); - } - - /** - * @return The enchantments the shop has on its items. - */ - public Map getEnchants() { - return this.item.getItemMeta().getEnchants(); - } - /** * @return Returns a dummy itemstack of the item this shop is selling. */ @@ -483,6 +366,56 @@ public class ContainerShop implements Shop { } } + @Override + public void checkDisplay() { + Util.debugLog("Checking the display..."); + if (!plugin.isDisplay()) + return; + if (!this.isLoaded) { + Util.debugLog("Shop not loaded, skipping..."); + return; + } + if (this.displayItem == null) { + Util.debugLog("Warning: DisplayItem is null, this shouldn't happend..."); + Util.debugLog("Call from: " + Thread.currentThread().getStackTrace()[2].getClassName() + "#" + Thread.currentThread() + .getStackTrace()[2].getMethodName() + "%" + Thread.currentThread().getStackTrace()[2].getLineNumber()); + return; + } + if (!this.displayItem.isSpawned()) { + /* Not spawned yet. */ + Util.debugLog("Target item not spawned, spawning..."); + this.displayItem.spawn(); + } else { + /* If not spawned, we didn't need check these, only check them when we need. */ + if (this.displayItem.checkDisplayNeedRegen()) { + this.displayItem.fixDisplayNeedRegen(); + } else {/* If display was regened, we didn't need check it moved, performance! */ + if (this.displayItem.checkDisplayIsMoved()) + this.displayItem.fixDisplayMoved(); + } + } + /* Dupe is always need check, if enabled display */ + if (plugin.isDisplay()) + this.displayItem.removeDupe(); + } + + @Override + public void clearStaffs() { + this.moderator.clearStaffs(); + Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); + update(); + } + + @Override + public boolean delStaff(@NotNull UUID player) { + boolean result = this.moderator.delStaff(player); + update(); + if (result == false) + return result; + Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); + return result; + } + /** * Changes the owner of this shop to the given player. * @@ -495,6 +428,52 @@ public class ContainerShop implements Shop { update(); } + /** + * @return The list of players who can manage the shop. + */ + @Override + public ArrayList getStaffs() { + return this.moderator.getStaffs(); + } + + /** + * 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** + */ + public ContainerShop clone() { + return new ContainerShop(this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Shop " + (loc.getWorld() == null ? + "unloaded world" : + loc.getWorld().getName()) + "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")"); + sb.append(" Owner: " + this.ownerName() + " - " + getOwner().toString()); + if (isUnlimited()) + sb.append(" Unlimited: true"); + sb.append(" Price: " + getPrice()); + sb.append(" Item: " + getItem().toString()); + return sb.toString(); + } + + /** + * 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() { + Block c = Util.getSecondHalf(this.getLocation().getBlock()); + if (c == null) + return null; + Shop shop = plugin.getShopManager().getShop(c.getLocation()); + return shop == null ? null : (ContainerShop) shop; + } + /** * Returns the display item associated with this shop. * @@ -504,6 +483,77 @@ public class ContainerShop implements Shop { return this.displayItem; } + /** + * @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() { + try { + if (loc.getBlock().getState().getType() == Material.ENDER_CHEST && plugin.getOpenInvPlugin() != null) { + OpenInv openInv = ((OpenInv) plugin.getOpenInvPlugin()); + return openInv.getSpecialEnderChest(openInv.loadPlayer(Bukkit.getOfflinePlayer(this.moderator.getOwner() + )), Bukkit.getOfflinePlayer((this.moderator.getOwner())).isOnline()).getBukkitInventory(); + } + } catch (Exception e) { + Util.debugLog(e.getMessage()); + return null; + } + InventoryHolder container; + try { + container = (InventoryHolder) this.loc.getBlock().getState(); + return container.getInventory(); + } catch (Exception e) { + this.onUnload(); + this.delete(); + Util.debugLog("Inventory doesn't exist anymore: " + this + " shop was removed."); + return null; + } + } + + /** + * @return The ItemStack type of this shop + */ + public Material getMaterial() { + return this.item.getType(); + } + + /** + * 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() { + 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; + } else { + // One is buying, one is selling. + return true; + } + } else { + return false; + } + } + + + + + public void setUnlimited(boolean unlimited) { this.unlimited = unlimited; this.setSignText(); @@ -770,19 +820,6 @@ public class ContainerShop implements Shop { return name; } - @Override - public String toString() { - StringBuilder sb = new StringBuilder("Shop " + (loc.getWorld() == null ? - "unloaded world" : - loc.getWorld().getName()) + "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")"); - sb.append(" Owner: " + this.ownerName() + " - " + getOwner().toString()); - if (isUnlimited()) - sb.append(" Unlimited: true"); - sb.append(" Price: " + getPrice()); - sb.append(" Item: " + getItem().toString()); - return sb.toString(); - } - @Override public ShopModerator getModerator() { return this.moderator.clone(); @@ -800,36 +837,4 @@ public class ContainerShop implements Shop { return this.isLoaded; } - @Override - public void checkDisplay() { - Util.debugLog("Checking the display..."); - if (!plugin.isDisplay()) - return; - if (!this.isLoaded) { - Util.debugLog("Shop not loaded, skipping..."); - return; - } - if (this.displayItem == null) { - Util.debugLog("Warning: DisplayItem is null, this shouldn't happend..."); - Util.debugLog("Call from: " + Thread.currentThread().getStackTrace()[2].getClassName() + "#" + Thread.currentThread() - .getStackTrace()[2].getMethodName() + "%" + Thread.currentThread().getStackTrace()[2].getLineNumber()); - return; - } - if (!this.displayItem.isSpawned()) { - /* Not spawned yet. */ - Util.debugLog("Target item not spawned, spawning..."); - this.displayItem.spawn(); - } else { - /* If not spawned, we didn't need check these, only check them when we need. */ - if (this.displayItem.checkDisplayNeedRegen()) { - this.displayItem.fixDisplayNeedRegen(); - } else {/* If display was regened, we didn't need check it moved, performance! */ - if (this.displayItem.checkDisplayIsMoved()) - this.displayItem.fixDisplayMoved(); - } - } - /* Dupe is always need check, if enabled display */ - if (plugin.isDisplay()) - this.displayItem.removeDupe(); - } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java index 87c60b67c..a48af3129 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java @@ -18,111 +18,6 @@ import org.maxgamer.quickshop.Util.Util; * cannot be interacted with. */ public interface DisplayItem { - /** - * Spawn new Displays - */ - void spawn(); - - /** - * Respawn the displays, if it not exist, it will spawn new one. - */ - void respawn(); - - /** - * Add the protect flags for entity or entity's hand item. - * Target entity will got protect by QuickShop - * - * @param entity Target entity - */ - void safeGuard(Entity entity); - - /** - * Check target Entity is or not a QuickShop display Entity. - * @param entity Target entity - * @return Is or not - */ - boolean checkIsShopEntity(Entity entity); - - /** - * Remove this shop's display in the whole world.(Not whole server) - * @return Success - */ - boolean removeDupe(); - - /** - * Remove the display entity. - */ - void remove(); - - - /** - * Get display should at location. - * Not display current location. - * @return Should at - */ - Location getDisplayLocation(); - - /** - * Get the display entity - * @return Target entity - */ - Entity getDisplay(); - - /** - * Check the display is or not moved. - * @return Moved - */ - boolean checkDisplayIsMoved(); - - /** - * Check the display is or not need respawn - * @return Need - */ - boolean checkDisplayNeedRegen(); - - /** - * Fix the display moved issue. - */ - void fixDisplayMoved(); - - /** - * Fix display need respawn issue. - */ - void fixDisplayNeedRegen(); - - /** - * Check the display is or not already spawned - * - * @return Spawned - */ - boolean isSpawned(); - - /** - * Create a new itemStack with protect flag. - * @param itemStack Old itemStack - * @param shop The shop - * @return New itemStack with protect flag. - */ - static ItemStack createGuardItemStack(@NotNull ItemStack itemStack, @NotNull Shop shop) { - itemStack = itemStack.clone(); - itemStack.setAmount(1); - ItemMeta iMeta = itemStack.getItemMeta(); - if (QuickShop.instance.getConfig().getBoolean("shop.display-item-use-name")) { - iMeta.setDisplayName("QuickShop DisplayItem"); - } - java.util.List lore = new ArrayList(); - Gson gson = new Gson(); - ShopProtectionFlag shopProtectionFlag = new ShopProtectionFlag(shop.getLocation().toString(), Util - .serialize(shop.getItem())); - String protectFlag = gson.toJson(shopProtectionFlag); - for (int i = 0; i < 21; i++) { - lore.add(protectFlag); //Create 20 lines lore to make sure no stupid plugin accident remove mark. - } - iMeta.setLore(lore); - itemStack.setItemMeta(iMeta); - return itemStack; - } - /** * Check the itemStack is contains protect flag. * @param itemStack Target ItemStack @@ -193,6 +88,109 @@ public interface DisplayItem { return false; } + /** + * Create a new itemStack with protect flag. + * + * @param itemStack Old itemStack + * @param shop The shop + * @return New itemStack with protect flag. + */ + static ItemStack createGuardItemStack(@NotNull ItemStack itemStack, @NotNull Shop shop) { + itemStack = itemStack.clone(); + itemStack.setAmount(1); + ItemMeta iMeta = itemStack.getItemMeta(); + if (QuickShop.instance.getConfig().getBoolean("shop.display-item-use-name")) { + iMeta.setDisplayName("QuickShop DisplayItem"); + } + java.util.List lore = new ArrayList(); + Gson gson = new Gson(); + ShopProtectionFlag shopProtectionFlag = new ShopProtectionFlag(shop.getLocation().toString(), Util.serialize(itemStack)); + String protectFlag = gson.toJson(shopProtectionFlag); + for (int i = 0; i < 21; i++) { + lore.add(protectFlag); //Create 20 lines lore to make sure no stupid plugin accident remove mark. + } + iMeta.setLore(lore); + itemStack.setItemMeta(iMeta); + return itemStack; + } + + /** + * Check the display is or not moved. + * + * @return Moved + */ + boolean checkDisplayIsMoved(); + + /** + * Check the display is or not need respawn + * + * @return Need + */ + boolean checkDisplayNeedRegen(); + + /** + * Check target Entity is or not a QuickShop display Entity. + * + * @param entity Target entity + * @return Is or not + */ + boolean checkIsShopEntity(Entity entity); + + /** + * Fix the display moved issue. + */ + void fixDisplayMoved(); + + /** + * Fix display need respawn issue. + */ + void fixDisplayNeedRegen(); + + /** + * Remove the display entity. + */ + void remove(); + + /** + * Remove this shop's display in the whole world.(Not whole server) + * + * @return Success + */ + boolean removeDupe(); + + /** + * Respawn the displays, if it not exist, it will spawn new one. + */ + void respawn(); + + /** + * Add the protect flags for entity or entity's hand item. + * Target entity will got protect by QuickShop + * + * @param entity Target entity + */ + void safeGuard(Entity entity); + + /** + * Spawn new Displays + */ + void spawn(); + + /** + * Get the display entity + * + * @return Target entity + */ + Entity getDisplay(); + + /** + * Get display should at location. + * Not display current location. + * + * @return Should at + */ + Location getDisplayLocation(); + /** * Get plugin now is using which one DisplayType * @return Using displayType. @@ -201,4 +199,11 @@ public interface DisplayItem { return DisplayType.fromID(QuickShop.instance.getConfig().getInt("shop.display-type")); } + /** + * Check the display is or not already spawned + * + * @return Spawned + */ + boolean isSpawned(); + } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Shop/DisplayType.java b/src/main/java/org/maxgamer/quickshop/Shop/DisplayType.java index 7e8e76b77..ace72356f 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/DisplayType.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/DisplayType.java @@ -4,12 +4,6 @@ import org.jetbrains.annotations.*; public enum DisplayType { UNKNOWN(-1), REALITEM(0), ARMORSTAND(1), VIRTUALITEM(2); - private int id; - - DisplayType(int id) { - this.id = id; - } - public static DisplayType fromID(int id) { for (DisplayType type : DisplayType.values()) { if (type.id == id) { @@ -23,10 +17,6 @@ public enum DisplayType { return displayType.id; } - public int toID() { - return id; - } - public static DisplayType typeIs(@Nullable DisplayItem displayItem) { if (displayItem instanceof RealDisplayItem) return REALITEM; @@ -34,4 +24,14 @@ public enum DisplayType { return ARMORSTAND; return UNKNOWN; } + + private int id; + + DisplayType(int id) { + this.id = id; + } + + public int toID() { + return id; + } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/Info.java b/src/main/java/org/maxgamer/quickshop/Shop/Info.java index 43e909431..d6774eba3 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/Info.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/Info.java @@ -12,10 +12,10 @@ import org.jetbrains.annotations.*; @EqualsAndHashCode @ToString public class Info { - private Location loc; private ShopAction action; private ItemStack item; private Block last; + private Location loc; private Shop shop; public Info(@NotNull Location loc, @NotNull ShopAction action, @Nullable ItemStack item, @Nullable Block last) { @@ -63,11 +63,8 @@ public class Info { return this.action; } - /** - * @return Location loc, Get shop's location, - */ - public Location getLocation() { - return this.loc; + public void setAction(ShopAction action) { + this.action = action; } /* @@ -82,8 +79,11 @@ public class Info { return this.item; } - public void setAction(ShopAction action) { - this.action = action; + /** + * @return Location loc, Get shop's location, + */ + public Location getLocation() { + return this.loc; } /** diff --git a/src/main/java/org/maxgamer/quickshop/Shop/InventoryPreview.java b/src/main/java/org/maxgamer/quickshop/Shop/InventoryPreview.java index 6a3c66e9a..04cb20b43 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/InventoryPreview.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/InventoryPreview.java @@ -23,8 +23,21 @@ import org.maxgamer.quickshop.Util.Util; @ToString public class InventoryPreview implements Listener { - private ItemStack itemStack; + public static boolean isPreviewItem(@Nullable ItemStack stack) { + if (stack == null) + return false; + if (!stack.hasItemMeta() || !stack.getItemMeta().hasLore()) + return false; + List lores = stack.getItemMeta().getLore(); + for (String string : lores) { + if (string.equals("QuickShop GUI preview item")) { + return true; + } + } + return false; + } private Inventory inventory; + private ItemStack itemStack; private Player player; /** @@ -51,6 +64,15 @@ public class InventoryPreview implements Listener { } } + public void close() { + if (inventory == null) + return; + for (HumanEntity player : inventory.getViewers()) { + player.closeInventory(); + } + inventory = null; // Destory + } + /** * Open the preview GUI for player. */ @@ -76,27 +98,4 @@ public class InventoryPreview implements Listener { } player.openInventory(inventory); } - - public void close() { - if (inventory == null) - return; - for (HumanEntity player : inventory.getViewers()) { - player.closeInventory(); - } - inventory = null; // Destory - } - - public static boolean isPreviewItem(@Nullable ItemStack stack) { - if (stack == null) - return false; - if (!stack.hasItemMeta() || !stack.getItemMeta().hasLore()) - return false; - List lores = stack.getItemMeta().getLore(); - for (String string : lores) { - if (string.equals("QuickShop GUI preview item")) { - return true; - } - } - return false; - } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java index 23f398807..f045bfc3e 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java @@ -17,11 +17,11 @@ import org.maxgamer.quickshop.Util.Util; @ToString public class RealDisplayItem implements DisplayItem { - private Shop shop; - private ItemStack originalItemStack; + private static QuickShop plugin = QuickShop.instance; private ItemStack guardedIstack; private Item item; - private static QuickShop plugin = QuickShop.instance; + private ItemStack originalItemStack; + private Shop shop; /** * ZZ Creates a new display item. @@ -37,55 +37,48 @@ public class RealDisplayItem implements DisplayItem { } @Override - public void spawn() { - if (shop.getLocation().getWorld() == null) { - Util.debugLog("Canceled the displayItem spawning because the location in the world is null."); - return; - } - - if (originalItemStack == null) { - Util.debugLog("Canceled the displayItem spawning because the ItemStack is null."); - return; - } - if (item != null && item.isValid() && !item.isDead()) { - Util.debugLog("Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!"); - StackTraceElement[] traces = Thread.currentThread().getStackTrace(); - for (StackTraceElement trace : traces) { - Util.debugLog(trace.getClassName() + "#" + trace.getMethodName() + "#" + trace.getLineNumber()); - } - } - if (!Util.isDisplayAllowBlock(getDisplayLocation().getBlock().getType())) { - Util.debugLog("Can't spawn the displayItem because there is not an AIR block above the shopblock."); - return; - } - - ShopDisplayItemSpawnEvent shopDisplayItemSpawnEvent = new ShopDisplayItemSpawnEvent(shop, originalItemStack, DisplayType.REALITEM); - Bukkit.getPluginManager().callEvent(shopDisplayItemSpawnEvent); - if (shopDisplayItemSpawnEvent.isCancelled()) { - Util.debugLog("Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on"); - return; - } - - this.item = this.shop.getLocation().getWorld().dropItem(getDisplayLocation(), originalItemStack); - this.item.setPickupDelay(Integer.MAX_VALUE); - this.item.setSilent(true); - this.item.setPortalCooldown(Integer.MAX_VALUE); - this.item.setVelocity(new Vector(0, 0.1, 0)); - safeGuard(this.item); - Util.debugLog("Spawned new DisplayItem for shop " + shop.getLocation().toString()); + public boolean checkDisplayIsMoved() { + if (this.item == null) + return false; + //return !this.item.getLocation().equals(getDisplayLocation()); + /* We give 0.6 block to allow item drop on the chest, not floating on the air. */ + if (!this.item.getLocation().getWorld().equals(getDisplayLocation().getWorld())) + return true; + return this.item.getLocation().distance(getDisplayLocation()) > 0.6; } @Override - public void safeGuard(@NotNull Entity entity) { - if (!(entity instanceof Item)) { - Util.debugLog("Failed to safeGuard " + entity.getLocation().toString() + ", cause target not a Item"); - return; + public boolean checkDisplayNeedRegen() { + if (this.item == null) + return false; + return !this.item.isValid() || this.item.isDead(); + } + + @Override + public boolean checkIsShopEntity(@NotNull Entity entity) { + if (!(entity instanceof Item)) + return false; + return DisplayItem.checkIsGuardItemStack(((Item) entity).getItemStack()); + } + + @Override + public void fixDisplayMoved() { + for (Entity entity : this.shop.getLocation().getWorld().getEntities()) { + if (!(entity instanceof Item)) + continue; + Item eItem = (Item) entity; + if (eItem.getUniqueId().equals(this.item.getUniqueId())) { + Util.debugLog("Fixing moved Item displayItem " + eItem.getUniqueId().toString() + " at " + eItem + .getLocation().toString()); + eItem.teleport(getDisplayLocation()); + return; + } } - Item item = (Item) entity; - //Set item protect in the armorstand's hand - this.guardedIstack = DisplayItem.createGuardItemStack(this.originalItemStack, this.shop); - item.setItemStack(this.guardedIstack); - Util.debugLog("Successfully safeGuard Item: " + item.getLocation().toString()); + } + + @Override + public void fixDisplayNeedRegen() { + respawn(); } @Override @@ -139,54 +132,66 @@ public class RealDisplayItem implements DisplayItem { spawn(); } + @Override + public void safeGuard(@NotNull Entity entity) { + if (!(entity instanceof Item)) { + Util.debugLog("Failed to safeGuard " + entity.getLocation().toString() + ", cause target not a Item"); + return; + } + Item item = (Item) entity; + //Set item protect in the armorstand's hand + this.guardedIstack = DisplayItem.createGuardItemStack(this.originalItemStack, this.shop); + item.setItemStack(this.guardedIstack); + Util.debugLog("Successfully safeGuard Item: " + item.getLocation().toString()); + } + + @Override + public void spawn() { + if (shop.getLocation().getWorld() == null) { + Util.debugLog("Canceled the displayItem spawning because the location in the world is null."); + return; + } + + if (originalItemStack == null) { + Util.debugLog("Canceled the displayItem spawning because the ItemStack is null."); + return; + } + if (item != null && item.isValid() && !item.isDead()) { + Util.debugLog("Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!"); + StackTraceElement[] traces = Thread.currentThread().getStackTrace(); + for (StackTraceElement trace : traces) { + Util.debugLog(trace.getClassName() + "#" + trace.getMethodName() + "#" + trace.getLineNumber()); + } + } + if (!Util.isDisplayAllowBlock(getDisplayLocation().getBlock().getType())) { + Util.debugLog("Can't spawn the displayItem because there is not an AIR block above the shopblock."); + return; + } + + ShopDisplayItemSpawnEvent shopDisplayItemSpawnEvent = new ShopDisplayItemSpawnEvent(shop, originalItemStack, DisplayType.REALITEM); + Bukkit.getPluginManager().callEvent(shopDisplayItemSpawnEvent); + if (shopDisplayItemSpawnEvent.isCancelled()) { + Util.debugLog("Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on"); + return; + } + + this.item = this.shop.getLocation().getWorld().dropItem(getDisplayLocation(), originalItemStack); + this.item.setPickupDelay(Integer.MAX_VALUE); + this.item.setSilent(true); + this.item.setPortalCooldown(Integer.MAX_VALUE); + this.item.setVelocity(new Vector(0, 0.1, 0)); + safeGuard(this.item); + Util.debugLog("Spawned new DisplayItem for shop " + shop.getLocation().toString()); + } + @Override public Entity getDisplay() { return this.item; } @Override - public boolean checkIsShopEntity(@NotNull Entity entity) { - if (!(entity instanceof Item)) - return false; - return DisplayItem.checkIsGuardItemStack(((Item) entity).getItemStack()); - } - - @Override - public boolean checkDisplayNeedRegen() { - if (this.item == null) - return false; - return !this.item.isValid() || this.item.isDead(); - } - - @Override - public boolean checkDisplayIsMoved() { - if (this.item == null) - return false; - //return !this.item.getLocation().equals(getDisplayLocation()); - /* We give 0.6 block to allow item drop on the chest, not floating on the air. */ - if (!this.item.getLocation().getWorld().equals(getDisplayLocation().getWorld())) - return true; - return this.item.getLocation().distance(getDisplayLocation()) > 0.6; - } - - @Override - public void fixDisplayNeedRegen() { - respawn(); - } - - @Override - public void fixDisplayMoved() { - for (Entity entity : this.shop.getLocation().getWorld().getEntities()) { - if (!(entity instanceof Item)) - continue; - Item eItem = (Item) entity; - if (eItem.getUniqueId().equals(this.item.getUniqueId())) { - Util.debugLog("Fixing moved Item displayItem " + eItem.getUniqueId().toString() + " at " + eItem - .getLocation().toString()); - eItem.teleport(getDisplayLocation()); - return; - } - } + public Location getDisplayLocation() { + return this.shop.getLocation().clone().add(0.5, 1.2, 0.5); } @Override @@ -195,9 +200,4 @@ public class RealDisplayItem implements DisplayItem { return false; return this.item.isValid(); } - - @Override - public Location getDisplayLocation() { - return this.shop.getLocation().clone().add(0.5, 1.2, 0.5); - } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/Shop.java b/src/main/java/org/maxgamer/quickshop/Shop/Shop.java index edb9fb5e3..4c504f903 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/Shop.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/Shop.java @@ -11,6 +11,40 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public interface Shop { + /** + * Add x ItemStack to the shop inventory + * + * @param paramItemStack The ItemStack you want add + * @param paramInt How many you want add + */ + void add(ItemStack paramItemStack, int paramInt); + + /** + * Add new staff to the moderators + * + * @param player New staff + * @return Success + */ + boolean addStaff(UUID player); + + /** + * Execute buy action for player with x items. + * + * @param paramPlayer Target player + * @param paramInt How many buyed? + */ + void buy(Player paramPlayer, int paramInt); + + /** + * Check the display location, and teleport, respawn if needs. + */ + void checkDisplay(); + + /** + * Empty moderators team. + */ + void clearStaffs(); + /** * Clone new shop object. * Not a deep clone. @@ -20,163 +54,11 @@ public interface Shop { Shop clone(); /** - * Check the display location, and teleport, respawn if needs. + * Remove a staff from moderators + * @param player Staff + * @return Success */ - void checkDisplay(); - - /** - * Get shop remaining stock. - * @return Remaining stock. - */ - int getRemainingStock(); - - /** - * Get shop remaining space. - * @return Remaining space. - */ - int getRemainingSpace(); - - /** - * Check the target ItemStack is matches with this shop's item. - * @param paramItemStack Target ItemStack. - * @return Matches - */ - boolean matches(ItemStack paramItemStack); - - /** - * Get shop's location - * @return Shop's location - */ - Location getLocation(); - - /** - * Get shop's price - * @return Price - */ - double getPrice(); - - /** - * Set shop's new price - * @param paramDouble New price - */ - void setPrice(double paramDouble); - - /** - * Update shop data to database - */ - void update(); - - /** - * Get shop's item durability, if have. - * @return Shop's item durability - */ - short getDurability(); - - /** - * Get shop's owner UUID - * @return Shop's owner UUID, can use Bukkit.getOfflinePlayer to convert to the OfflinePlayer. - */ - UUID getOwner(); - - /** - * Get shop item's ItemStack - * @return The shop's ItemStack - */ - ItemStack getItem(); - - /** - * Remove x ItemStack from the shop inventory - * @param paramItemStack Want removed ItemStack - * @param paramInt Want remove how many - */ - void remove(ItemStack paramItemStack, int paramInt); - - /** - * Add x ItemStack to the shop inventory - * @param paramItemStack The ItemStack you want add - * @param paramInt How many you want add - */ - void add(ItemStack paramItemStack, int paramInt); - - /** - * Execute sell action for player with x items. - * @param paramPlayer Target player - * @param paramInt How many sold? - */ - void sell(Player paramPlayer, int paramInt); - - /** - * Execute buy action for player with x items. - * @param paramPlayer Target player - * @param paramInt How many buyed? - */ - void buy(Player paramPlayer, int paramInt); - - /** - * Set new owner to the shop's owner - * @param paramString New owner UUID - */ - void setOwner(UUID paramString); - - /** - * Set shop is or not Unlimited Mode (Admin Shop) - * @param paramBoolean status - */ - void setUnlimited(boolean paramBoolean); - - /** - * Get shop is or not in Unlimited Mode (Admin Shop) - * @return yes or not - */ - boolean isUnlimited(); - - /** - * Get shop type - * @return shop type - */ - ShopType getShopType(); - - /** - * Get shop is or not in buying mode - * @return yes or no - */ - boolean isBuying(); - - /** - * Get shop is or not in selling mode - * @return yes or no - */ - boolean isSelling(); - - /** - * Set new shop type for this shop - * @param paramShopType New shop type - */ - void setShopType(ShopType paramShopType); - - /** - * Generate new sign texts on shop's sign. - */ - void setSignText(); - - /** - * Set texts on shop's sign - * @param paramArrayOfString The texts you want set - */ - void setSignText(String[] paramArrayOfString); - - /** - * Get shop signs, may have multi signs - * @return Signs for the shop - */ - List getSigns(); - - /** - * Check shop is or not attacked the target block - * @param paramBlock Target block - * @return isAttached - */ - boolean isAttached(Block paramBlock); + boolean delStaff(UUID player); /** * Delete shop from ram, and database. @@ -190,32 +72,96 @@ public interface Shop { void delete(boolean paramBoolean); /** - * Shop is valid - * @return status + * Check shop is or not attacked the target block + * + * @param paramBlock Target block + * @return isAttached */ - boolean isValid(); + boolean isAttached(Block paramBlock); /** - * Unload shop from world + * Check the target ItemStack is matches with this shop's item. + * @param paramItemStack Target ItemStack. + * @return Matches */ - void onUnload(); - - /** - * Load shop to the world - */ - void onLoad(); + boolean matches(ItemStack paramItemStack); /** * Execute codes when player click the shop will did things */ void onClick(); + /** + * Load shop to the world + */ + void onLoad(); + + /** + * Unload shop from world + */ + void onUnload(); + /** * Get shop's owner name, it will return owner name or Admin Shop(i18n) when it is unlimited * @return owner name */ String ownerName(); + /** + * Remove x ItemStack from the shop inventory + * @param paramItemStack Want removed ItemStack + * @param paramInt Want remove how many + */ + void remove(ItemStack paramItemStack, int paramInt); + + /** + * Execute sell action for player with x items. + * @param paramPlayer Target player + * @param paramInt How many sold? + */ + void sell(Player paramPlayer, int paramInt); + + /** + * Generate new sign texts on shop's sign. + */ + void setSignText(); + + /** + * Update shop data to database + */ + void update(); + + /** + * Set new shop type for this shop + * @param paramShopType New shop type + */ + void setShopType(ShopType paramShopType); + + /** + * Get shop's item durability, if have. + * @return Shop's item durability + */ + short getDurability(); + + /** + * Get shop item's ItemStack + * + * @return The shop's ItemStack + */ + ItemStack getItem(); + + /** + * Set texts on shop's sign + * @param paramArrayOfString The texts you want set + */ + void setSignText(String[] paramArrayOfString); + + /** + * Get shop's location + * @return Shop's location + */ + Location getLocation(); + /** * Return this shop's moderators * @return Shop moderators @@ -229,35 +175,104 @@ public interface Shop { void setModerator(ShopModerator shopModerator); /** - * Add new staff to the moderators - * @param player New staff - * @return Success + * Get shop's owner UUID + * + * @return Shop's owner UUID, can use Bukkit.getOfflinePlayer to convert to the OfflinePlayer. */ - boolean addStaff(UUID player); + UUID getOwner(); /** - * Remove a staff from moderators - * @param player Staff - * @return Success + * Set new owner to the shop's owner + * + * @param paramString New owner UUID */ - boolean delStaff(UUID player); + void setOwner(UUID paramString); /** - * Empty moderators team. + * Get shop's price + * + * @return Price */ - void clearStaffs(); + double getPrice(); /** - * Get this container shop is loaded or unloaded. - * @return Loaded + * Set shop's new price + * @param paramDouble New price */ - boolean isLoaded(); + void setPrice(double paramDouble); + + /** + * Get shop remaining space. + * @return Remaining space. + */ + int getRemainingSpace(); + + /** + * Get shop remaining stock. + * @return Remaining stock. + */ + int getRemainingStock(); + + /** + * Get shop type + * @return shop type + */ + ShopType getShopType(); + + /** + * Get shop signs, may have multi signs + * + * @return Signs for the shop + */ + List getSigns(); /** * Directly get all staffs. * @return staffs - */ + */ ArrayList getStaffs(); + /** + * Get shop is or not in buying mode + * + * @return yes or no + */ + boolean isBuying(); + + /** + * Get this container shop is loaded or unloaded. + * + * @return Loaded + */ + boolean isLoaded(); + + /** + * Get shop is or not in selling mode + * + * @return yes or no + */ + boolean isSelling(); + + /** + * Get shop is or not in Unlimited Mode (Admin Shop) + * + * @return yes or not + */ + boolean isUnlimited(); + + /** + * Set shop is or not Unlimited Mode (Admin Shop) + * + * @param paramBoolean status + */ + void setUnlimited(boolean paramBoolean); + + /** + * Shop is valid + * + * @return status + */ + boolean isValid(); + } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java index cab81b705..1b3a440c5 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java @@ -21,12 +21,12 @@ import org.maxgamer.quickshop.Util.Util; * A class allow plugin load shops fast and simply. */ public class ShopLoader { - private QuickShop plugin; - private int errors; final private ArrayList loadTimes = new ArrayList<>(); - private int totalLoaded = 0; + private int errors; private int loadAfterChunkLoaded = 0; private int loadAfterWorldLoaded = 0; + private QuickShop plugin; + private int totalLoaded = 0; /** * The shop load allow plugin load shops fast and simply. @@ -37,9 +37,41 @@ public class ShopLoader { this.plugin = plugin; } - public void loadShops() { - loadShops(null); + private void exceptionHandler(@NotNull Exception ex, @Nullable Location shopLocation) { + errors++; + Logger logger = plugin.getLogger(); + logger.warning("##########FAILED TO LOAD SHOP##########"); + logger.warning(" >> Error Info:"); + logger.warning(ex.getMessage()); + logger.warning(" >> Error Trace"); + ex.printStackTrace(); + logger.warning(" >> Target Location Info"); + logger.warning("Location: " + ((shopLocation == null) ? "NULL" : shopLocation.toString())); + logger.warning("Block: " + ((shopLocation == null) ? "NULL" : shopLocation.getBlock().getType().name())); + logger.warning(" >> Database Info"); + try { + logger.warning("Connected: " + String.valueOf(plugin.getDatabase().getConnection().isClosed())); + } catch (SQLException | NullPointerException e) { + logger.warning("Connected: " + "FALSE - Failed to load status."); + } + + try { + logger.warning("Readonly: " + String.valueOf(plugin.getDatabase().getConnection().isReadOnly())); + } catch (SQLException | NullPointerException e) { + logger.warning("Readonly: " + "FALSE - Failed to load status."); + } + + try { + logger.warning("ClientInfo: " + String.valueOf(plugin.getDatabase().getConnection().getClientInfo().toString())); + } catch (SQLException | NullPointerException e) { + logger.warning("ClientInfo: " + "FALSE - Failed to load status."); + } + + logger.warning("#######################################"); + if (errors > 10) + logger.severe("QuickShop detected too many errors when loading shops, you should backup your shop database and ask the developer for help"); } + /** * Load all shops * @param worldName The world name @@ -105,6 +137,10 @@ public class ShopLoader { } } + public void loadShops() { + loadShops(null); + } + private Long mean(Long[] m) { long sum = 0; for (Long aM : m) { @@ -115,13 +151,6 @@ public class ShopLoader { return sum / m.length; } - private void singleShopLoaded(@NotNull Timer singleShopLoadTimer) { - totalLoaded++; - long singleShopLoadTime = singleShopLoadTimer.endTimer(); - loadTimes.add(singleShopLoadTime); - Util.debugLog("Loaded shop used time " + singleShopLoadTime + "ms"); - } - private boolean shopNullCheck(@Nullable Shop shop) { if (shop == null) { Util.debugLog("Shop Object is null"); @@ -150,85 +179,26 @@ public class ShopLoader { return false; } - private void exceptionHandler(@NotNull Exception ex, @Nullable Location shopLocation) { - errors++; - Logger logger = plugin.getLogger(); - logger.warning("##########FAILED TO LOAD SHOP##########"); - logger.warning(" >> Error Info:"); - logger.warning(ex.getMessage()); - logger.warning(" >> Error Trace"); - ex.printStackTrace(); - logger.warning(" >> Target Location Info"); - logger.warning("Location: " + ((shopLocation == null) ? "NULL" : shopLocation.toString())); - logger.warning("Block: " + ((shopLocation == null) ? "NULL" : shopLocation.getBlock().getType().name())); - logger.warning(" >> Database Info"); - try { - logger.warning("Connected: " + String.valueOf(plugin.getDatabase().getConnection().isClosed())); - } catch (SQLException | NullPointerException e) { - logger.warning("Connected: " + "FALSE - Failed to load status."); - } - - try { - logger.warning("Readonly: " + String.valueOf(plugin.getDatabase().getConnection().isReadOnly())); - } catch (SQLException | NullPointerException e) { - logger.warning("Readonly: " + "FALSE - Failed to load status."); - } - - try { - logger.warning("ClientInfo: " + String.valueOf(plugin.getDatabase().getConnection().getClientInfo().toString())); - } catch (SQLException | NullPointerException e) { - logger.warning("ClientInfo: " + "FALSE - Failed to load status."); - } - - logger.warning("#######################################"); - if (errors > 10) - logger.severe("QuickShop detected too many errors when loading shops, you should backup your shop database and ask the developer for help"); - } - - @Getter - @Setter - class ShopDatabaseInfoOrigin { - private int x; - private int y; - private int z; - private String world; - private String item; - private String moderators; - private double price; - private int type; - private boolean unlimited; - - ShopDatabaseInfoOrigin(ResultSet rs) { - try { - this.x = rs.getInt("x"); - this.y = rs.getInt("y"); - this.z = rs.getInt("z"); - this.world = rs.getString("world"); - this.item = rs.getString("itemConfig"); - this.moderators = rs.getString("owner"); - this.price = rs.getDouble("price"); - this.type = rs.getInt("type"); - this.unlimited = rs.getBoolean("unlimited"); - } catch (SQLException sqlex) { - exceptionHandler(sqlex, null); - } - - } + private void singleShopLoaded(@NotNull Timer singleShopLoadTimer) { + totalLoaded++; + long singleShopLoadTime = singleShopLoadTimer.endTimer(); + loadTimes.add(singleShopLoadTime); + Util.debugLog("Loaded shop used time " + singleShopLoadTime + "ms"); } @Getter @Setter class ShopDatabaseInfo { + private ItemStack item; + private Location location; + private ShopModerator moderators; + private double price; + private ShopType type; + private boolean unlimited; + private World world; private int x; private int y; private int z; - private double price; - private boolean unlimited; - private ShopType type; - private World world; - private ItemStack item; - private ShopModerator moderators; - private Location location; ShopDatabaseInfo(ShopDatabaseInfoOrigin origin) { try { @@ -282,4 +252,35 @@ public class ShopLoader { return shopModerator; } } + + @Getter + @Setter + class ShopDatabaseInfoOrigin { + private String item; + private String moderators; + private double price; + private int type; + private boolean unlimited; + private String world; + private int x; + private int y; + private int z; + + ShopDatabaseInfoOrigin(ResultSet rs) { + try { + this.x = rs.getInt("x"); + this.y = rs.getInt("y"); + this.z = rs.getInt("z"); + this.world = rs.getString("world"); + this.item = rs.getString("itemConfig"); + this.moderators = rs.getString("owner"); + this.price = rs.getDouble("price"); + this.type = rs.getInt("type"); + this.unlimited = rs.getBoolean("unlimited"); + } catch (SQLException sqlex) { + exceptionHandler(sqlex, null); + } + + } + } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java index 518e4ebdb..d349373fb 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java @@ -33,378 +33,15 @@ import org.maxgamer.quickshop.Util.Util; */ @SuppressWarnings("WeakerAccess") public class ShopManager { - private QuickShop plugin; - private HashMap actions = new HashMap(); - private HashMap>> shops = new HashMap<>(); final private static ItemStack AIR = new ItemStack(Material.AIR); + private HashMap actions = new HashMap(); + private QuickShop plugin; + private HashMap>> shops = new HashMap<>(); public ShopManager(@NotNull QuickShop plugin) { this.plugin = plugin; } - /** - * @return Returns the HashMap. Info contains what - * their last question etc was. - */ - public HashMap getActions() { - return this.actions; - } - - /** - * Create a shop use Shop and Info object. - * - * @param shop The shop object - * @param info The info object - */ - public void createShop(@NotNull Shop shop, @NotNull Info info) { - ShopCreateEvent ssShopCreateEvent = new ShopCreateEvent(shop, Bukkit.getPlayer(shop.getOwner())); - Bukkit.getPluginManager().callEvent(ssShopCreateEvent); - if (ssShopCreateEvent.isCancelled()) { - return; - } - Location loc = shop.getLocation(); - ItemStack item = shop.getItem(); - try { - // Write it to the database - plugin.getDatabaseHelper().createShop(plugin.getDatabase(), ShopModerator.serialize(shop.getModerator()), shop - .getPrice(), item, (shop.isUnlimited() ? - 1 : - 0), shop.getShopType().toID(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - // Add it to the world - addShop(loc.getWorld().getName(), shop); - } catch (SQLException error) { - plugin.getLogger().warning("SQLException detected, trying to auto fix the database..."); - boolean backupSuccess = Util.backupDatabase(); - try { - if (backupSuccess) { - plugin.getDatabaseHelper().removeShop(plugin.getDatabase(), loc.getBlockX(), loc.getBlockY(), loc - .getBlockZ(), loc.getWorld().getName()); - } else { - plugin.getLogger().warning("Failed to backup the database, all changes will revert after a reboot."); - } - } catch (SQLException error2) { - //Failed removing - plugin.getLogger().warning("Failed to autofix the database, all changes will revert after a reboot."); - error.printStackTrace(); - error2.printStackTrace(); - } - } - //Create sign - if (info.getSignBlock() != null && plugin.getConfig().getBoolean("shop.auto-sign")) { - if (!Util.isAir(info.getSignBlock().getType())) { - Util.debugLog("Sign cannot placed cause no enough space(Not air block)"); - return; - } - boolean isWaterLogged = false; - if (info.getSignBlock().getType() == Material.WATER) - isWaterLogged = true; - - info.getSignBlock().setType(Util.getSignMaterial()); - BlockState bs = info.getSignBlock().getState(); - if (isWaterLogged) { - if (bs.getBlockData() instanceof Waterlogged) { - Waterlogged waterable = (Waterlogged) bs.getBlockData(); - waterable.setWaterlogged(true); // Looks like sign directly put in water - } - } - if (bs.getBlockData() instanceof WallSign) { - org.bukkit.block.data.type.WallSign signBlockDataType = (org.bukkit.block.data.type.WallSign) bs.getBlockData(); - BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); - if (bf != null) { - signBlockDataType.setFacing(bf); - bs.setBlockData(signBlockDataType); - } - } else { - plugin.getLogger().warning("Sign material " + bs.getType() - .name() + " not a WallSign, make sure you using correct sign material."); - } - bs.update(true); - shop.setSignText(); - } - } - - /** - * 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(@NotNull String world, @NotNull Shop shop) { - this.addShop(world, shop); - } - - /** - * Returns a hashmap of World - Chunk - Shop - * - * @return a hashmap of World - Chunk - Shop - */ - public HashMap>> getShops() { - return this.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(@NotNull String world) { - return this.shops.get(world); - } - - /** - * Returns a hashmap of Shops - * - * @param c The chunk to search. Referencing doesn't matter, only - * coordinates and world are used. - * @return Shops - */ - public HashMap getShops(@NotNull Chunk c) { - // long start = System.nanoTime(); - return getShops(c.getWorld().getName(), c.getX(), c.getZ()); - // long end = System.nanoTime(); - // plugin.getLogger().log(Level.WARNING, "Chunk lookup in " + ((end - start)/1000000.0) + - // "ms."); - } - - public HashMap getShops(String world, int chunkX, int chunkZ) { - HashMap> inWorld = this.getShops(world); - if (inWorld == null) { - return null; - } - ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ); - return inWorld.get(shopChunk); - } - - /** - * 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(@NotNull Location loc) { - 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); - } - - /** - * Adds a shop to the world. Does NOT require the chunk or world to be loaded - * Call shop.onLoad by yourself - * - * @param world The name of the world - * @param shop The shop to add - */ - public void addShop(@NotNull String world, @NotNull Shop shop) { - HashMap> inWorld = this.getShops() - .computeIfAbsent(world, k -> new HashMap<>(3)); - // There's no world storage yet. We need to create that hashmap. - // Put it in the data universe - // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT - // location rounded to the nearest 16. - int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); - int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); - // Get the chunk set from the world info - ShopChunk shopChunk = new ShopChunk(world, x, z); - HashMap inChunk = inWorld.computeIfAbsent(shopChunk, k -> new HashMap<>(1)); - // That chunk data hasn't been created yet - Create it! - // Put it in the world - // Put the shop in its location in the chunk list. - inChunk.put(shop.getLocation(), shop); - // shop.onLoad(); - - } - - /** - * Removes a shop from the world. Does NOT remove it from the database. * - * REQUIRES * the world to be loaded - * Call shop.onUnload by your self. - * - * @param shop The shop to remove - */ - public void removeShop(@NotNull Shop shop) { - // shop.onUnload(); - Location loc = shop.getLocation(); - String world = loc.getWorld().getName(); - HashMap> inWorld = this.getShops().get(world); - int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); - int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); - ShopChunk shopChunk = new ShopChunk(world, x, z); - HashMap inChunk = inWorld.get(shopChunk); - if (inChunk == null) - return; - inChunk.remove(loc); - // shop.onUnload(); - } - - /** - * 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.isDisplay()) { - for (World world : Bukkit.getWorlds()) { - for (Chunk chunk : world.getLoadedChunks()) { - HashMap inChunk = this.getShops(chunk); - if (inChunk == null || inChunk.isEmpty()) - continue; - for (Shop shop : inChunk.values()) { - shop.onUnload(); - } - } - } - } - this.actions.clear(); - this.shops.clear(); - } - - /** - * 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 - * @param bf The blockface to check - * @return True if they're allowed to place a shop there. - */ - public boolean canBuildShop(@NotNull Player p, @NotNull Block b, @NotNull BlockFace bf) { - RegisteredListener openInvRegisteredListener = null; // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139 - // try { - // if (plugin.openInvPlugin != null) { - // for (RegisteredListener listener : PlayerInteractEvent.getHandlerList().getRegisteredListeners()) { - // if (listener.getPlugin().getName().equals(plugin.openInvPlugin.getName())) { - // openInvRegisteredListener = listener; - // PlayerInteractEvent.getHandlerList().unregister(listener); - // break; - // } - // } - // } - try { - plugin.getCompatibilityTool().toggleInteractListeners(false); - - if (plugin.isLimit()) { - int owned = 0; - if (!plugin.getConfig().getBoolean("limits.old-algorithm")) { - for (HashMap> shopmap : getShops().values()) { - for (HashMap shopLocs : shopmap.values()) { - for (Shop shop : shopLocs.values()) { - if (shop.getOwner().equals(p.getUniqueId()) && !shop.isUnlimited()) { - owned++; - } - } - } - } - } else { - Iterator it = getShopIterator(); - while (it.hasNext()) { - if (it.next().getOwner().equals(p.getUniqueId())) { - owned++; - } - } - } - - int max = plugin.getShopLimit(p); - if (owned + 1 > max) { - //p.sendMessage(ChatColor.RED + "You have already created a maximum of " + owned + "/" + max + " shops!"); - p.sendMessage(MsgUtil.getMessage("reached-maximum-can-create", String.valueOf(owned), String.valueOf(max))); - return false; - } - } - if (!plugin.getPermissionChecker().canBuild(p, b, false)) { - Util.debugLog("PermissionChecker canceled shop creation"); - return false; - } - ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation()); - Bukkit.getPluginManager().callEvent(spce); - if (spce.isCancelled()) { - return false; - } - } finally { - // if (plugin.openInvPlugin != null && openInvRegisteredListener != null) { - // PlayerInteractEvent.getHandlerList().register(openInvRegisteredListener); - // } - plugin.getCompatibilityTool().toggleInteractListeners(true); - } - - return true; - } - - public void handleChat(@NotNull Player p, @NotNull String msg) { - handleChat(p, msg, false); - } - - public void handleChat(@NotNull Player p, @NotNull String msg, boolean bypassProtectionChecks) { - final String message = ChatColor.stripColor(msg); - // Use from the main thread, because Bukkit hates life - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { - HashMap actions = getActions(); - // They wanted to do something. - Info info = actions.remove(p.getUniqueId()); - if (info == null) - return; // multithreaded means this can happen - if (info.getLocation().getWorld() != p.getLocation().getWorld()) { - p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); - return; - } - if (info.getLocation().distanceSquared(p.getLocation()) > 25) { - p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); - return; - } - /* Creation handling */ - // if (info.getAction() == ShopAction.CREATE) { - // actionCreate(p, actions, info, message); - // /* Purchase Handling */ - // } else if (info.getAction() == ShopAction.BUY) { - // actionTrade(p, actions, info, message); - // } - switch (info.getAction()) { - case CREATE: - actionCreate(p, actions, info, message, bypassProtectionChecks); - break; - case BUY: - actionTrade(p, actions, info, message); - break; - case CANCELLED: - break; //Go away - } - }); - } - - private void actionTrade(@NotNull Player p, @NotNull HashMap actions, @NotNull Info info, @NotNull String message) { - int amount; - try { - amount = Integer.parseInt(message); - } catch (NumberFormatException e) { - p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); - return; - } - // Get the shop they interacted with - Shop shop = plugin.getShopManager().getShop(info.getLocation()); - // It's not valid anymore - if (shop == null || !Util.canBeShop(info.getLocation().getBlock())) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - return; - } - if (info.hasChanged(shop)) { - p.sendMessage(MsgUtil.getMessage("shop-has-changed")); - return; - } - if (shop.isBuying()) { - actionBuy(p, actions, info, message, shop, amount); - } else if (shop.isSelling()) { - actionSell(p, actions, info, message, shop, amount); - } else { - p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); - plugin.getLogger().warning("Shop data broken? Loc:" + shop.getLocation().toString()); - } - } - @SuppressWarnings("deprecation") private void actionBuy(@NotNull Player p, @NotNull HashMap actions2, @NotNull Info info, @NotNull String message, @NotNull Shop shop, int amount) { if (!Util.canBeShop(info.getLocation().getBlock())) { @@ -494,93 +131,6 @@ public class ShopManager { shop.setSignText(); // Update the signs count } - @SuppressWarnings("deprecation") - private void actionSell(@NotNull Player p, @NotNull HashMap actions2, @NotNull Info info, @NotNull String message, @NotNull Shop shop, int amount) { - if (!Util.canBeShop(info.getLocation().getBlock())) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - return; - } - if (info.hasChanged(shop)) { - p.sendMessage(MsgUtil.getMessage("shop-has-changed")); - return; - } - int stock = shop.getRemainingStock(); - if (stock == -1) - stock = 10000; - if (stock < amount) { - p.sendMessage(MsgUtil - .getMessage("shop-stock-too-low", "" + shop.getRemainingStock(), Util.getItemStackName(shop.getItem()))); - return; - } - if (amount < 1) { - // & Dumber - p.sendMessage(MsgUtil.getMessage("negative-amount")); - return; - } - int pSpace = Util.countSpace(p.getInventory(), shop.getItem()); - if (amount > pSpace) { - p.sendMessage(MsgUtil.getMessage("not-enough-space", String.valueOf(pSpace))); - return; - } - ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) - return; // Cancelled - // Money handling - double tax = plugin.getConfig().getDouble("tax"); - double total = amount * shop.getPrice(); - - if (tax < 0) - tax = 0; //Tax was disabled. - if (shop.getModerator().isModerator(p.getUniqueId())) - tax = 0; //Is staff or owner, so we won't will take them tax - - Economy eco = plugin.getEconomy(); - - boolean successA = eco.withdraw(p.getUniqueId(), total); //Withdraw owner's money - if (!successA) { - p.sendMessage(MsgUtil - .getMessage("you-cant-afford-to-buy", format(total), format(eco.getBalance(p.getUniqueId())))); - return; - } - boolean shouldPayOwner = !shop.isUnlimited() || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") && shop - .isUnlimited()); - if (shouldPayOwner) { - boolean successB = eco.deposit(shop.getOwner(), total * (1 - tax)); - if (!successB) { - plugin.getLogger().warning("Failed to deposit the money for player " + Bukkit.getPlayer(shop.getOwner())); - /* Rollback the trade */ - if (!eco.deposit(p.getUniqueId(), total * (1 - tax))) { - plugin.getLogger().warning("Failed to rollback the purchase actions for player " + Bukkit - .getOfflinePlayer(shop.getOwner()).getName()); - } - p.sendMessage(MsgUtil.getMessage("purchase-failed")); - return; - } - } - - String msg; - // Notify the shop owner - if (plugin.getConfig().getBoolean("show-tax")) { - msg = MsgUtil.getMessage("player-bought-from-your-store-tax", p.getName(), "" + amount, Util - .getItemStackName(shop.getItem()), Util.format((tax * total))); - } else { - msg = MsgUtil.getMessage("player-bought-from-your-store", p.getName(), "" + amount, Util - .getItemStackName(shop.getItem())); - } - // Transfers the item from A to B - if (stock == amount) - msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop - .getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), Util - .getItemStackName(shop.getItem())); - - MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited()); - shop.sell(p, amount); - MsgUtil.sendPurchaseSuccess(p, shop, amount); - ShopSuccessPurchaseEvent se = new ShopSuccessPurchaseEvent(shop, p, amount, total, tax); - Bukkit.getPluginManager().callEvent(se); - } - @SuppressWarnings("deprecation") private void actionCreate(@NotNull Player p, @NotNull HashMap actions2, @NotNull Info info, @NotNull String message, boolean bypassProtectionChecks) { Util.debugLog("actionCreate"); @@ -720,14 +270,312 @@ public class ShopManager { } } + @SuppressWarnings("deprecation") + private void actionSell(@NotNull Player p, @NotNull HashMap actions2, @NotNull Info info, @NotNull String message, @NotNull Shop shop, int amount) { + if (!Util.canBeShop(info.getLocation().getBlock())) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + return; + } + if (info.hasChanged(shop)) { + p.sendMessage(MsgUtil.getMessage("shop-has-changed")); + return; + } + int stock = shop.getRemainingStock(); + if (stock == -1) + stock = 10000; + if (stock < amount) { + p.sendMessage(MsgUtil + .getMessage("shop-stock-too-low", "" + shop.getRemainingStock(), Util.getItemStackName(shop.getItem()))); + return; + } + if (amount < 1) { + // & Dumber + p.sendMessage(MsgUtil.getMessage("negative-amount")); + return; + } + int pSpace = Util.countSpace(p.getInventory(), shop.getItem()); + if (amount > pSpace) { + p.sendMessage(MsgUtil.getMessage("not-enough-space", String.valueOf(pSpace))); + return; + } + ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) + return; // Cancelled + // Money handling + double tax = plugin.getConfig().getDouble("tax"); + double total = amount * shop.getPrice(); + + if (tax < 0) + tax = 0; //Tax was disabled. + if (shop.getModerator().isModerator(p.getUniqueId())) + tax = 0; //Is staff or owner, so we won't will take them tax + + Economy eco = plugin.getEconomy(); + + boolean successA = eco.withdraw(p.getUniqueId(), total); //Withdraw owner's money + if (!successA) { + p.sendMessage(MsgUtil + .getMessage("you-cant-afford-to-buy", format(total), format(eco.getBalance(p.getUniqueId())))); + return; + } + boolean shouldPayOwner = !shop.isUnlimited() || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") && shop + .isUnlimited()); + if (shouldPayOwner) { + boolean successB = eco.deposit(shop.getOwner(), total * (1 - tax)); + if (!successB) { + plugin.getLogger().warning("Failed to deposit the money for player " + Bukkit.getPlayer(shop.getOwner())); + /* Rollback the trade */ + if (!eco.deposit(p.getUniqueId(), total * (1 - tax))) { + plugin.getLogger().warning("Failed to rollback the purchase actions for player " + Bukkit + .getOfflinePlayer(shop.getOwner()).getName()); + } + p.sendMessage(MsgUtil.getMessage("purchase-failed")); + return; + } + } + + String msg; + // Notify the shop owner + if (plugin.getConfig().getBoolean("show-tax")) { + msg = MsgUtil.getMessage("player-bought-from-your-store-tax", p.getName(), "" + amount, Util + .getItemStackName(shop.getItem()), Util.format((tax * total))); + } else { + msg = MsgUtil.getMessage("player-bought-from-your-store", p.getName(), "" + amount, Util + .getItemStackName(shop.getItem())); + } + // Transfers the item from A to B + if (stock == amount) + msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop + .getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), Util + .getItemStackName(shop.getItem())); + + MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited()); + shop.sell(p, amount); + MsgUtil.sendPurchaseSuccess(p, shop, amount); + ShopSuccessPurchaseEvent se = new ShopSuccessPurchaseEvent(shop, p, amount, total, tax); + Bukkit.getPluginManager().callEvent(se); + } + + private void actionTrade(@NotNull Player p, @NotNull HashMap actions, @NotNull Info info, @NotNull String message) { + int amount; + try { + amount = Integer.parseInt(message); + } catch (NumberFormatException e) { + p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); + return; + } + // Get the shop they interacted with + Shop shop = plugin.getShopManager().getShop(info.getLocation()); + // It's not valid anymore + if (shop == null || !Util.canBeShop(info.getLocation().getBlock())) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + return; + } + if (info.hasChanged(shop)) { + p.sendMessage(MsgUtil.getMessage("shop-has-changed")); + return; + } + if (shop.isBuying()) { + actionBuy(p, actions, info, message, shop, amount); + } else if (shop.isSelling()) { + actionSell(p, actions, info, message, shop, amount); + } else { + p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); + plugin.getLogger().warning("Shop data broken? Loc:" + shop.getLocation().toString()); + } + } + /** - * Returns a new shop iterator object, allowing iteration over shops easily, - * instead of sorting through a 3D hashmap. + * Adds a shop to the world. Does NOT require the chunk or world to be loaded + * Call shop.onLoad by yourself * - * @return a new shop iterator object. + * @param world The name of the world + * @param shop The shop to add */ - public Iterator getShopIterator() { - return new ShopIterator(); + public void addShop(@NotNull String world, @NotNull Shop shop) { + HashMap> inWorld = this.getShops() + .computeIfAbsent(world, k -> new HashMap<>(3)); + // There's no world storage yet. We need to create that hashmap. + // Put it in the data universe + // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT + // location rounded to the nearest 16. + int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); + int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); + // Get the chunk set from the world info + ShopChunk shopChunk = new ShopChunk(world, x, z); + HashMap inChunk = inWorld.computeIfAbsent(shopChunk, k -> new HashMap<>(1)); + // That chunk data hasn't been created yet - Create it! + // Put it in the world + // Put the shop in its location in the chunk list. + inChunk.put(shop.getLocation(), shop); + // shop.onLoad(); + + } + + /** + * 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 + * @param bf The blockface to check + * @return True if they're allowed to place a shop there. + */ + public boolean canBuildShop(@NotNull Player p, @NotNull Block b, @NotNull BlockFace bf) { + RegisteredListener openInvRegisteredListener = null; // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139 + // try { + // if (plugin.openInvPlugin != null) { + // for (RegisteredListener listener : PlayerInteractEvent.getHandlerList().getRegisteredListeners()) { + // if (listener.getPlugin().getName().equals(plugin.openInvPlugin.getName())) { + // openInvRegisteredListener = listener; + // PlayerInteractEvent.getHandlerList().unregister(listener); + // break; + // } + // } + // } + try { + plugin.getCompatibilityTool().toggleInteractListeners(false); + + if (plugin.isLimit()) { + int owned = 0; + if (!plugin.getConfig().getBoolean("limits.old-algorithm")) { + for (HashMap> shopmap : getShops().values()) { + for (HashMap shopLocs : shopmap.values()) { + for (Shop shop : shopLocs.values()) { + if (shop.getOwner().equals(p.getUniqueId()) && !shop.isUnlimited()) { + owned++; + } + } + } + } + } else { + Iterator it = getShopIterator(); + while (it.hasNext()) { + if (it.next().getOwner().equals(p.getUniqueId())) { + owned++; + } + } + } + + int max = plugin.getShopLimit(p); + if (owned + 1 > max) { + //p.sendMessage(ChatColor.RED + "You have already created a maximum of " + owned + "/" + max + " shops!"); + p.sendMessage(MsgUtil.getMessage("reached-maximum-can-create", String.valueOf(owned), String.valueOf(max))); + return false; + } + } + if (!plugin.getPermissionChecker().canBuild(p, b, false)) { + Util.debugLog("PermissionChecker canceled shop creation"); + return false; + } + ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation()); + Bukkit.getPluginManager().callEvent(spce); + if (spce.isCancelled()) { + return false; + } + } finally { + // if (plugin.openInvPlugin != null && openInvRegisteredListener != null) { + // PlayerInteractEvent.getHandlerList().register(openInvRegisteredListener); + // } + plugin.getCompatibilityTool().toggleInteractListeners(true); + } + + 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.isDisplay()) { + for (World world : Bukkit.getWorlds()) { + for (Chunk chunk : world.getLoadedChunks()) { + HashMap inChunk = this.getShops(chunk); + if (inChunk == null || inChunk.isEmpty()) + continue; + for (Shop shop : inChunk.values()) { + shop.onUnload(); + } + } + } + } + this.actions.clear(); + this.shops.clear(); + } + + /** + * Create a shop use Shop and Info object. + * + * @param shop The shop object + * @param info The info object + */ + public void createShop(@NotNull Shop shop, @NotNull Info info) { + ShopCreateEvent ssShopCreateEvent = new ShopCreateEvent(shop, Bukkit.getPlayer(shop.getOwner())); + Bukkit.getPluginManager().callEvent(ssShopCreateEvent); + if (ssShopCreateEvent.isCancelled()) { + return; + } + Location loc = shop.getLocation(); + ItemStack item = shop.getItem(); + try { + // Write it to the database + plugin.getDatabaseHelper().createShop(plugin.getDatabase(), ShopModerator.serialize(shop.getModerator()), shop + .getPrice(), item, (shop.isUnlimited() ? + 1 : + 0), shop.getShopType().toID(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + // Add it to the world + addShop(loc.getWorld().getName(), shop); + } catch (SQLException error) { + plugin.getLogger().warning("SQLException detected, trying to auto fix the database..."); + boolean backupSuccess = Util.backupDatabase(); + try { + if (backupSuccess) { + plugin.getDatabaseHelper().removeShop(plugin.getDatabase(), loc.getBlockX(), loc.getBlockY(), loc + .getBlockZ(), loc.getWorld().getName()); + } else { + plugin.getLogger().warning("Failed to backup the database, all changes will revert after a reboot."); + } + } catch (SQLException error2) { + //Failed removing + plugin.getLogger().warning("Failed to autofix the database, all changes will revert after a reboot."); + error.printStackTrace(); + error2.printStackTrace(); + } + } + //Create sign + if (info.getSignBlock() != null && plugin.getConfig().getBoolean("shop.auto-sign")) { + if (!Util.isAir(info.getSignBlock().getType())) { + Util.debugLog("Sign cannot placed cause no enough space(Not air block)"); + return; + } + boolean isWaterLogged = false; + if (info.getSignBlock().getType() == Material.WATER) + isWaterLogged = true; + + info.getSignBlock().setType(Util.getSignMaterial()); + BlockState bs = info.getSignBlock().getState(); + if (isWaterLogged) { + if (bs.getBlockData() instanceof Waterlogged) { + Waterlogged waterable = (Waterlogged) bs.getBlockData(); + waterable.setWaterlogged(true); // Looks like sign directly put in water + } + } + if (bs.getBlockData() instanceof WallSign) { + org.bukkit.block.data.type.WallSign signBlockDataType = (org.bukkit.block.data.type.WallSign) bs.getBlockData(); + BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); + if (bf != null) { + signBlockDataType.setFacing(bf); + bs.setBlockData(signBlockDataType); + } + } else { + plugin.getLogger().warning("Sign material " + bs.getType() + .name() + " not a WallSign, make sure you using correct sign material."); + } + bs.update(true); + shop.setSignText(); + } } /** @@ -740,11 +588,163 @@ public class ShopManager { return plugin.getEconomy().format(d); } + /** + * 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(@NotNull Location loc) { + 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 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(@NotNull String world) { + return this.shops.get(world); + } + + /** + * Returns a hashmap of Shops + * + * @param c The chunk to search. Referencing doesn't matter, only + * coordinates and world are used. + * @return Shops + */ + public HashMap getShops(@NotNull Chunk c) { + // long start = System.nanoTime(); + return getShops(c.getWorld().getName(), c.getX(), c.getZ()); + // long end = System.nanoTime(); + // plugin.getLogger().log(Level.WARNING, "Chunk lookup in " + ((end - start)/1000000.0) + + // "ms."); + } + + public HashMap getShops(String world, int chunkX, int chunkZ) { + HashMap> inWorld = this.getShops(world); + if (inWorld == null) { + return null; + } + ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ); + return inWorld.get(shopChunk); + } + + public void handleChat(@NotNull Player p, @NotNull String msg) { + handleChat(p, msg, false); + } + + public void handleChat(@NotNull Player p, @NotNull String msg, boolean bypassProtectionChecks) { + final String message = ChatColor.stripColor(msg); + // Use from the main thread, because Bukkit hates life + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { + HashMap actions = getActions(); + // They wanted to do something. + Info info = actions.remove(p.getUniqueId()); + if (info == null) + return; // multithreaded means this can happen + if (info.getLocation().getWorld() != p.getLocation().getWorld()) { + p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); + return; + } + if (info.getLocation().distanceSquared(p.getLocation()) > 25) { + p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); + return; + } + /* Creation handling */ + // if (info.getAction() == ShopAction.CREATE) { + // actionCreate(p, actions, info, message); + // /* Purchase Handling */ + // } else if (info.getAction() == ShopAction.BUY) { + // actionTrade(p, actions, info, message); + // } + switch (info.getAction()) { + case CREATE: + actionCreate(p, actions, info, message, bypassProtectionChecks); + break; + case BUY: + actionTrade(p, actions, info, message); + break; + case CANCELLED: + break; //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(@NotNull String world, @NotNull 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 + * Call shop.onUnload by your self. + * + * @param shop The shop to remove + */ + public void removeShop(@NotNull Shop shop) { + // shop.onUnload(); + Location loc = shop.getLocation(); + String world = loc.getWorld().getName(); + HashMap> inWorld = this.getShops().get(world); + int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); + int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); + ShopChunk shopChunk = new ShopChunk(world, x, z); + HashMap inChunk = inWorld.get(shopChunk); + if (inChunk == null) + return; + inChunk.remove(loc); + // shop.onUnload(); + } + + /** + * @return Returns the HashMap. Info contains what + * their last question etc was. + */ + public HashMap getActions() { + return this.actions; + } + + /** + * 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; + } + public class ShopIterator implements Iterator { - private Iterator shops; private Iterator> chunks; - private Iterator>> worlds; private Shop current; + private Iterator shops; + private Iterator>> worlds; public ShopIterator() { worlds = getShops().values().iterator(); diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java index 0be5b1c6f..e1991afa2 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java @@ -12,6 +12,16 @@ import org.jetbrains.annotations.*; */ @EqualsAndHashCode public class ShopModerator { + public static ShopModerator deserialize(@NotNull String serilized) { + //Use Gson deserialize data + Gson gson = new Gson(); + return gson.fromJson(serilized, ShopModerator.class); + } + + public static String serialize(@NotNull ShopModerator shopModerator) { + Gson gson = new Gson(); + return gson.toJson(shopModerator); //Use Gson serialize this class + } private UUID owner; private ArrayList staffs; @@ -40,34 +50,6 @@ public class ShopModerator { this.staffs = new ArrayList(); } - public ShopModerator clone() { - return new ShopModerator(this); - } - - /** - * Get moderators owner (Shop Owner). - * @return Owner's UUID - */ - public UUID getOwner() { - return owner; - } - - /** - * Set moderators owner (Shop Owner) - * @param player Owner's UUID - */ - public void setOwner(@NotNull UUID player) { - this.owner = player; - } - - /** - * Set moderators staffs - * @param players staffs list - */ - public void setStaffs(@NotNull ArrayList players) { - this.staffs = players; - } - /** * Add moderators staff to staff list * @param player New staff @@ -80,6 +62,22 @@ public class ShopModerator { return true; } + /** + * Remove all staffs + */ + public void clearStaffs() { + staffs.clear(); + } + + public ShopModerator clone() { + return new ShopModerator(this); + } + + @Override + public String toString() { + return serialize(this); + } + /** * Remove moderators staff from staff list * @param player Staff @@ -90,18 +88,14 @@ public class ShopModerator { } /** - * Remove all staffs + * Get a player is or not moderators + * @param player Player + * @return yes or no, return true when it is staff or owner */ - public void clearStaffs() { - staffs.clear(); - } - - /** - * Get staffs list - * @return Staffs - */ - public ArrayList getStaffs() { - return staffs; + public boolean isModerator(@NotNull UUID player) { + if (isOwner(player)) + return true; + return isStaff(player); } /** @@ -123,29 +117,37 @@ public class ShopModerator { } /** - * Get a player is or not moderators - * @param player Player - * @return yes or no, return true when it is staff or owner + * Get moderators owner (Shop Owner). + * @return Owner's UUID */ - public boolean isModerator(@NotNull UUID player) { - if (isOwner(player)) - return true; - return isStaff(player); + public UUID getOwner() { + return owner; } - public static String serialize(@NotNull ShopModerator shopModerator) { - Gson gson = new Gson(); - return gson.toJson(shopModerator); //Use Gson serialize this class + /** + * Set moderators owner (Shop Owner) + * + * @param player Owner's UUID + */ + public void setOwner(@NotNull UUID player) { + this.owner = player; } - public static ShopModerator deserialize(@NotNull String serilized) { - //Use Gson deserialize data - Gson gson = new Gson(); - return gson.fromJson(serilized, ShopModerator.class); + /** + * Get staffs list + * + * @return Staffs + */ + public ArrayList getStaffs() { + return staffs; } - @Override - public String toString() { - return serialize(this); + /** + * Set moderators staffs + * + * @param players staffs list + */ + public void setStaffs(@NotNull ArrayList players) { + this.staffs = players; } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopProtectionFlag.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopProtectionFlag.java index c02e0a814..a2920625e 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopProtectionFlag.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopProtectionFlag.java @@ -7,9 +7,9 @@ import lombok.*; @EqualsAndHashCode @ToString public class ShopProtectionFlag { - private String shopLocation; private String itemStackString; private String mark = "QuickShop DisplayItem"; + private String shopLocation; public ShopProtectionFlag(String shopLocation, String itemStackString) { this.shopLocation = shopLocation; diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java index b19c38615..24e2f7a28 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java @@ -4,12 +4,6 @@ import org.jetbrains.annotations.*; public enum ShopType { SELLING(0), BUYING(1); - private int id; - - ShopType(int id) { - this.id = id; - } - public static ShopType fromID(int id) { for (ShopType type : ShopType.values()) { if (type.id == id) { @@ -23,6 +17,12 @@ public enum ShopType { return shopType.id; } + private int id; + + ShopType(int id) { + this.id = id; + } + public int toID() { return id; } diff --git a/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java b/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java index 0c4b307a0..ab612fd9b 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java @@ -16,9 +16,26 @@ import org.jetbrains.annotations.*; A utils for print sheet on chat. */ public class ChatSheetPrinter { + final ChatColor chatColor = ChatColor.DARK_PURPLE; //StringBuffer buffer = new StringBuffer(); private CommandSender p; - final ChatColor chatColor = ChatColor.DARK_PURPLE; + + public void printCenterLine(@NotNull String text) { + p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_half_line") + text + MsgUtil + .getMessage("tableformat.right_half_line")); + } + + public void printExecuteableCmdLine(@NotNull String text, @NotNull String hoverText, @NotNull String executeCmd) { + TextComponent message = new TextComponent(chatColor + MsgUtil.getMessage("tableformat.left_begin") + text); + message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, executeCmd)); + message.setHoverEvent( + new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hoverText).create())); + p.spigot().sendMessage(message); + } + + public void printFooter() { + p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.full_line")); + } public void printHeader() { p.sendMessage(""); @@ -30,23 +47,6 @@ public class ChatSheetPrinter { p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_begin") + " " + text); } - public void printCenterLine(@NotNull String text) { - p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_half_line") + text + MsgUtil - .getMessage("tableformat.right_half_line")); - } - - public void printFooter() { - p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.full_line")); - } - - public void printExecuteableCmdLine(@NotNull String text, @NotNull String hoverText, @NotNull String executeCmd) { - TextComponent message = new TextComponent(chatColor + MsgUtil.getMessage("tableformat.left_begin") + text); - message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, executeCmd)); - message.setHoverEvent( - new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hoverText).create())); - p.spigot().sendMessage(message); - } - public void printSuggestableCmdLine(@NotNull String text, @NotNull String hoverText, @NotNull String suggestCmd) { TextComponent message = new TextComponent(chatColor + MsgUtil.getMessage("tableformat.left_begin") + text); message.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, suggestCmd)); diff --git a/src/main/java/org/maxgamer/quickshop/Util/Compatibility.java b/src/main/java/org/maxgamer/quickshop/Util/Compatibility.java index 93272be99..339a6ed30 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Compatibility.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Compatibility.java @@ -10,8 +10,9 @@ import org.maxgamer.quickshop.QuickShop; * WIP */ public class Compatibility { - private QuickShop plugin; + private final ArrayList disabledListeners = new ArrayList<>(); final private ArrayList knownIncompatiablePlugin = new ArrayList<>(); + private QuickShop plugin; public Compatibility(@NotNull QuickShop plugin) { this.plugin = plugin; @@ -19,8 +20,6 @@ public class Compatibility { knownIncompatiablePlugin.add("LWC"); } - private final ArrayList disabledListeners = new ArrayList<>(); - /** * Switch the compatibility mode on or off, set false to disable all we known incompatiable plugin listener, * set true to enable back all disabled plugin liseners. diff --git a/src/main/java/org/maxgamer/quickshop/Util/IncompatibleChecker.java b/src/main/java/org/maxgamer/quickshop/Util/IncompatibleChecker.java index 747dc36e7..8501f8ad9 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/IncompatibleChecker.java +++ b/src/main/java/org/maxgamer/quickshop/Util/IncompatibleChecker.java @@ -27,6 +27,22 @@ public class IncompatibleChecker { return incompatibleVersionList.contains(version); } + private void mc1_10() { + incompatibleVersionList.add("v1_10_R1"); + } + + private void mc1_11() { + incompatibleVersionList.add("v1_11_R1"); + } + + private void mc1_12() { + incompatibleVersionList.add("v1_12_R1"); + } + + private void mc1_13() { + incompatibleVersionList.add("v1_13_R1"); //1.13.0-1.13.1 no Tag feature. + } + private void mc1_5() { incompatibleVersionList.add("v1_5_R1"); incompatibleVersionList.add("v1_5_R2"); @@ -56,20 +72,4 @@ public class IncompatibleChecker { incompatibleVersionList.add("v1_9_R1"); incompatibleVersionList.add("v1_9_R2"); } - - private void mc1_10() { - incompatibleVersionList.add("v1_10_R1"); - } - - private void mc1_11() { - incompatibleVersionList.add("v1_11_R1"); - } - - private void mc1_12() { - incompatibleVersionList.add("v1_12_R1"); - } - - private void mc1_13() { - incompatibleVersionList.add("v1_13_R1"); //1.13.0-1.13.1 no Tag feature. - } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/ItemMatcher.java b/src/main/java/org/maxgamer/quickshop/Util/ItemMatcher.java index ffa0b7391..15303cea2 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ItemMatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ItemMatcher.java @@ -17,8 +17,8 @@ import org.maxgamer.quickshop.QuickShop; * A util allow quickshop check item matches easy and quick. */ public class ItemMatcher { - private QuickShop plugin; private ItemMetaMatcher itemMetaMatcher; + private QuickShop plugin; public ItemMatcher(QuickShop plugin) { this.plugin = plugin; @@ -63,14 +63,14 @@ public class ItemMatcher { } class ItemMetaMatcher { + private boolean attributes; + private boolean custommodeldata; private boolean damage; private boolean displayname; - private boolean lores; private boolean enchs; - private boolean potions; - private boolean attributes; private boolean itemflags; - private boolean custommodeldata; + private boolean lores; + private boolean potions; public ItemMetaMatcher(ConfigurationSection itemMatcherConfig) { this.damage = itemMatcherConfig.getBoolean("damage"); @@ -83,6 +83,108 @@ public class ItemMatcher { this.custommodeldata = itemMatcherConfig.getBoolean("custommodeldata"); } + private boolean attributeModifiersMatches(ItemMeta meta1, ItemMeta meta2) { + if (!this.attributes) + return true; + if (meta1.hasAttributeModifiers() != meta2.hasAttributeModifiers()) + return false; + + if (!meta1.hasAttributeModifiers()) + return true; //No attributeModifiers need to be checked. + + return (meta1.getAttributeModifiers().hashCode() == meta2.getAttributeModifiers().hashCode()); + } + + private boolean customModelDataMatches(ItemMeta meta1, ItemMeta meta2) { + if (!this.custommodeldata) + return true; + if (meta1.hasCustomModelData() != meta2.hasCustomModelData()) + return false; + if (!meta1.hasCustomModelData()) + return true; //No customModelData needs to be checked. + return (meta1.getCustomModelData() == meta2.getCustomModelData()); + } + + private boolean damageMatches(ItemMeta meta1, ItemMeta meta2) { + if (!this.damage) + return true; + if ((meta1 instanceof Damageable) != (meta2 instanceof Damageable)) + return false; + + if (!(meta1 instanceof Damageable)) + return true; //No damage need to check. + + Damageable damage1 = (Damageable) meta1; + Damageable damage2 = (Damageable) meta2; + + if (damage1.hasDamage() != damage2.hasDamage()) + return false; + + if (!damage1.hasDamage()) + return true; //No damage need to check. + + return damage1.getDamage() == damage2.getDamage(); + + } + + private boolean displayMatches(ItemMeta meta1, ItemMeta meta2) { + if (!this.displayname) + return true; + if (meta1.hasDisplayName() != meta2.hasDisplayName()) + return false; + if (!meta1.hasDisplayName()) + return true; //Passed check. no display need to check + return (meta1.getDisplayName().equals(meta2.getDisplayName())); + } + + private boolean enchMatches(ItemMeta meta1, ItemMeta meta2) { + if (!this.enchs) + return true; + if (meta1.hasEnchants() != meta2.hasEnchants()) + return false; + + if (meta1.hasEnchants()) { + Map enchMap1 = meta1.getEnchants(); + Map enchMap2 = meta2.getEnchants(); + if (!Util.mapDuoMatches(enchMap1, enchMap2)) + return false; + } + if (meta1 instanceof EnchantmentStorageMeta != meta2 instanceof EnchantmentStorageMeta) + return false; + if (meta1 instanceof EnchantmentStorageMeta) { + Map stor1 = ((EnchantmentStorageMeta) meta1).getStoredEnchants(); + Map stor2 = ((EnchantmentStorageMeta) meta2).getStoredEnchants(); + return Util.mapDuoMatches(stor1, stor2); + } + return true; + } + + private boolean itemFlagsMatches(ItemMeta meta1, ItemMeta meta2) { + if (!this.itemflags) + return true; + return (meta1.getItemFlags().hashCode() == meta2.getItemFlags().hashCode()); + } + + private boolean loresMatches(ItemMeta meta1, ItemMeta meta2) { + Util.debugLog("Lores checker"); + if (!this.lores) + return true; + Util.debugLog("Lores checking"); + if (meta1.hasLore() != meta2.hasLore()) + return false; + if (!meta1.hasLore()) + return true; // No lores need to be checked. + List lores1 = meta1.getLore(); + List lores2 = meta2.getLore(); + if (lores1.size() != lores2.size()) + return false; + for (int i = 0; i < lores1.size(); i++) { + if (!lores1.get(i).equals(lores2.get(i))) + return false; + } + return (lores2.hashCode() == lores2.hashCode()); + } + boolean matches(ItemStack stack1, ItemStack stack2) { Util.debugLog("Begin the item matches checking..."); if (stack1.hasItemMeta() != stack2.hasItemMeta()) @@ -121,84 +223,6 @@ public class ItemMatcher { return true; } - private boolean rootMatches(ItemMeta meta1, ItemMeta meta2) { - return (meta1.hashCode() == meta2.hashCode()); - } - - private boolean damageMatches(ItemMeta meta1, ItemMeta meta2) { - if (!this.damage) - return true; - if ((meta1 instanceof Damageable) != (meta2 instanceof Damageable)) - return false; - - if (!(meta1 instanceof Damageable)) - return true; //No damage need to check. - - Damageable damage1 = (Damageable) meta1; - Damageable damage2 = (Damageable) meta2; - - if (damage1.hasDamage() != damage2.hasDamage()) - return false; - - if (!damage1.hasDamage()) - return true; //No damage need to check. - - return damage1.getDamage() == damage2.getDamage(); - - } - - private boolean displayMatches(ItemMeta meta1, ItemMeta meta2) { - if (!this.displayname) - return true; - if (meta1.hasDisplayName() != meta2.hasDisplayName()) - return false; - if (!meta1.hasDisplayName()) - return true; //Passed check. no display need to check - return (meta1.getDisplayName().equals(meta2.getDisplayName())); - } - - private boolean loresMatches(ItemMeta meta1, ItemMeta meta2) { - Util.debugLog("Lores checker"); - if (!this.lores) - return true; - Util.debugLog("Lores checking"); - if (meta1.hasLore() != meta2.hasLore()) - return false; - if (!meta1.hasLore()) - return true; // No lores need to be checked. - List lores1 = meta1.getLore(); - List lores2 = meta2.getLore(); - if (lores1.size() != lores2.size()) - return false; - for (int i = 0; i < lores1.size(); i++) { - if (!lores1.get(i).equals(lores2.get(i))) - return false; - } - return (lores2.hashCode() == lores2.hashCode()); - } - - private boolean enchMatches(ItemMeta meta1, ItemMeta meta2) { - if (!this.enchs) - return true; - if (meta1.hasEnchants() != meta2.hasEnchants()) - return false; - - if (meta1.hasEnchants()) { - Map enchMap1 = meta1.getEnchants(); - Map enchMap2 = meta2.getEnchants(); - if (!Util.mapDuoMatches(enchMap1, enchMap2)) - return false; - } - if (meta1 instanceof EnchantmentStorageMeta != meta2 instanceof EnchantmentStorageMeta) - return false; - if (meta1 instanceof EnchantmentStorageMeta) { - Map stor1 = ((EnchantmentStorageMeta) meta1).getStoredEnchants(); - Map stor2 = ((EnchantmentStorageMeta) meta2).getStoredEnchants(); - return Util.mapDuoMatches(stor1, stor2); - } - return true; - } - private boolean potionMatches(ItemMeta meta1, ItemMeta meta2) { if (!this.potions) return true; @@ -231,32 +255,8 @@ public class ItemMatcher { return true; } - private boolean attributeModifiersMatches(ItemMeta meta1, ItemMeta meta2) { - if (!this.attributes) - return true; - if (meta1.hasAttributeModifiers() != meta2.hasAttributeModifiers()) - return false; - - if (!meta1.hasAttributeModifiers()) - return true; //No attributeModifiers need to be checked. - - return (meta1.getAttributeModifiers().hashCode() == meta2.getAttributeModifiers().hashCode()); - } - - private boolean itemFlagsMatches(ItemMeta meta1, ItemMeta meta2) { - if (!this.itemflags) - return true; - return (meta1.getItemFlags().hashCode() == meta2.getItemFlags().hashCode()); - } - - private boolean customModelDataMatches(ItemMeta meta1, ItemMeta meta2) { - if (!this.custommodeldata) - return true; - if (meta1.hasCustomModelData() != meta2.hasCustomModelData()) - return false; - if (!meta1.hasCustomModelData()) - return true; //No customModelData needs to be checked. - return (meta1.getCustomModelData() == meta2.getCustomModelData()); + private boolean rootMatches(ItemMeta meta1, ItemMeta meta2) { + return (meta1.hashCode() == meta2.hashCode()); } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/ItemNMS.java b/src/main/java/org/maxgamer/quickshop/Util/ItemNMS.java index 8b510d48c..c2def9927 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ItemNMS.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ItemNMS.java @@ -1,54 +1,54 @@ -package org.maxgamer.quickshop.Util; - -import java.lang.reflect.Method; - -import lombok.*; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.*; -import org.maxgamer.quickshop.QuickShop; - -@Getter -public abstract class ItemNMS { - private static Method craftItemStack_asNMSCopyMethod; - private static Class nbtTagCompoundClass; - private static Method itemStack_saveMethod; - - static { - String name = Bukkit.getServer().getClass().getPackage().getName(); - String nmsVersion = name.substring(name.lastIndexOf('.') + 1); - - try { - craftItemStack_asNMSCopyMethod = Class.forName("org.bukkit.craftbukkit." + nmsVersion + ".inventory.CraftItemStack") - .getDeclaredMethod("asNMSCopy", ItemStack.class); - - nbtTagCompoundClass = Class.forName("net.minecraft.server." + nmsVersion + ".NBTTagCompound"); - - itemStack_saveMethod = Class.forName("net.minecraft.server." + nmsVersion + ".ItemStack") - .getDeclaredMethod("save", nbtTagCompoundClass); - - } catch (Throwable t) { - QuickShop.instance.getLogger().info("A error happend:"); - t.printStackTrace(); - QuickShop.instance.getLogger().info("Try to update QSRR and leave feedback about the bug on issue tracker if it continues."); - } - } - - /** - * Save ItemStack to Json passthrough the NMS. - * - * @param bStack ItemStack - * @return The json for ItemStack. - * @throws Throwable throws - */ - public static String saveJsonfromNMS(@NotNull ItemStack bStack) throws Throwable { - if (bStack.getType() == Material.AIR) - return null; - Object mcStack = craftItemStack_asNMSCopyMethod.invoke(null, bStack); - Object nbtTagCompound = nbtTagCompoundClass.newInstance(); - - itemStack_saveMethod.invoke(mcStack, nbtTagCompound); - return nbtTagCompound.toString(); - } -} +package org.maxgamer.quickshop.Util; + +import java.lang.reflect.Method; + +import lombok.*; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.*; +import org.maxgamer.quickshop.QuickShop; + +@Getter +public abstract class ItemNMS { + private static Method craftItemStack_asNMSCopyMethod; + private static Method itemStack_saveMethod; + private static Class nbtTagCompoundClass; + + static { + String name = Bukkit.getServer().getClass().getPackage().getName(); + String nmsVersion = name.substring(name.lastIndexOf('.') + 1); + + try { + craftItemStack_asNMSCopyMethod = Class.forName("org.bukkit.craftbukkit." + nmsVersion + ".inventory.CraftItemStack") + .getDeclaredMethod("asNMSCopy", ItemStack.class); + + nbtTagCompoundClass = Class.forName("net.minecraft.server." + nmsVersion + ".NBTTagCompound"); + + itemStack_saveMethod = Class.forName("net.minecraft.server." + nmsVersion + ".ItemStack") + .getDeclaredMethod("save", nbtTagCompoundClass); + + } catch (Throwable t) { + QuickShop.instance.getLogger().info("A error happend:"); + t.printStackTrace(); + QuickShop.instance.getLogger().info("Try to update QSRR and leave feedback about the bug on issue tracker if it continues."); + } + } + + /** + * Save ItemStack to Json passthrough the NMS. + * + * @param bStack ItemStack + * @return The json for ItemStack. + * @throws Throwable throws + */ + public static String saveJsonfromNMS(@NotNull ItemStack bStack) throws Throwable { + if (bStack.getType() == Material.AIR) + return null; + Object mcStack = craftItemStack_asNMSCopyMethod.invoke(null, bStack); + Object nbtTagCompound = nbtTagCompoundClass.newInstance(); + + itemStack_saveMethod.invoke(mcStack, nbtTagCompound); + return nbtTagCompound.toString(); + } +} diff --git a/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java b/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java index 5151ce1f9..06cc37a43 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java +++ b/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java @@ -32,18 +32,145 @@ import org.maxgamer.quickshop.Shop.Shop; @SuppressWarnings("WeakerAccess") public class MsgUtil { - private static QuickShop plugin = QuickShop.instance; - private static YamlConfiguration itemi18n; - private static YamlConfiguration enchi18n; - private static YamlConfiguration potioni18n; - private static HashMap> player_messages = new HashMap<>(); - private static boolean inited; - private static YamlConfiguration messagei18n; - private static File messageFile; public static String invaildMsg = "Invaild message"; + private static YamlConfiguration enchi18n; + private static boolean inited; + private static YamlConfiguration itemi18n; + private static File messageFile; + private static YamlConfiguration messagei18n; + private static HashMap> player_messages = new HashMap<>(); + private static QuickShop plugin = QuickShop.instance; + private static YamlConfiguration potioni18n; - public static YamlConfiguration getI18nYaml() { - return messagei18n; + /** + * Translate boolean value to String, the symbon is changeable by language file. + * + * @param bool The boolean value + * @return The result of translate. + */ + public static String bool2String(boolean bool) { + if (bool) { + return MsgUtil.getMessage("booleanformat.success"); + } else { + return MsgUtil.getMessage("booleanformat.failed"); + } + } + + /** + * Deletes any messages that are older than a week in the database, to save + * on space. + */ + public static void clean() { + plugin.getLogger().info("Cleaning purchase messages from the database that are over a week old..."); + // 604800,000 msec = 1 week. + long weekAgo = System.currentTimeMillis() - 604800000; + plugin.getDatabaseHelper().cleanMessage(plugin.getDatabase(), weekAgo); + } + + /** + * Replace args in raw to args + * + * @param raw text + * @param args args + * @return filled text + */ + public static String fillArgs(@Nullable String raw, @Nullable String... args) { + if (raw == null) + return "Invalid message: null"; + if (raw.isEmpty()) + return ""; + if (args == null) + return raw; + for (int i = 0; i < args.length; i++) + raw = StringUtils.replace(raw, "{" + i + "}", args[i] == null ? "" : args[i]); + return raw; + } + + /** + * 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(@NotNull OfflinePlayer p) { + if (p.isOnline()) { + UUID pName = p.getUniqueId(); + LinkedList msgs = player_messages.get(pName); + if (msgs != null) { + for (String msg : msgs) { + if (p.getPlayer() != null) + p.getPlayer().sendMessage(msg); + } + plugin.getDatabaseHelper().cleanMessageForPlayer(plugin.getDatabase(), pName); + msgs.clear(); + } + return true; + } + return false; + } + + /** + * Get Enchantment's i18n name. + * + * @param key The Enchantment. + * @return Enchantment's i18n name. + */ + public static String getEnchi18n(@NotNull Enchantment key) { + String enchString = key.getKey().getKey(); + if (enchString.isEmpty()) + return "Enchantment key is empty"; + String enchI18n = enchi18n.getString("enchi18n." + enchString); + if (enchI18n != null && !enchI18n.isEmpty()) + return enchI18n; + return Util.prettifyText(enchString); + } + + /** + * Get item's i18n name + * + * @param itemBukkitName ItemBukkitName(e.g. Material.STONE.name()) + * @return String Item's i18n name. + */ + public static String getItemi18n(@NotNull String itemBukkitName) { + if (itemBukkitName.isEmpty()) + return "Item is empty"; + String itemnameI18n = itemi18n.getString("itemi18n." + itemBukkitName); + if (itemnameI18n != null && !itemnameI18n.isEmpty()) + return itemnameI18n; + Material material = Material.matchMaterial(itemBukkitName); + if (material == null) + return "Material not exist"; + return Util.prettifyText(material.name()); + } + + /** + * getMessage in messages.yml + * + * @param loc location + * @param args args + * @return message + */ + public static String getMessage(@NotNull String loc, @NotNull String... args) { + String raw = messagei18n.getString(loc); + if (raw == null) + return invaildMsg + ": " + loc; + return fillArgs(raw, args); + } + + /** + * Get potion effect's i18n name. + * + * @param potion potionType + * @return Potion's i18n name. + */ + public static String getPotioni18n(@NotNull PotionEffectType potion) { + String potionString = potion.getName().trim(); + if (potionString.isEmpty()) + return "Potion name is empty."; + String potionI18n = potioni18n.getString("potioni18n." + potionString); + if (potionI18n != null && !potionI18n.isEmpty()) + return potionI18n; + return Util.prettifyText(potionString); } public static void loadCfgMessages(@NotNull String... reload) { @@ -88,6 +215,480 @@ public class MsgUtil { } } + public static void loadEnchi18n() { + plugin.getLogger().info("Starting loading Enchantment i18n..."); + File enchi18nFile = new File(plugin.getDataFolder(), "enchi18n.yml"); + if (!enchi18nFile.exists()) { + plugin.getLogger().info("Creating enchi18n.yml"); + plugin.saveResource("enchi18n.yml", true); + } + // Store it + enchi18n = YamlConfiguration.loadConfiguration(enchi18nFile); + enchi18n.options().copyDefaults(true); + YamlConfiguration enchi18nYAML = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin. + getResource("enchi18n.yml"))); + enchi18n.setDefaults(enchi18nYAML); + Util.parseColours(enchi18n); + Enchantment[] enchsi18n = Enchantment.values(); + for (Enchantment ench : enchsi18n) { + String enchi18nString = enchi18n.getString("enchi18n." + ench.getKey().getKey().toString().trim()); + if (enchi18nString != null && !enchi18nString.isEmpty()) + continue; + String enchName = ench.getKey().getKey(); + enchi18n.set("enchi18n." + enchName, Util.prettifyText(enchName)); + plugin.getLogger().info("Found new ench [" + Util.prettifyText(enchName) + "] , adding it to the config..."); + } + try { + enchi18n.save(enchi18nFile); + } catch (IOException e) { + e.printStackTrace(); + plugin.getLogger().log(Level.WARNING, "Could not load/save transaction enchname from enchi18n.yml. Skipping."); + } + plugin.getLogger().info("Complete to load enchname i18n."); + } + + /** + * Load Itemi18n fron file + */ + public static void loadItemi18n() { + File itemi18nFile = new File(plugin.getDataFolder(), "itemi18n.yml"); + if (!itemi18nFile.exists()) { + plugin.getLogger().info("Creating itemi18n.yml"); + plugin.saveResource("itemi18n.yml", true); + } + // Store it + itemi18n = YamlConfiguration.loadConfiguration(itemi18nFile); + itemi18n.options().copyDefaults(true); + YamlConfiguration itemi18nYAML = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin + .getResource("itemi18n.yml"))); + itemi18n.setDefaults(itemi18nYAML); + Util.parseColours(itemi18n); + Material[] itemsi18n = Material.values(); + for (Material material : itemsi18n) { + String itemi18nString = itemi18n.getString("itemi18n." + material.name()); + if (itemi18nString != null && !itemi18nString.isEmpty()) + continue; + String itemName = material.name(); + String lastItemName = Util.prettifyText(itemName); + String localizedName = Util.getLocalizedName(new ItemStack(material)); + /* If have localizedName, use localizedName, not our processed name */ + if (localizedName != null) + lastItemName = localizedName; + itemi18n.set("itemi18n." + itemName, lastItemName); + plugin.getLogger().info("Found new items/blocks [" + Util + .prettifyText(lastItemName) + "] , adding it to the config..."); + } + try { + itemi18n.save(itemi18nFile); + } catch (IOException e) { + e.printStackTrace(); + plugin.getLogger().log(Level.WARNING, "Could not load/save transaction itemname from itemi18n.yml. Skipping."); + } + plugin.getLogger().info("Complete to load Itemname i18n."); + } + + public static void loadPotioni18n() { + plugin.getLogger().info("Starting loading Potion i18n..."); + File potioni18nFile = new File(plugin.getDataFolder(), "potioni18n.yml"); + if (!potioni18nFile.exists()) { + plugin.getLogger().info("Creating potioni18n.yml"); + plugin.saveResource("potioni18n.yml", true); + } + // Store it + potioni18n = YamlConfiguration.loadConfiguration(potioni18nFile); + potioni18n.options().copyDefaults(true); + YamlConfiguration potioni18nYAML = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin + .getResource("potioni18n.yml"))); + potioni18n.setDefaults(potioni18nYAML); + Util.parseColours(potioni18n); + PotionEffectType[] potionsi18n = PotionEffectType.values(); + for (PotionEffectType potion : potionsi18n) { + if (potion != null) { + String potionI18n = potioni18n.getString("potioni18n." + potion.getName().trim()); + if (potionI18n != null && !potionI18n.isEmpty()) + continue; + String potionName = potion.getName(); + plugin.getLogger().info("Found new potion [" + Util.prettifyText(potionName) + "] , adding it to the config..."); + potioni18n.set("potioni18n." + potionName, Util.prettifyText(potionName)); + } + } + try { + potioni18n.save(potioni18nFile); + } catch (IOException e) { + e.printStackTrace(); + plugin.getLogger().log(Level.WARNING, "Could not load/save transaction potionname from potioni18n.yml. Skipping."); + } + plugin.getLogger().info("Complete to load potionname i18n."); + } + + /** + * loads all player purchase messages from the database. + */ + public static void loadTransactionMessages() { + player_messages.clear(); // Delete old messages + try { + ResultSet rs = plugin.getDatabaseHelper().selectAllMessages(plugin.getDatabase()); + while (rs.next()) { + UUID owner = UUID.fromString(rs.getString("owner")); + String message = rs.getString("message"); + LinkedList msgs = player_messages.computeIfAbsent(owner, k -> new LinkedList<>()); + msgs.add(message); + } + } catch (SQLException e) { + e.printStackTrace(); + plugin.getLogger().log(Level.WARNING, "Could not load transaction messages from database. Skipping."); + } + } + + /** + * @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. + * @param isUnlimited The shop is or unlimited + */ + public static void send(@NotNull UUID player, @NotNull String message, boolean isUnlimited) { + if (plugin.getConfig().getBoolean("shop.ignore-unlimited-shop-messages") && isUnlimited) + return; //Ignore unlimited shops messages. + OfflinePlayer p = Bukkit.getOfflinePlayer(player); + if (!p.isOnline()) { + LinkedList msgs = player_messages.get(player); + // msgs = new LinkedList(); + if (msgs == null) + msgs = new LinkedList<>(); + player_messages.put(player, msgs); + msgs.add(message); + plugin.getDatabaseHelper().sendMessage(plugin.getDatabase(), player, message, System.currentTimeMillis()); + } else { + if (p.getPlayer() != null) + p.getPlayer().sendMessage(message); + } + } + + /** + * Send controlPanel infomation to sender + * + * @param sender Target sender + * @param shop Target shop + */ + public static void sendControlPanelInfo(@NotNull CommandSender sender, @NotNull Shop shop) { + if (!sender.hasPermission("quickshop.use")) { + return; + } + + if (plugin.getConfig().getBoolean("sneak-to-control")) + if (sender instanceof Player) + if (!((Player) sender).isSneaking()) + return; + ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(sender); + chatSheetPrinter.printHeader(); + chatSheetPrinter.printLine(MsgUtil.getMessage("controlpanel.infomation")); + // Owner + if (!sender.hasPermission("quickshop.setowner")) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.owner", shop.ownerName())); + } else { + chatSheetPrinter.printSuggestableCmdLine(MsgUtil.getMessage("controlpanel.setowner", shop.ownerName()), MsgUtil + .getMessage("controlpanel.setowner-hover"), MsgUtil.getMessage("controlpanel.commands.setowner")); + } + + // Unlimited + if (sender.hasPermission("quickshop.unlimited")) { + String text = MsgUtil.getMessage("controlpanel.unlimited", bool2String(shop.isUnlimited())); + String hoverText = MsgUtil.getMessage("controlpanel.unlimited-hover"); + //String clickCommand = "/qs silentunlimited " + shop.getLocation().getWorld().getName() + " " + // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " + // + shop.getLocation().getBlockZ(); + String clickCommand = MsgUtil.getMessage("controlpanel.commands.unlimited", + String.valueOf(shop.getLocation().getWorld().getName()), + String.valueOf(shop.getLocation().getBlockX()), + String.valueOf(shop.getLocation().getBlockY()), + String.valueOf(shop.getLocation().getBlockZ())); + chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); + } + // Buying/Selling Mode + if (sender.hasPermission("quickshop.create.buy") && sender.hasPermission("quickshop.create.sell")) { + if (shop.isSelling()) { + String text = MsgUtil.getMessage("controlpanel.mode-selling"); + String hoverText = MsgUtil.getMessage("controlpanel.mode-selling-hover"); + //String clickCommand = "/qs silentbuy " + shop.getLocation().getWorld().getName() + " " + // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " + // + shop.getLocation().getBlockZ(); + String clickCommand = MsgUtil.getMessage("controlpanel.commands.buy", + String.valueOf(shop.getLocation().getWorld().getName()), + String.valueOf(shop.getLocation().getBlockX()), + String.valueOf(shop.getLocation().getBlockY()), + String.valueOf(shop.getLocation().getBlockZ())); + chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); + } else if (shop.isBuying()) { + String text = MsgUtil.getMessage("controlpanel.mode-buying"); + String hoverText = MsgUtil.getMessage("controlpanel.mode-buying-hover"); + //String clickCommand = "/qs silentsell " + shop.getLocation().getWorld().getName() + " " + // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " + // + shop.getLocation().getBlockZ() ; + String clickCommand = MsgUtil.getMessage("controlpanel.commands.sell", + String.valueOf(shop.getLocation().getWorld().getName()), + String.valueOf(shop.getLocation().getBlockX()), + String.valueOf(shop.getLocation().getBlockY()), + String.valueOf(shop.getLocation().getBlockZ())); + chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); + } + } + // Set Price + if (sender.hasPermission("quickshop.other.price") || shop.getOwner().equals(((Player) sender).getUniqueId())) { + String text = MsgUtil.getMessage("controlpanel.price", String.valueOf(shop.getPrice())); + String hoverText = MsgUtil.getMessage("controlpanel.price-hover"); + //String clickCommand = "/qs price [New Price]"; + String clickCommand = MsgUtil.getMessage("controlpanel.commands.price"); + chatSheetPrinter.printSuggestableCmdLine(text, hoverText, clickCommand); + } + // Refill + if (sender.hasPermission("quickshop.refill")) { + String text = MsgUtil.getMessage("controlpanel.refill", String.valueOf(shop.getPrice())); + String hoverText = MsgUtil.getMessage("controlpanel.refill-hover"); + //String clickCommand = "/qs refill [Amount]"; + String clickCommand = MsgUtil.getMessage("controlpanel.commands.refill"); + chatSheetPrinter.printSuggestableCmdLine(text, hoverText, clickCommand); + } + // Refill + if (sender.hasPermission("quickshop.empty")) { + String text = MsgUtil.getMessage("controlpanel.empty", String.valueOf(shop.getPrice())); + String hoverText = MsgUtil.getMessage("controlpanel.empty-hover"); + //String clickCommand = "/qs silentempty " + shop.getLocation().getWorld().getName() + " " + // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " + // + shop.getLocation().getBlockZ(); + String clickCommand = MsgUtil.getMessage("controlpanel.commands.empty", + String.valueOf(shop.getLocation().getWorld().getName()), + String.valueOf(shop.getLocation().getBlockX()), + String.valueOf(shop.getLocation().getBlockY()), + String.valueOf(shop.getLocation().getBlockZ())); + chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); + } + // Remove + if (sender.hasPermission("quickshop.other.destroy") || shop.getOwner().equals(((Player) sender).getUniqueId())) { + String text = MsgUtil.getMessage("controlpanel.remove", String.valueOf(shop.getPrice())); + String hoverText = MsgUtil.getMessage("controlpanel.remove-hover"); + //String clickCommand = "/qs silentremove " + shop.getLocation().getWorld().getName() + " " + // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " + // + shop.getLocation().getBlockZ(); + String clickCommand = MsgUtil.getMessage("controlpanel.commands.remove", + String.valueOf(shop.getLocation().getWorld().getName()), + String.valueOf(shop.getLocation().getBlockX()), + String.valueOf(shop.getLocation().getBlockY()), + String.valueOf(shop.getLocation().getBlockZ())); + chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); + } + + chatSheetPrinter.printFooter(); + } + + /** + * Send globalAlert to ops, console, log file. + * + * @param content The content to send. + */ + public static void sendGlobalAlert(String content) { + sendMessageToOps(content); + plugin.getLogger().warning(content); + plugin.getLogWatcher().add(content); + Util.debugLog(content); + } + + /** + * Send the ItemPreview chat msg by NMS. + * + * @param shop Target shop + * @param itemStack Target ItemStack + * @param player Target player + * @param normalText The text you will see + */ + public static void sendItemholochat(@NotNull Shop shop, @NotNull ItemStack itemStack, @NotNull Player player, @NotNull String normalText) { + try { + String json = ItemNMS.saveJsonfromNMS(itemStack); + if (json == null) + return; + TextComponent normalmessage = new TextComponent(normalText + " " + MsgUtil.getMessage("menu.preview")); + ComponentBuilder cBuilder = new ComponentBuilder(json); + if (player.hasPermission("quickshop.preview")) + normalmessage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, MsgUtil + .getMessage("menu.commands.preview", shop.getLocation().getWorld().getName(), String + .valueOf(shop.getLocation().getBlockX()), String.valueOf(shop.getLocation().getBlockY()), String + .valueOf(shop.getLocation().getBlockZ())))); + normalmessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, cBuilder.create())); + player.spigot().sendMessage(normalmessage); + } catch (Throwable t) { + t.printStackTrace(); + } + } + + /** + * Send a message for all online Ops. + * + * @param message The message you want send + */ + public static void sendMessageToOps(@NotNull String message) { + new BukkitRunnable() { + @Override + public void run() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.isOp() || player.hasPermission("quickshop.alert")) { + player.sendMessage(message); + } + } + } + }.runTaskAsynchronously(plugin); + + } + + /** + * Send a purchaseSuccess message for a player. + * + * @param p Target player + * @param shop Target shop + * @param amount Trading item amounts. + */ + public static void sendPurchaseSuccess(@NotNull Player p, @NotNull Shop shop, int amount) { + ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); + chatSheetPrinter.printHeader(); + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.successful-purchase")); + chatSheetPrinter.printLine(MsgUtil + .getMessage("menu.item-name-and-price", "" + amount, Util.getItemStackName(shop.getItem()), Util + .format((amount * shop.getPrice())))); + Map enchs = new HashMap<>(); + if (shop.getItem().hasItemMeta() && shop.getItem().getItemMeta().hasEnchants()) + enchs = shop.getItem().getItemMeta().getEnchants(); + if (!enchs.isEmpty()) { + chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants")); + for (Entry entries : enchs.entrySet()) { + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); + } + } + if (shop.getItem().getItemMeta() instanceof EnchantmentStorageMeta) { + EnchantmentStorageMeta stor = (EnchantmentStorageMeta) shop.getItem().getItemMeta(); + stor.getStoredEnchants(); + enchs = stor.getStoredEnchants(); + if (!enchs.isEmpty()) { + chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.stored-enchants")); + for (Entry entries : enchs.entrySet()) { + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); + } + } + } + chatSheetPrinter.printFooter(); + } + + /** + * Send a sellSuccess message for a player. + * + * @param p Target player + * @param shop Target shop + * @param amount Trading item amounts. + */ + public static void sendSellSuccess(@NotNull Player p, @NotNull Shop shop, int amount) { + ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); + chatSheetPrinter.printHeader(); + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.successfully-sold")); + chatSheetPrinter.printLine(MsgUtil + .getMessage("menu.item-name-and-price", "" + amount, Util.getItemStackName(shop.getItem()), Util + .format((amount * shop.getPrice())))); + if (plugin.getConfig().getBoolean("show-tax")) { + double tax = plugin.getConfig().getDouble("tax"); + double total = amount * shop.getPrice(); + if (tax != 0) { + if (!p.getUniqueId().equals(shop.getOwner())) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.sell-tax", Util.format((tax * total)))); + } else { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.sell-tax-self")); + } + } + } + Map enchs = new HashMap<>(); + if (shop.getItem().hasItemMeta() && shop.getItem().getItemMeta().hasEnchants()) + enchs = shop.getItem().getItemMeta().getEnchants(); + if (!enchs.isEmpty()) { + chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants")); + for (Entry entries : enchs.entrySet()) { + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); + } + } + if (shop.getItem().getItemMeta() instanceof EnchantmentStorageMeta) { + EnchantmentStorageMeta stor = (EnchantmentStorageMeta) shop.getItem().getItemMeta(); + stor.getStoredEnchants(); + enchs = stor.getStoredEnchants(); + if (!enchs.isEmpty()) { + chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.stored-enchants")); + for (Entry entries : enchs.entrySet()) { + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); + } + } + } + chatSheetPrinter.printFooter(); + } + + /** + * Send a shop infomation to a player. + * + * @param p Target player + * @param shop The shop + */ + public static void sendShopInfo(@NotNull Player p, @NotNull Shop shop) { + // Potentially faster with an array? + ItemStack items = shop.getItem(); + ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); + chatSheetPrinter.printHeader(); + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.shop-information")); + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.owner", shop.ownerName())); + //Enabled + sendItemholochat(shop, shop.getItem(), p, ChatColor.DARK_PURPLE + MsgUtil + .getMessage("tableformat.left_begin") + " " + MsgUtil + .getMessage("menu.item", Util.getItemStackName(shop.getItem()))); + if (Util.isTool(items.getType())) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.damage-percent-remaining", Util.getToolPercentage(items))); + } + if (shop.isSelling()) { + if (shop.getRemainingStock() == -1) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.stock", "" + MsgUtil.getMessage("signs.unlimited"))); + } else { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.stock", "" + shop.getRemainingStock())); + } + } else { + if (shop.getRemainingSpace() == -1) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.space", "" + MsgUtil.getMessage("signs.unlimited"))); + } else { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.space", "" + shop.getRemainingSpace())); + } + } + chatSheetPrinter.printLine(MsgUtil + .getMessage("menu.price-per", Util.getItemStackName(shop.getItem()), Util.format(shop.getPrice()))); + if (shop.isBuying()) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.this-shop-is-buying")); + } else { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.this-shop-is-selling")); + } + Map enchs = new HashMap<>(); + if (items.hasItemMeta() && items.getItemMeta().hasEnchants()) + enchs = items.getItemMeta().getEnchants(); + if (!enchs.isEmpty()) { + chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants")); + for (Entry entries : enchs.entrySet()) { + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey()) + " " + entries.getValue()); + } + } + if (items.getItemMeta() instanceof EnchantmentStorageMeta) { + EnchantmentStorageMeta stor = (EnchantmentStorageMeta) items.getItemMeta(); + stor.getStoredEnchants(); + enchs = stor.getStoredEnchants(); + if (!enchs.isEmpty()) { + chatSheetPrinter.printLine(MsgUtil.getMessage("menu.stored-enchants") + MsgUtil + .getMessage("tableformat.right_half_line")); + for (Entry entries : enchs.entrySet()) { + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey()) + " " + entries + .getValue()); + } + } + } + chatSheetPrinter.printFooter(); + } + @SuppressWarnings("UnusedAssignment") private static void updateMessages(int selectedVersion) throws IOException { if (selectedVersion == 1) { @@ -299,608 +900,8 @@ public class MsgUtil { } - /** - * Send a message for all online Ops. - * - * @param message The message you want send - */ - public static void sendMessageToOps(@NotNull String message) { - new BukkitRunnable() { - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.isOp() || player.hasPermission("quickshop.alert")) { - player.sendMessage(message); - } - } - } - }.runTaskAsynchronously(plugin); - - } - /** - * Send controlPanel infomation to sender - * - * @param sender Target sender - * @param shop Target shop - */ - public static void sendControlPanelInfo(@NotNull CommandSender sender, @NotNull Shop shop) { - if (!sender.hasPermission("quickshop.use")) { - return; - } - - if (plugin.getConfig().getBoolean("sneak-to-control")) - if (sender instanceof Player) - if (!((Player) sender).isSneaking()) - return; - ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(sender); - chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(MsgUtil.getMessage("controlpanel.infomation")); - // Owner - if (!sender.hasPermission("quickshop.setowner")) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.owner", shop.ownerName())); - } else { - chatSheetPrinter.printSuggestableCmdLine(MsgUtil.getMessage("controlpanel.setowner", shop.ownerName()), MsgUtil - .getMessage("controlpanel.setowner-hover"), MsgUtil.getMessage("controlpanel.commands.setowner")); - } - - // Unlimited - if (sender.hasPermission("quickshop.unlimited")) { - String text = MsgUtil.getMessage("controlpanel.unlimited", bool2String(shop.isUnlimited())); - String hoverText = MsgUtil.getMessage("controlpanel.unlimited-hover"); - //String clickCommand = "/qs silentunlimited " + shop.getLocation().getWorld().getName() + " " - // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " - // + shop.getLocation().getBlockZ(); - String clickCommand = MsgUtil.getMessage("controlpanel.commands.unlimited", - String.valueOf(shop.getLocation().getWorld().getName()), - String.valueOf(shop.getLocation().getBlockX()), - String.valueOf(shop.getLocation().getBlockY()), - String.valueOf(shop.getLocation().getBlockZ())); - chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); - } - // Buying/Selling Mode - if (sender.hasPermission("quickshop.create.buy") && sender.hasPermission("quickshop.create.sell")) { - if (shop.isSelling()) { - String text = MsgUtil.getMessage("controlpanel.mode-selling"); - String hoverText = MsgUtil.getMessage("controlpanel.mode-selling-hover"); - //String clickCommand = "/qs silentbuy " + shop.getLocation().getWorld().getName() + " " - // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " - // + shop.getLocation().getBlockZ(); - String clickCommand = MsgUtil.getMessage("controlpanel.commands.buy", - String.valueOf(shop.getLocation().getWorld().getName()), - String.valueOf(shop.getLocation().getBlockX()), - String.valueOf(shop.getLocation().getBlockY()), - String.valueOf(shop.getLocation().getBlockZ())); - chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); - } else if (shop.isBuying()) { - String text = MsgUtil.getMessage("controlpanel.mode-buying"); - String hoverText = MsgUtil.getMessage("controlpanel.mode-buying-hover"); - //String clickCommand = "/qs silentsell " + shop.getLocation().getWorld().getName() + " " - // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " - // + shop.getLocation().getBlockZ() ; - String clickCommand = MsgUtil.getMessage("controlpanel.commands.sell", - String.valueOf(shop.getLocation().getWorld().getName()), - String.valueOf(shop.getLocation().getBlockX()), - String.valueOf(shop.getLocation().getBlockY()), - String.valueOf(shop.getLocation().getBlockZ())); - chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); - } - } - // Set Price - if (sender.hasPermission("quickshop.other.price") || shop.getOwner().equals(((Player) sender).getUniqueId())) { - String text = MsgUtil.getMessage("controlpanel.price", String.valueOf(shop.getPrice())); - String hoverText = MsgUtil.getMessage("controlpanel.price-hover"); - //String clickCommand = "/qs price [New Price]"; - String clickCommand = MsgUtil.getMessage("controlpanel.commands.price"); - chatSheetPrinter.printSuggestableCmdLine(text, hoverText, clickCommand); - } - // Refill - if (sender.hasPermission("quickshop.refill")) { - String text = MsgUtil.getMessage("controlpanel.refill", String.valueOf(shop.getPrice())); - String hoverText = MsgUtil.getMessage("controlpanel.refill-hover"); - //String clickCommand = "/qs refill [Amount]"; - String clickCommand = MsgUtil.getMessage("controlpanel.commands.refill"); - chatSheetPrinter.printSuggestableCmdLine(text, hoverText, clickCommand); - } - // Refill - if (sender.hasPermission("quickshop.empty")) { - String text = MsgUtil.getMessage("controlpanel.empty", String.valueOf(shop.getPrice())); - String hoverText = MsgUtil.getMessage("controlpanel.empty-hover"); - //String clickCommand = "/qs silentempty " + shop.getLocation().getWorld().getName() + " " - // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " - // + shop.getLocation().getBlockZ(); - String clickCommand = MsgUtil.getMessage("controlpanel.commands.empty", - String.valueOf(shop.getLocation().getWorld().getName()), - String.valueOf(shop.getLocation().getBlockX()), - String.valueOf(shop.getLocation().getBlockY()), - String.valueOf(shop.getLocation().getBlockZ())); - chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); - } - // Remove - if (sender.hasPermission("quickshop.other.destroy") || shop.getOwner().equals(((Player) sender).getUniqueId())) { - String text = MsgUtil.getMessage("controlpanel.remove", String.valueOf(shop.getPrice())); - String hoverText = MsgUtil.getMessage("controlpanel.remove-hover"); - //String clickCommand = "/qs silentremove " + shop.getLocation().getWorld().getName() + " " - // + shop.getLocation().getBlockX() + " " + shop.getLocation().getBlockY() + " " - // + shop.getLocation().getBlockZ(); - String clickCommand = MsgUtil.getMessage("controlpanel.commands.remove", - String.valueOf(shop.getLocation().getWorld().getName()), - String.valueOf(shop.getLocation().getBlockX()), - String.valueOf(shop.getLocation().getBlockY()), - String.valueOf(shop.getLocation().getBlockZ())); - chatSheetPrinter.printExecuteableCmdLine(text, hoverText, clickCommand); - } - - chatSheetPrinter.printFooter(); - } - - /** - * Translate boolean value to String, the symbon is changeable by language file. - * - * @param bool The boolean value - * @return The result of translate. - */ - public static String bool2String(boolean bool) { - if (bool) { - return MsgUtil.getMessage("booleanformat.success"); - } else { - return MsgUtil.getMessage("booleanformat.failed"); - } - } - - /** - * loads all player purchase messages from the database. - */ - public static void loadTransactionMessages() { - player_messages.clear(); // Delete old messages - try { - ResultSet rs = plugin.getDatabaseHelper().selectAllMessages(plugin.getDatabase()); - while (rs.next()) { - UUID owner = UUID.fromString(rs.getString("owner")); - String message = rs.getString("message"); - LinkedList msgs = player_messages.computeIfAbsent(owner, k -> new LinkedList<>()); - msgs.add(message); - } - } catch (SQLException e) { - e.printStackTrace(); - plugin.getLogger().log(Level.WARNING, "Could not load transaction messages from database. Skipping."); - } - } - - /** - * Load Itemi18n fron file - */ - public static void loadItemi18n() { - File itemi18nFile = new File(plugin.getDataFolder(), "itemi18n.yml"); - if (!itemi18nFile.exists()) { - plugin.getLogger().info("Creating itemi18n.yml"); - plugin.saveResource("itemi18n.yml", true); - } - // Store it - itemi18n = YamlConfiguration.loadConfiguration(itemi18nFile); - itemi18n.options().copyDefaults(true); - YamlConfiguration itemi18nYAML = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin - .getResource("itemi18n.yml"))); - itemi18n.setDefaults(itemi18nYAML); - Util.parseColours(itemi18n); - Material[] itemsi18n = Material.values(); - for (Material material : itemsi18n) { - String itemi18nString = itemi18n.getString("itemi18n." + material.name()); - if (itemi18nString != null && !itemi18nString.isEmpty()) - continue; - String itemName = material.name(); - String lastItemName = Util.prettifyText(itemName); - String localizedName = Util.getLocalizedName(new ItemStack(material)); - /* If have localizedName, use localizedName, not our processed name */ - if (localizedName != null) - lastItemName = localizedName; - itemi18n.set("itemi18n." + itemName, lastItemName); - plugin.getLogger().info("Found new items/blocks [" + Util - .prettifyText(lastItemName) + "] , adding it to the config..."); - } - try { - itemi18n.save(itemi18nFile); - } catch (IOException e) { - e.printStackTrace(); - plugin.getLogger().log(Level.WARNING, "Could not load/save transaction itemname from itemi18n.yml. Skipping."); - } - plugin.getLogger().info("Complete to load Itemname i18n."); - } - - /** - * Get item's i18n name - * - * @param itemBukkitName ItemBukkitName(e.g. Material.STONE.name()) - * @return String Item's i18n name. - */ - public static String getItemi18n(@NotNull String itemBukkitName) { - if (itemBukkitName.isEmpty()) - return "Item is empty"; - String itemnameI18n = itemi18n.getString("itemi18n." + itemBukkitName); - if (itemnameI18n != null && !itemnameI18n.isEmpty()) - return itemnameI18n; - Material material = Material.matchMaterial(itemBukkitName); - if (material == null) - return "Material not exist"; - return Util.prettifyText(material.name()); - } - - public static void loadEnchi18n() { - plugin.getLogger().info("Starting loading Enchantment i18n..."); - File enchi18nFile = new File(plugin.getDataFolder(), "enchi18n.yml"); - if (!enchi18nFile.exists()) { - plugin.getLogger().info("Creating enchi18n.yml"); - plugin.saveResource("enchi18n.yml", true); - } - // Store it - enchi18n = YamlConfiguration.loadConfiguration(enchi18nFile); - enchi18n.options().copyDefaults(true); - YamlConfiguration enchi18nYAML = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin. - getResource("enchi18n.yml"))); - enchi18n.setDefaults(enchi18nYAML); - Util.parseColours(enchi18n); - Enchantment[] enchsi18n = Enchantment.values(); - for (Enchantment ench : enchsi18n) { - String enchi18nString = enchi18n.getString("enchi18n." + ench.getKey().getKey().toString().trim()); - if (enchi18nString != null && !enchi18nString.isEmpty()) - continue; - String enchName = ench.getKey().getKey(); - enchi18n.set("enchi18n." + enchName, Util.prettifyText(enchName)); - plugin.getLogger().info("Found new ench [" + Util.prettifyText(enchName) + "] , adding it to the config..."); - } - try { - enchi18n.save(enchi18nFile); - } catch (IOException e) { - e.printStackTrace(); - plugin.getLogger().log(Level.WARNING, "Could not load/save transaction enchname from enchi18n.yml. Skipping."); - } - plugin.getLogger().info("Complete to load enchname i18n."); - } - - /** - * Get Enchantment's i18n name. - * - * @param key The Enchantment. - * @return Enchantment's i18n name. - */ - public static String getEnchi18n(@NotNull Enchantment key) { - String enchString = key.getKey().getKey(); - if (enchString.isEmpty()) - return "Enchantment key is empty"; - String enchI18n = enchi18n.getString("enchi18n." + enchString); - if (enchI18n != null && !enchI18n.isEmpty()) - return enchI18n; - return Util.prettifyText(enchString); - } - - public static void loadPotioni18n() { - plugin.getLogger().info("Starting loading Potion i18n..."); - File potioni18nFile = new File(plugin.getDataFolder(), "potioni18n.yml"); - if (!potioni18nFile.exists()) { - plugin.getLogger().info("Creating potioni18n.yml"); - plugin.saveResource("potioni18n.yml", true); - } - // Store it - potioni18n = YamlConfiguration.loadConfiguration(potioni18nFile); - potioni18n.options().copyDefaults(true); - YamlConfiguration potioni18nYAML = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin - .getResource("potioni18n.yml"))); - potioni18n.setDefaults(potioni18nYAML); - Util.parseColours(potioni18n); - PotionEffectType[] potionsi18n = PotionEffectType.values(); - for (PotionEffectType potion : potionsi18n) { - if (potion != null) { - String potionI18n = potioni18n.getString("potioni18n." + potion.getName().trim()); - if (potionI18n != null && !potionI18n.isEmpty()) - continue; - String potionName = potion.getName(); - plugin.getLogger().info("Found new potion [" + Util.prettifyText(potionName) + "] , adding it to the config..."); - potioni18n.set("potioni18n." + potionName, Util.prettifyText(potionName)); - } - } - try { - potioni18n.save(potioni18nFile); - } catch (IOException e) { - e.printStackTrace(); - plugin.getLogger().log(Level.WARNING, "Could not load/save transaction potionname from potioni18n.yml. Skipping."); - } - plugin.getLogger().info("Complete to load potionname i18n."); - } - - /** - * Get potion effect's i18n name. - * - * @param potion potionType - * @return Potion's i18n name. - */ - public static String getPotioni18n(@NotNull PotionEffectType potion) { - String potionString = potion.getName().trim(); - if (potionString.isEmpty()) - return "Potion name is empty."; - String potionI18n = potioni18n.getString("potioni18n." + potionString); - if (potionI18n != null && !potionI18n.isEmpty()) - return potionI18n; - return Util.prettifyText(potionString); - } - - /** - * @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. - * @param isUnlimited The shop is or unlimited - */ - public static void send(@NotNull UUID player, @NotNull String message, boolean isUnlimited) { - if (plugin.getConfig().getBoolean("shop.ignore-unlimited-shop-messages") && isUnlimited) - return; //Ignore unlimited shops messages. - OfflinePlayer p = Bukkit.getOfflinePlayer(player); - if (!p.isOnline()) { - LinkedList msgs = player_messages.get(player); - // msgs = new LinkedList(); - if (msgs == null) - msgs = new LinkedList<>(); - player_messages.put(player, msgs); - msgs.add(message); - plugin.getDatabaseHelper().sendMessage(plugin.getDatabase(), player, message, System.currentTimeMillis()); - } else { - if (p.getPlayer() != null) - p.getPlayer().sendMessage(message); - } - } - - /** - * Deletes any messages that are older than a week in the database, to save - * on space. - */ - public static void clean() { - plugin.getLogger().info("Cleaning purchase messages from the database that are over a week old..."); - // 604800,000 msec = 1 week. - long weekAgo = System.currentTimeMillis() - 604800000; - plugin.getDatabaseHelper().cleanMessage(plugin.getDatabase(), 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(@NotNull OfflinePlayer p) { //TODO Changed to UUID - if (p.isOnline()) { - UUID pName = p.getUniqueId(); - LinkedList msgs = player_messages.get(pName); - if (msgs != null) { - for (String msg : msgs) { - if (p.getPlayer() != null) - p.getPlayer().sendMessage(msg); - } - plugin.getDatabaseHelper().cleanMessageForPlayer(plugin.getDatabase(), pName); - msgs.clear(); - } - return true; - } - return false; - } - - /** - * Send a shop infomation to a player. - * - * @param p Target player - * @param shop The shop - */ - public static void sendShopInfo(@NotNull Player p, @NotNull Shop shop) { - // Potentially faster with an array? - ItemStack items = shop.getItem(); - ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); - chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.shop-information")); - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.owner", shop.ownerName())); - //Enabled - sendItemholochat(shop, shop.getItem(), p, ChatColor.DARK_PURPLE + MsgUtil - .getMessage("tableformat.left_begin") + " " + MsgUtil - .getMessage("menu.item", Util.getItemStackName(shop.getItem()))); - if (Util.isTool(items.getType())) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.damage-percent-remaining", Util.getToolPercentage(items))); - } - if (shop.isSelling()) { - if (shop.getRemainingStock() == -1) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.stock", "" + MsgUtil.getMessage("signs.unlimited"))); - } else { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.stock", "" + shop.getRemainingStock())); - } - } else { - if (shop.getRemainingSpace() == -1) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.space", "" + MsgUtil.getMessage("signs.unlimited"))); - } else { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.space", "" + shop.getRemainingSpace())); - } - } - chatSheetPrinter.printLine(MsgUtil - .getMessage("menu.price-per", Util.getItemStackName(shop.getItem()), Util.format(shop.getPrice()))); - if (shop.isBuying()) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.this-shop-is-buying")); - } else { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.this-shop-is-selling")); - } - Map enchs = new HashMap<>(); - if (items.hasItemMeta() && items.getItemMeta().hasEnchants()) - enchs = items.getItemMeta().getEnchants(); - if (!enchs.isEmpty()) { - chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants")); - for (Entry entries : enchs.entrySet()) { - chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey()) + " " + entries.getValue()); - } - } - if (items.getItemMeta() instanceof EnchantmentStorageMeta) { - EnchantmentStorageMeta stor = (EnchantmentStorageMeta) items.getItemMeta(); - stor.getStoredEnchants(); - enchs = stor.getStoredEnchants(); - if (!enchs.isEmpty()) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.stored-enchants") + MsgUtil - .getMessage("tableformat.right_half_line")); - for (Entry entries : enchs.entrySet()) { - chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey()) + " " + entries - .getValue()); - } - } - } - chatSheetPrinter.printFooter(); - } - - /** - * Send a purchaseSuccess message for a player. - * - * @param p Target player - * @param shop Target shop - * @param amount Trading item amounts. - */ - public static void sendPurchaseSuccess(@NotNull Player p, @NotNull Shop shop, int amount) { - ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); - chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.successful-purchase")); - chatSheetPrinter.printLine(MsgUtil - .getMessage("menu.item-name-and-price", "" + amount, Util.getItemStackName(shop.getItem()), Util - .format((amount * shop.getPrice())))); - Map enchs = new HashMap<>(); - if (shop.getItem().hasItemMeta() && shop.getItem().getItemMeta().hasEnchants()) - enchs = shop.getItem().getItemMeta().getEnchants(); - if (!enchs.isEmpty()) { - chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants")); - for (Entry entries : enchs.entrySet()) { - chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); - } - } - if (shop.getItem().getItemMeta() instanceof EnchantmentStorageMeta) { - EnchantmentStorageMeta stor = (EnchantmentStorageMeta) shop.getItem().getItemMeta(); - stor.getStoredEnchants(); - enchs = stor.getStoredEnchants(); - if (!enchs.isEmpty()) { - chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.stored-enchants")); - for (Entry entries : enchs.entrySet()) { - chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); - } - } - } - chatSheetPrinter.printFooter(); - } - - /** - * Send globalAlert to ops, console, log file. - * - * @param content The content to send. - */ - public static void sendGlobalAlert(String content) { - sendMessageToOps(content); - plugin.getLogger().warning(content); - plugin.getLogWatcher().add(content); - Util.debugLog(content); - } - - /** - * Send a sellSuccess message for a player. - * - * @param p Target player - * @param shop Target shop - * @param amount Trading item amounts. - */ - public static void sendSellSuccess(@NotNull Player p, @NotNull Shop shop, int amount) { - ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); - chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.successfully-sold")); - chatSheetPrinter.printLine(MsgUtil - .getMessage("menu.item-name-and-price", "" + amount, Util.getItemStackName(shop.getItem()), Util - .format((amount * shop.getPrice())))); - if (plugin.getConfig().getBoolean("show-tax")) { - double tax = plugin.getConfig().getDouble("tax"); - double total = amount * shop.getPrice(); - if (tax != 0) { - if (!p.getUniqueId().equals(shop.getOwner())) { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.sell-tax", Util.format((tax * total)))); - } else { - chatSheetPrinter.printLine(MsgUtil.getMessage("menu.sell-tax-self")); - } - } - } - Map enchs = new HashMap<>(); - if (shop.getItem().hasItemMeta() && shop.getItem().getItemMeta().hasEnchants()) - enchs = shop.getItem().getItemMeta().getEnchants(); - if (!enchs.isEmpty()) { - chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants")); - for (Entry entries : enchs.entrySet()) { - chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); - } - } - if (shop.getItem().getItemMeta() instanceof EnchantmentStorageMeta) { - EnchantmentStorageMeta stor = (EnchantmentStorageMeta) shop.getItem().getItemMeta(); - stor.getStoredEnchants(); - enchs = stor.getStoredEnchants(); - if (!enchs.isEmpty()) { - chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.stored-enchants")); - for (Entry entries : enchs.entrySet()) { - chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey())); - } - } - } - chatSheetPrinter.printFooter(); - } - - /** - * getMessage in messages.yml - * - * @param loc location - * @param args args - * @return message - */ - public static String getMessage(@NotNull String loc, @NotNull String... args) { - String raw = messagei18n.getString(loc); - if (raw == null) - return invaildMsg + ": " + loc; - return fillArgs(raw, args); - } - - /** - * Replace args in raw to args - * - * @param raw text - * @param args args - * @return filled text - */ - public static String fillArgs(@Nullable String raw, @Nullable String... args) { - if (raw == null) - return "Invalid message: null"; - if (raw.isEmpty()) - return ""; - if (args == null) - return raw; - for (int i = 0; i < args.length; i++) - raw = StringUtils.replace(raw, "{" + i + "}", args[i] == null ? "" : args[i]); - return raw; - } - - /** - * Send the ItemPreview chat msg by NMS. - * - * @param shop Target shop - * @param itemStack Target ItemStack - * @param player Target player - * @param normalText The text you will see - */ - public static void sendItemholochat(@NotNull Shop shop, @NotNull ItemStack itemStack, @NotNull Player player, @NotNull String normalText) { - try { - String json = ItemNMS.saveJsonfromNMS(itemStack); - if (json == null) - return; - TextComponent normalmessage = new TextComponent(normalText + " " + MsgUtil.getMessage("menu.preview")); - ComponentBuilder cBuilder = new ComponentBuilder(json); - if (player.hasPermission("quickshop.preview")) - normalmessage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, MsgUtil - .getMessage("menu.commands.preview", shop.getLocation().getWorld().getName(), String - .valueOf(shop.getLocation().getBlockX()), String.valueOf(shop.getLocation().getBlockY()), String - .valueOf(shop.getLocation().getBlockZ())))); - normalmessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, cBuilder.create())); - player.spigot().sendMessage(normalmessage); - } catch (Throwable t) { - t.printStackTrace(); - } + public static YamlConfiguration getI18nYaml() { + return messagei18n; } // /** diff --git a/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java b/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java index 325a365ad..917c244c0 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java +++ b/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java @@ -27,16 +27,16 @@ import org.maxgamer.quickshop.QuickShop; * Auto report errors to qs's sentry. */ public class SentryErrorReporter { - private Context context; private final String dsn = "https://6a7881aa07164412bcb84a0f76253ae9@sentry.io/1473041?" + "stacktrace.app.packages=org.maxgamer.quickshop"; + private final ArrayList reported = new ArrayList<>(); + private Context context; + private boolean disable; + private boolean enabled; + private List ignoredException = new ArrayList<>(); + private QuickShop plugin; /* Pre-init it if it called before the we create it... */ private SentryClient sentryClient; - private boolean enabled; - private final ArrayList reported = new ArrayList<>(); - private QuickShop plugin; private boolean tempDisable; - private boolean disable; - private List ignoredException = new ArrayList<>(); public SentryErrorReporter(@NotNull QuickShop plugin) { this.plugin = plugin; @@ -80,19 +80,71 @@ public class SentryErrorReporter { } /** - * Unload Sentry error reporter + * Dupe report check + * @param throwable Throws + * @return dupecated */ - private void unit() { - enabled = false; + private boolean canReport(@NotNull Throwable throwable) { + if (!enabled) { + return false; + } + StackTraceElement stackTraceElement; + if (throwable.getStackTrace().length < 3) { + stackTraceElement = throwable.getStackTrace()[1]; + } else { + stackTraceElement = throwable.getStackTrace()[2]; + } + String text = stackTraceElement.getClassName() + "#" + stackTraceElement.getMethodName() + "#" + stackTraceElement + .getLineNumber(); + if (!reported.contains(text)) { + reported.add(text); + return true; + } else { + return false; + } + } - private String getPluginInfo() { - StringBuilder buffer = new StringBuilder(); - for (Plugin bplugin : Bukkit.getPluginManager().getPlugins()) { - buffer.append("\t").append(bplugin.getName()).append("@").append(bplugin.isEnabled() ? "Enabled" : "Disabled") - .append("\n"); + /** + * Check a throw is cause by QS + * @param throwable Throws + * @return Cause or not + */ + private boolean checkWasCauseByQS(@Nullable Throwable throwable) { + if (throwable == null) + return false; + while (throwable.getCause() != null) { + throwable = throwable.getCause(); } - return buffer.toString(); + long element = Arrays.stream(throwable.getStackTrace()) + .limit(10) + .filter(stackTraceElement -> stackTraceElement.getClassName().contains("org.maxgamer.quickshop")) + .count(); + return element > 0; + } + + /** + * Set ignore throw. + * It will unlocked after accept a throw + */ + public void ignoreThrow() { + tempDisable = true; + } + + /** + * Set ignore throws. + * It will unlocked after called method resetIgnores. + */ + public void ignoreThrows() { + disable = true; + } + + /** + * Reset ignore throw(s). + */ + public void resetIgnores() { + tempDisable = false; + disable = false; } /** @@ -161,71 +213,19 @@ public class SentryErrorReporter { } /** - * Check a throw is cause by QS - * @param throwable Throws - * @return Cause or not + * Unload Sentry error reporter */ - private boolean checkWasCauseByQS(@Nullable Throwable throwable) { - if (throwable == null) - return false; - while (throwable.getCause() != null) { - throwable = throwable.getCause(); - } - long element = Arrays.stream(throwable.getStackTrace()) - .limit(10) - .filter(stackTraceElement -> stackTraceElement.getClassName().contains("org.maxgamer.quickshop")) - .count(); - return element > 0; + private void unit() { + enabled = false; } - /** - * Dupe report check - * @param throwable Throws - * @return dupecated - */ - private boolean canReport(@NotNull Throwable throwable) { - if (!enabled) { - return false; - } - StackTraceElement stackTraceElement; - if (throwable.getStackTrace().length < 3) { - stackTraceElement = throwable.getStackTrace()[1]; - } else { - stackTraceElement = throwable.getStackTrace()[2]; - } - String text = stackTraceElement.getClassName() + "#" + stackTraceElement.getMethodName() + "#" + stackTraceElement - .getLineNumber(); - if (!reported.contains(text)) { - reported.add(text); - return true; - } else { - return false; - } - - } - - class QuickShopExceptionFilter implements Filter { - - /** - * Check if a given log record should be published. - * - * @param record a LogRecord - * @return true if the log record should be published. - */ - @Override - public boolean isLoggable(@NotNull LogRecord record) { - if (!enabled) - return true; - Level level = record.getLevel(); - if (level != Level.WARNING && level != Level.SEVERE) - return true; - if (Util.isDevMode()) { - sendError(record.getThrown(), record.getMessage()); - return true; - } else { - return sendError(record.getThrown(), record.getMessage()) == null; - } + private String getPluginInfo() { + StringBuilder buffer = new StringBuilder(); + for (Plugin bplugin : Bukkit.getPluginManager().getPlugins()) { + buffer.append("\t").append(bplugin.getName()).append("@").append(bplugin.isEnabled() ? "Enabled" : "Disabled") + .append("\n"); } + return buffer.toString(); } class GlobalExceptionFilter implements Filter { @@ -252,28 +252,28 @@ public class SentryErrorReporter { } } - /** - * Set ignore throw. - * It will unlocked after accept a throw - */ - public void ignoreThrow() { - tempDisable = true; - } + class QuickShopExceptionFilter implements Filter { - /** - * Set ignore throws. - * It will unlocked after called method resetIgnores. - */ - public void ignoreThrows() { - disable = true; - } - - /** - * Reset ignore throw(s). - */ - public void resetIgnores() { - tempDisable = false; - disable = false; + /** + * Check if a given log record should be published. + * + * @param record a LogRecord + * @return true if the log record should be published. + */ + @Override + public boolean isLoggable(@NotNull LogRecord record) { + if (!enabled) + return true; + Level level = record.getLevel(); + if (level != Level.WARNING && level != Level.SEVERE) + return true; + if (Util.isDevMode()) { + sendError(record.getThrown(), record.getMessage()); + return true; + } else { + return sendError(record.getThrown(), record.getMessage()) == null; + } + } } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Timer.java b/src/main/java/org/maxgamer/quickshop/Util/Timer.java index 6138b87dd..3102d1d1d 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Timer.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Timer.java @@ -32,6 +32,27 @@ public class Timer { this.startTime = startTime; } + /** + * Return how long time running when timer set and destory the timer. + * + * @return time + */ + public long endTimer() { + long time = System.currentTimeMillis() - startTime; + startTime = 0; + return time; + } + + /** + * Return how long time running after atTimeS. THIS NOT WILL DESTORY AND STOP THE TIMER + * + * @param atTime The inited time + * @return time + */ + public long getTimerAt(long atTime) { + return atTime - startTime; + } + /** * Create a Timer. * Time Unit: ms @@ -48,25 +69,4 @@ public class Timer { public long getTimer() { return System.currentTimeMillis() - startTime; } - - /** - * Return how long time running after atTimeS. THIS NOT WILL DESTORY AND STOP THE TIMER - * - * @param atTime The inited time - * @return time - */ - public long getTimerAt(long atTime) { - return atTime - startTime; - } - - /** - * Return how long time running when timer set and destory the timer. - * - * @return time - */ - public long endTimer() { - long time = System.currentTimeMillis() - startTime; - startTime = 0; - return time; - } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/UpdateInfomation.java b/src/main/java/org/maxgamer/quickshop/Util/UpdateInfomation.java index e02766ca8..1c047c949 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/UpdateInfomation.java +++ b/src/main/java/org/maxgamer/quickshop/Util/UpdateInfomation.java @@ -5,9 +5,10 @@ import org.jetbrains.annotations.*; @AllArgsConstructor @ToString -@Getter -@Setter +@Data +@EqualsAndHashCode public class UpdateInfomation { - @Nullable private String version; private boolean isBeta; + @Nullable private String version; + } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Updater.java b/src/main/java/org/maxgamer/quickshop/Util/Updater.java index f75b6fb52..9fdbefe19 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Updater.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Updater.java @@ -25,7 +25,7 @@ public class Updater { */ public static UpdateInfomation checkUpdate() { if (!QuickShop.instance.getConfig().getBoolean("updater")) { - return new UpdateInfomation(null, false); + return new UpdateInfomation(false, null); } try { HttpsURLConnection connection = (HttpsURLConnection) new URL("https://api.spigotmc.org/legacy/update.php?resource=62575") @@ -37,47 +37,17 @@ public class Updater { String spigotPluginVersion = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine(); if (spigotPluginVersion != null && !spigotPluginVersion.equals(localPluginVersion)) { connection.disconnect(); - return new UpdateInfomation(spigotPluginVersion, spigotPluginVersion.toLowerCase().contains("beta")); + return new UpdateInfomation(spigotPluginVersion.toLowerCase().contains("beta"), spigotPluginVersion); } connection.disconnect(); - return new UpdateInfomation(spigotPluginVersion, false); + return new UpdateInfomation(false, spigotPluginVersion); } catch (IOException e) { Bukkit.getConsoleSender() .sendMessage(ChatColor.RED + "[QuickShop] Failed to check for an update on SpigotMC.org! It might be an internet issue or the SpigotMC host is down. If you want disable the update checker, you can disable in config.yml, but we still high-recommend check for updates on SpigotMC.org often."); - return new UpdateInfomation(null, false); + return new UpdateInfomation(false, null); } } - public static void replaceTheJar(byte[] data) throws RuntimeException, IOException { - File pluginFolder = new File("plugins"); - if (!pluginFolder.exists()) - throw new RuntimeException("Can't find the plugins folder."); - if (!pluginFolder.isDirectory()) - throw new RuntimeException("Plugins not a folder."); - File[] plugins = pluginFolder.listFiles(); - if (plugins == null) - throw new IOException("Can't get the files in plugins folder"); - File quickshop = null; - for (File plugin : plugins) { - try { - PluginDescriptionFile desc = QuickShop.instance.getPluginLoader().getPluginDescription(plugin); - if (!desc.getName().equals(QuickShop.instance.getDescription().getName())) - continue; - Util.debugLog("Selected: " + plugin.getPath()); - quickshop = plugin; - break; - } catch (InvalidDescriptionException e) { //Ignore } - } - - } - if (quickshop == null) - throw new RuntimeException("Failed to get QuickShop Jar File."); - OutputStream outputStream = new FileOutputStream(quickshop, false); - outputStream.write(data); - outputStream.flush(); - outputStream.close(); - } - public static byte[] downloadUpdatedJar() throws IOException { org.kohsuke.github.GHRelease ghRelease = GitHub.connectAnonymously().getUser("Ghost-chu") .getRepository("QuickShop-Reremake").getLatestRelease(); @@ -122,4 +92,34 @@ public class Updater { Util.debugLog("Download complete."); return os.toByteArray(); } + + public static void replaceTheJar(byte[] data) throws RuntimeException, IOException { + File pluginFolder = new File("plugins"); + if (!pluginFolder.exists()) + throw new RuntimeException("Can't find the plugins folder."); + if (!pluginFolder.isDirectory()) + throw new RuntimeException("Plugins not a folder."); + File[] plugins = pluginFolder.listFiles(); + if (plugins == null) + throw new IOException("Can't get the files in plugins folder"); + File quickshop = null; + for (File plugin : plugins) { + try { + PluginDescriptionFile desc = QuickShop.instance.getPluginLoader().getPluginDescription(plugin); + if (!desc.getName().equals(QuickShop.instance.getDescription().getName())) + continue; + Util.debugLog("Selected: " + plugin.getPath()); + quickshop = plugin; + break; + } catch (InvalidDescriptionException e) { //Ignore } + } + + } + if (quickshop == null) + throw new RuntimeException("Failed to get QuickShop Jar File."); + OutputStream outputStream = new FileOutputStream(quickshop, false); + outputStream.write(data); + outputStream.flush(); + outputStream.close(); + } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Util.java b/src/main/java/org/maxgamer/quickshop/Util/Util.java index 1e10ccc2f..7cc6134df 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Util.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Util.java @@ -38,12 +38,453 @@ import org.maxgamer.quickshop.Watcher.InventoryEditContainer; @SuppressWarnings("WeakerAccess") public class Util { private static EnumSet blacklist = EnumSet.noneOf(Material.class); - private static EnumSet shoppables = EnumSet.noneOf(Material.class); - private static EnumMap> restrictedPrices = new EnumMap<>(Material.class); - private static List worldBlacklist = new ArrayList<>(); @Getter private static List debugLogs = new ArrayList<>(); - private static QuickShop plugin; private static boolean devMode; + private static QuickShop plugin; + private static EnumMap> restrictedPrices = new EnumMap<>(Material.class); + private static Object serverInstance; + private static EnumSet shoppables = EnumSet.noneOf(Material.class); + private static Field tpsField; + private static List worldBlacklist = new ArrayList<>(); + + /** + * Convert strArray to String. + * E.g "Foo, Bar" + * + * @param strArray Target array + * @return str + */ + public static String array2String(@NotNull String[] strArray) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < strArray.length; i++) { + builder.append(strArray[i]); + if (i + 1 != strArray.length) + builder.append(", "); + } + return builder.toString(); + } + + /** + * Backup shops.db + * + * @return The result for backup + */ + public static boolean backupDatabase() { + if (plugin.getDatabase().getCore() instanceof MySQLCore) + return true; //Backup and logs by MySQL + File dataFolder = plugin.getDataFolder(); + File sqlfile = new File(dataFolder, "shop.db"); + if (!sqlfile.exists()) { + plugin.getLogger().warning("Failed to backup! (File not found)"); + return false; + } + String uuid = UUID.randomUUID().toString().replaceAll("_", ""); + File bksqlfile = new File(dataFolder, "/shop_backup_" + uuid + ".db"); + try { + Files.copy(sqlfile, bksqlfile); + } catch (Exception e1) { + e1.printStackTrace(); + plugin.getLogger().warning("Failed to backup the database."); + return false; + } + return true; + } + + /** + * 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(@NotNull Block b) { + BlockState bs = b.getState(); + if ((!(bs instanceof InventoryHolder)) && b.getType() != Material.ENDER_CHEST) { + return false; + } + if (b.getType() == Material.ENDER_CHEST) { + if (plugin.getOpenInvPlugin() == null) { + return false; + } + } + if (!isShoppables(b.getType())) + return false; + //noinspection RedundantIfStatement + if (isBlacklistWorld(b.getWorld())) + return false; + return true; + + } + + /** + * 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(@Nullable Inventory inv, @NotNull ItemStack item) { + if (inv == null) + return 0; + int items = 0; + for (ItemStack iStack : inv.getStorageContents()) { + //noinspection ConstantConditions + if (iStack == null) + continue; + if (plugin.getItemMatcher().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(@Nullable Inventory inv, @NotNull ItemStack item) { + if (inv == null) + return 0; + int space = 0; + + ItemStack[] contents = inv.getStorageContents(); + for (ItemStack iStack : contents) { + //noinspection ConstantConditions + if (iStack == null || iStack.getType() == Material.AIR) { + space += item.getMaxStackSize(); + } else if (plugin.getItemMatcher().matches(item, iStack)) { + space += item.getMaxStackSize() - iStack.getAmount(); + } + } + return space; + } + + /** + * Print debug log when plugin running on dev mode. + * + * @param logs logs + */ + public static void debugLog(@NotNull String... logs) { + + String className = Thread.currentThread().getStackTrace()[2].getClassName(); + try { + Class c = Class.forName(className); + className = c.getSimpleName(); + if (!c.getSimpleName().isEmpty()) + className = c.getSimpleName(); + } catch (ClassNotFoundException e) { + //Ignore + } + String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); + int codeLine = Thread.currentThread().getStackTrace()[2].getLineNumber(); + + for (String log : logs) { + String text = "[DEBUG] [" + className + "]" + " [" + methodName + "] (" + codeLine + ") " + log; + debugLogs.add(text); + if (debugLogs.size() > 5000) /* Keep debugLogs max can have 5k lines. */ + debugLogs.remove(0); + if (!devMode) + return; + plugin.getLogger().info(text); + } + } + + /** + * Covert YAML string to ItemStack. + * + * @param config serialized ItemStack + * @return ItemStack iStack + * @throws InvalidConfigurationException when failed deserialize config + */ + public static ItemStack deserialize(@NotNull String config) throws InvalidConfigurationException { + YamlConfiguration cfg = new YamlConfiguration(); + cfg.loadFromString(config); + cfg.getString("item"); + return cfg.getItemStack("item"); + } + + /** + * Check two location is or not equals for the BlockPosition on 2D + * + * @param b1 block 1 + * @param b2 block 2 + * @return Equals or not. + */ + private static boolean equalsBlockStateLocation(@NotNull Location b1, @NotNull Location b2) { + return (b1.getBlockX() == b2.getBlockX()) && (b1.getBlockY() == b2.getBlockY()) && (b1.getBlockZ() == b2 + .getBlockZ()) && (b1.getWorld().getName().equals(b2.getWorld().getName())); + } + + /** + * First uppercase for every words the first char for a text. + * + * @param string text + * @return Processed text. + */ + public static String firstUppercase(@NotNull String string) { + if (string.length() > 1) { + return Character.toUpperCase(string.charAt(0)) + string.substring(1).toLowerCase(); + } else { + return string.toUpperCase(); + } + } + + /** + * Formats the given number according to how vault would like it. E.g. $50 or 5 + * dollars. + * + * @param n price + * @return The formatted string. + */ + public static String format(double n) { + if (plugin.getConfig().getBoolean("shop.disable-vault-format")) { + return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + } + try { + String formated = plugin.getEconomy().format(n); + if (formated == null || formated.isEmpty()) { + Util.debugLog("Use alternate-currency-symbol to formatting, Cause economy plugin returned null"); + return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + } else { + return formated; + } + } catch (NumberFormatException e) { + Util.debugLog("format", e.getMessage()); + Util.debugLog("format", "Use alternate-currency-symbol to formatting, Cause NumberFormatException"); + return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + } + } + + /** + * Fetches the block which the given sign is attached to + * + * @param b The block which is attached + * @return The block the sign is attached to + */ + public static Block getAttached(@NotNull Block b) { + try { + if (b.getBlockData() instanceof Directional) { + Directional directional = (Directional) b.getBlockData(); + return b.getRelative(directional.getFacing().getOppositeFace()); + } else { + return null; + } + // sometimes?? + } catch (NullPointerException | ClassCastException e) { + Util.debugLog("Exception caughted: " + e.getMessage()); + return null; // /Not sure what causes this. + } + } + + /** + * Return the Class name. + */ + public static String getClassPrefix(Class c) { + String callClassName = Thread.currentThread().getStackTrace()[2].getClassName(); + String customClassName = c.getSimpleName(); + return "[" + callClassName + "-" + customClassName + "] "; + } + + public static String getItemStackName(@NotNull ItemStack itemStack) { + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName()) + return itemStack.getItemMeta().getDisplayName(); + return MsgUtil.getItemi18n(itemStack.getType().name()); + } + + /** + * Get ItemStack's local name, return null if failed to get. + * + * @param itemStack Target ItemStack + * @return LocalName or NULL + */ + public static String getLocalizedName(@NotNull ItemStack itemStack) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta == null) + return null; + if (!itemMeta.hasLocalizedName()) + return null; + return itemMeta.getLocalizedName(); + } + + public static Class getNMSClass(@Nullable String className) { + if (className == null) + className = "MinecraftServer"; + String name = Bukkit.getServer().getClass().getPackage().getName(); + String version = name.substring(name.lastIndexOf('.') + 1); + try { + return Class.forName("net.minecraft.server." + version + "." + className); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + /** + * @param iStack itemstack + * @return potion data, readable + */ + public static String getPotiondata(@NotNull ItemStack iStack) { + if ((iStack.getType() != Material.POTION) && (iStack.getType() != Material.LINGERING_POTION) && (iStack + .getType() != Material.SPLASH_POTION)) { + return null; + } + List pEffects = new ArrayList(); + PotionMeta pMeta = (PotionMeta) iStack.getItemMeta(); + //if (pMeta.getBasePotionData().getType() != null) { + if (!(pMeta.getBasePotionData().isUpgraded())) { + pEffects.add(ChatColor.BLUE + MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType())); + } else { + pEffects.add(ChatColor.BLUE + MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType()) + " II"); + } + + //} + if (pMeta.hasCustomEffects()) { + List cEffects = pMeta.getCustomEffects(); + for (PotionEffect potionEffect : cEffects) { + pEffects.add(MsgUtil.getPotioni18n(potionEffect.getType()) + " " + RomanNumber + .toRoman(potionEffect.getAmplifier())); + } + } + if (!pEffects.isEmpty()) { + StringBuilder result = new StringBuilder(); + for (String effectString : pEffects) { + result.append(effectString); + result.append("\n"); + } + return result.toString(); + } else { + return null; + } + } + + /** + * Return an entry with min and max prices, but null if there isn't a price restriction + * + * @param material mat + * @return min, max + */ + public static Entry getPriceRestriction(@NotNull Material material) { + return restrictedPrices.get(material); + } + + /** + * 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(@NotNull Block b) { + if (!isDoubleChest(b)) { + Util.debugLog("Target block not a DoubleChest, ignored."); + return null; + } + Chest oneSideOfChest = (Chest) b.getState(); + InventoryHolder chestHolder = oneSideOfChest.getInventory().getHolder(); + if (chestHolder instanceof DoubleChest) { + DoubleChest doubleChest = (DoubleChest) chestHolder; + InventoryHolder left = doubleChest.getLeftSide(); + InventoryHolder right = doubleChest.getRightSide(); + Chest leftC = (Chest) left; + Chest rightC = (Chest) right; + if (equalsBlockStateLocation(oneSideOfChest.getLocation(), rightC.getLocation())) { + Util.debugLog("The left side of the chest was found."); + return leftC.getBlock(); + } + if (equalsBlockStateLocation(oneSideOfChest.getLocation(), leftC.getLocation())) { + Util.debugLog("The right side of the chest was found."); + return rightC.getBlock(); + } + Util.debugLog("Bug detected, DoubleChest holder can't find the any one side chest."); + return null; + } else { + Util.debugLog("ChestHolder not a DoubleChest holder."); + return null; + } + } + + /** + * Returns the chest attached to the given chest. The given block must be a + * chest. + * + * @param b he chest to check. + * @return the block which is also a chest and connected to b. + * @deprecated + */ + @Deprecated + public static Block getSecondHalf_old(@NotNull Block b) { + // if (b.getType() != Material.CHEST && b.getType() != Material.TRAPPED_CHEST) + // // return null; + if (!isDoubleChest(b)) + return null; + 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 (Block c : blocks) { + if (c.getType() == b.getType()) { + return c; + } + } + return null; + } + + /** + * Get how many shop in the target world. + * + * @param worldName Target world. + * @return The shops. + */ + public static int getShopsInWorld(@NotNull String worldName) { + int cost = 0; + Iterator iterator = plugin.getShopManager().getShopIterator(); + while (iterator.hasNext()) { + Shop shop = iterator.next(); + if (shop.getLocation().getWorld().getName().equals(worldName)) { + cost++; + } + } + return cost; + } + + /** + * 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(@NotNull ItemStack item) { + if (!(item.getItemMeta() instanceof Damageable)) { + Util.debugLog(item.getType().name() + " not Damageable."); + return "Error: NaN"; + } + double dura = ((Damageable) item.getItemMeta()).getDamage(); + double max = item.getType().getMaxDurability(); + DecimalFormat formatter = new DecimalFormat("0"); + return formatter.format((1 - dura / max) * 100.0); + } + + /** + * Use yaw to calc the BlockFace + * + * @param yaw Yaw (Player.getLocation().getYaw()) + * @return BlockFace blockFace + */ + public static BlockFace getYawFace(float yaw) { + if (yaw > 315 && yaw <= 45) { + return BlockFace.NORTH; + } else if (yaw > 45 && yaw <= 135) { + return BlockFace.EAST; + } else if (yaw > 135 && yaw <= 225) { + return BlockFace.SOUTH; + } else { + return BlockFace.WEST; + } + } /** * Initialize the Util tools. @@ -101,109 +542,89 @@ public class Util { } /** - * Match the map1 and map2 + * Read the InputStream to the byte array. * - * @param map1 Map1 - * @param map2 Map2 - * @return Map1 match Map2 + * @param filePath Target file + * @return Byte array */ - public static boolean mapMatches(@NotNull Map map1, @NotNull Map map2) { - for (Object obj : map1.keySet()) { - if (!map2.containsKey(obj)) - return false; - if (map1.get(obj) != map2.get(obj)) - return false; + public static byte[] inputStream2ByteArray(@NotNull String filePath) { + try { + InputStream in = new FileInputStream(filePath); + byte[] data = toByteArray(in); + in.close(); + return data; + } catch (IOException e) { + return null; } - return true; + } /** - * Match the both map1 and map2 + * Read the InputStream to the byte array. * - * @param map1 Map1 - * @param map2 Map2 - * @return Map1 match Map2 and Map2 match Map1 + * @param inputStream Target stream + * @return Byte array */ - public static boolean mapDuoMatches(@NotNull Map map1, @NotNull Map map2) { - boolean result = mapMatches(map1, map2); - if (!result) - return false; - return mapMatches(map2, map1); + public static byte[] inputStream2ByteArray(@NotNull InputStream inputStream) { + try { + byte[] data = toByteArray(inputStream); + inputStream.close(); + return data; + } catch (IOException e) { + return null; + } + } /** - * Return an entry with min and max prices, but null if there isn't a price restriction + * Call this to check items in inventory and remove it. * - * @param material mat - * @return min, max + * @param inv inv */ - public static Entry getPriceRestriction(@NotNull Material material) { - return restrictedPrices.get(material); - } - - /** - * Check a material is possible become a shop - * - * @param material Mat - * @return Can or not - */ - public static boolean isShoppables(@NotNull Material material) { - return shoppables.contains(material); - } - - /** - * Parse colors for the YamlConfiguration. - * - * @param config yaml config - */ - public static void parseColours(@NotNull YamlConfiguration config) { - Set keys = config.getKeys(true); - for (String key : keys) { - String filtered = config.getString(key); - if (filtered == null) - continue; - if (filtered.startsWith("MemorySection")) { - continue; + public static void inventoryCheck(@Nullable Inventory inv) { + if (inv == null) + return; + new BukkitRunnable() { + @Override + public void run() { + try { + for (int i = 0; i < inv.getSize(); i++) { + ItemStack itemStack = inv.getItem(i); + if (itemStack == null) + continue; + if (DisplayItem.checkIsGuardItemStack(itemStack)) { + // Found Item and remove it. + plugin.getSyncTaskWatcher().getInventoryEditQueue() + .offer(new InventoryEditContainer(inv, i, new ItemStack(Material.AIR, 0))); + Util.debugLog("Found a displayitem in an inventory, Scheduling to removeal..."); + String locationS = "Unknown (Plugin GUI?)"; + Location location = inv.getLocation(); + if (location != null) + locationS = location.toString(); + MsgUtil.sendGlobalAlert("[InventoryCheck] Found displayItem in inventory at " + locationS + ", Item is " + itemStack + .getType().name()); + } + } + } catch (Throwable t) { + //Ignore + } } - filtered = ChatColor.translateAlternateColorCodes('&', filtered); - config.set(key, filtered); - } + }.runTaskAsynchronously(plugin); } - /** - * Parse colors for the Text. - * - * @param text the text - * @return parsed text - */ - public static String parseColours(@NotNull String text) { - text = ChatColor.translateAlternateColorCodes('&', text); - return text; - } - - /** - * 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(@NotNull Block b) { - BlockState bs = b.getState(); - if ((!(bs instanceof InventoryHolder)) && b.getType() != Material.ENDER_CHEST) { - return false; + public static boolean isAir(@NotNull Material mat) { + if (mat == Material.AIR) + return true; + /* For 1.13 new AIR */ + try { + if (mat == Material.CAVE_AIR) + return true; + if (mat == Material.VOID_AIR) + return true; + } catch (Throwable t) { + //ignore } - if (b.getType() == Material.ENDER_CHEST) { - if (plugin.getOpenInvPlugin() == null) { - return false; - } - } - if (!isShoppables(b.getType())) - return false; - //noinspection RedundantIfStatement - if (isBlacklistWorld(b.getWorld())) - return false; - return true; - + return false; } public static boolean isBlacklistWorld(@NotNull World world) { @@ -211,95 +632,64 @@ public class Util { } /** - * 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) + * @param m The material to check if it is blacklisted + * @return true if the material is black listed. False if not. */ - public static String getToolPercentage(@NotNull ItemStack item) { - if (!(item.getItemMeta() instanceof Damageable)) { - Util.debugLog(item.getType().name() + " not Damageable."); - return "Error: NaN"; - } - double dura = ((Damageable) item.getItemMeta()).getDamage(); - double max = item.getType().getMaxDurability(); - DecimalFormat formatter = new DecimalFormat("0"); - return formatter.format((1 - dura / max) * 100.0); + public static boolean isBlacklisted(@NotNull Material m) { + return blacklist.contains(m); } /** - * Returns the chest attached to the given chest. The given block must be a - * chest. + * Get this class available or not * - * @param b he chest to check. - * @return the block which is also a chest and connected to b. - * @deprecated + * @param qualifiedName class qualifiedName + * @return boolean Available */ - @Deprecated - public static Block getSecondHalf_old(@NotNull Block b) { - // if (b.getType() != Material.CHEST && b.getType() != Material.TRAPPED_CHEST) - // // return null; - if (!isDoubleChest(b)) - return null; - 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 (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(@NotNull Block b) { - if (!isDoubleChest(b)) { - Util.debugLog("Target block not a DoubleChest, ignored."); - return null; - } - Chest oneSideOfChest = (Chest) b.getState(); - InventoryHolder chestHolder = oneSideOfChest.getInventory().getHolder(); - if (chestHolder instanceof DoubleChest) { - DoubleChest doubleChest = (DoubleChest) chestHolder; - InventoryHolder left = doubleChest.getLeftSide(); - InventoryHolder right = doubleChest.getRightSide(); - Chest leftC = (Chest) left; - Chest rightC = (Chest) right; - if (equalsBlockStateLocation(oneSideOfChest.getLocation(), rightC.getLocation())) { - Util.debugLog("The left side of the chest was found."); - return leftC.getBlock(); - } - if (equalsBlockStateLocation(oneSideOfChest.getLocation(), leftC.getLocation())) { - Util.debugLog("The right side of the chest was found."); - return rightC.getBlock(); - } - Util.debugLog("Bug detected, DoubleChest holder can't find the any one side chest."); - return null; - } else { - Util.debugLog("ChestHolder not a DoubleChest holder."); - return null; + public static boolean isClassAvailable(@NotNull String qualifiedName) { + try { + Class.forName(qualifiedName); + return true; + } catch (ClassNotFoundException e) { + return false; } } + public static boolean isDisplayAllowBlock(@NotNull Material mat) { + if (isAir(mat)) + return true; + return isWallSign(mat); + } + + public static boolean isDoubleChest(@Nullable Block b) { + if (b == null) { + Util.debugLog("The block is NULL."); + return false; + } + if (!(b.getState() instanceof Container)) { + Util.debugLog("Target block not a Container."); + return false; + } + Container container = (Container) b.getState(); + return (container.getInventory() instanceof DoubleChestInventory); + } + /** - * Check two location is or not equals for the BlockPosition on 2D + * Returns true if the given location is loaded or not. * - * @param b1 block 1 - * @param b2 block 2 - * @return Equals or not. + * @param loc The location + * @return true if the given location is loaded or not. */ - private static boolean equalsBlockStateLocation(@NotNull Location b1, @NotNull Location b2) { - return (b1.getBlockX() == b2.getBlockX()) && (b1.getBlockY() == b2.getBlockY()) && (b1.getBlockZ() == b2 - .getBlockZ()) && (b1.getWorld().getName().equals(b2.getWorld().getName())); + public static boolean isLoaded(@NotNull Location loc) { + // plugin.getLogger().log(Level.WARNING, "Checking isLoaded(Location loc)"); + if (loc.getWorld() == null) { + // plugin.getLogger().log(Level.WARNING, "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. + int x = (int) Math.floor((loc.getBlockX()) / 16.0); + int z = (int) Math.floor((loc.getBlockZ()) / 16.0); + return (loc.getWorld().isChunkLoaded(x, z)); } /** @@ -333,79 +723,13 @@ public class Util { } /** - * Covert ItemStack to YAML string. + * Check a material is possible become a shop * - * @param iStack target ItemStack - * @return String serialized itemStack + * @param material Mat + * @return Can or not */ - public static String serialize(@NotNull ItemStack iStack) { - YamlConfiguration cfg = new YamlConfiguration(); - cfg.set("item", iStack); - return cfg.saveToString(); - } - - /** - * Covert YAML string to ItemStack. - * - * @param config serialized ItemStack - * @return ItemStack iStack - * @throws InvalidConfigurationException when failed deserialize config - */ - public static ItemStack deserialize(@NotNull String config) throws InvalidConfigurationException { - YamlConfiguration cfg = new YamlConfiguration(); - cfg.loadFromString(config); - cfg.getString("item"); - return cfg.getItemStack("item"); - } - - /** - * Converts a name like IRON_INGOT into Iron Ingot to improve readability - * - * @param ugly The string such as IRON_INGOT - * @return A nicer version, such as Iron Ingot - */ - public static String prettifyText(@NotNull String ugly) { - String[] nameParts = ugly.split("_"); - if (nameParts.length == 1) { - return firstUppercase(ugly); - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < nameParts.length; i++) { - sb.append(firstUppercase(nameParts[i])); - if (i + 1 != nameParts.length) - sb.append(" "); - - } - return sb.toString(); - } - - /** - * Get ItemStack's local name, return null if failed to get. - * - * @param itemStack Target ItemStack - * @return LocalName or NULL - */ - public static String getLocalizedName(@NotNull ItemStack itemStack) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta == null) - return null; - if (!itemMeta.hasLocalizedName()) - return null; - return itemMeta.getLocalizedName(); - } - - /** - * First uppercase for every words the first char for a text. - * - * @param string text - * @return Processed text. - */ - public static String firstUppercase(@NotNull String string) { - if (string.length() > 1) { - return Character.toUpperCase(string.charAt(0)) + string.substring(1).toLowerCase(); - } else { - return string.toUpperCase(); - } + public static boolean isShoppables(@NotNull Material material) { + return shoppables.contains(material); } /** @@ -418,108 +742,24 @@ public class Util { } /** - * Formats the given number according to how vault would like it. E.g. $50 or 5 - * dollars. + * Check a string is or not a UUID string * - * @param n price - * @return The formatted string. + * @param string Target string + * @return is UUID */ - public static String format(double n) { - if (plugin.getConfig().getBoolean("shop.disable-vault-format")) { - return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; - } + public static boolean isUUID(@NotNull String string) { + if (string.length() != 36 && string.length() != 32) + return false; + Util.debugLog("Run an extra uuid check for " + string + ". Length: " + string.length()); try { - String formated = plugin.getEconomy().format(n); - if (formated == null || formated.isEmpty()) { - Util.debugLog("Use alternate-currency-symbol to formatting, Cause economy plugin returned null"); - return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; - } else { - return formated; - } - } catch (NumberFormatException e) { - Util.debugLog("format", e.getMessage()); - Util.debugLog("format", "Use alternate-currency-symbol to formatting, Cause NumberFormatException"); - return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + //noinspection ResultOfMethodCallIgnored + UUID.fromString(string); + return true; + } catch (IllegalArgumentException e) { + return false; } } - /** - * @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(@NotNull Material m) { - return blacklist.contains(m); - } - - /** - * Fetches the block which the given sign is attached to - * - * @param b The block which is attached - * @return The block the sign is attached to - */ - public static Block getAttached(@NotNull Block b) { - try { - if (b.getBlockData() instanceof Directional) { - Directional directional = (Directional) b.getBlockData(); - return b.getRelative(directional.getFacing().getOppositeFace()); - } else { - return null; - } - // sometimes?? - } catch (NullPointerException | ClassCastException e) { - Util.debugLog("Exception caughted: " + e.getMessage()); - return null; // /Not sure what causes this. - } - } - - /** - * 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(@Nullable Inventory inv, @NotNull ItemStack item) { - if (inv == null) - return 0; - int items = 0; - for (ItemStack iStack : inv.getStorageContents()) { - //noinspection ConstantConditions - if (iStack == null) - continue; - if (plugin.getItemMatcher().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(@Nullable Inventory inv, @NotNull ItemStack item) { - if (inv == null) - return 0; - int space = 0; - - ItemStack[] contents = inv.getStorageContents(); - for (ItemStack iStack : contents) { - //noinspection ConstantConditions - if (iStack == null || iStack.getType() == Material.AIR) { - space += item.getMaxStackSize(); - } else if (plugin.getItemMatcher().matches(item, iStack)) { - space += item.getMaxStackSize() - iStack.getAmount(); - } - } - return space; - } - /** * Check a material is or not a WALL_SIGN * @@ -536,6 +776,23 @@ public class Util { } } + /** + * Convert strList to String. + * E.g "Foo, Bar" + * + * @param strList Target list + * @return str + */ + public static String list2String(@NotNull List strList) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < strList.size(); i++) { + builder.append(strList.get(i)); + if (i + 1 != strList.size()) + builder.append(", "); + } + return builder.toString(); + } + /** * Returns loc with modified pitch/yaw angles so it faces lookat * @@ -575,302 +832,85 @@ public class Util { } /** - * Returns true if the given location is loaded or not. + * Match the both map1 and map2 * - * @param loc The location - * @return true if the given location is loaded or not. + * @param map1 Map1 + * @param map2 Map2 + * @return Map1 match Map2 and Map2 match Map1 */ - public static boolean isLoaded(@NotNull Location loc) { - // plugin.getLogger().log(Level.WARNING, "Checking isLoaded(Location loc)"); - if (loc.getWorld() == null) { - // plugin.getLogger().log(Level.WARNING, "Is not loaded. (No world)"); + public static boolean mapDuoMatches(@NotNull Map map1, @NotNull Map map2) { + boolean result = mapMatches(map1, map2); + if (!result) return false; - } - // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT - // location rounded to the nearest 16. - int x = (int) Math.floor((loc.getBlockX()) / 16.0); - int z = (int) Math.floor((loc.getBlockZ()) / 16.0); - return (loc.getWorld().isChunkLoaded(x, z)); + return mapMatches(map2, map1); } /** - * Use yaw to calc the BlockFace + * Match the map1 and map2 * - * @param yaw Yaw (Player.getLocation().getYaw()) - * @return BlockFace blockFace + * @param map1 Map1 + * @param map2 Map2 + * @return Map1 match Map2 */ - public static BlockFace getYawFace(float yaw) { - if (yaw > 315 && yaw <= 45) { - return BlockFace.NORTH; - } else if (yaw > 45 && yaw <= 135) { - return BlockFace.EAST; - } else if (yaw > 135 && yaw <= 225) { - return BlockFace.SOUTH; - } else { - return BlockFace.WEST; + public static boolean mapMatches(@NotNull Map map1, @NotNull Map map2) { + for (Object obj : map1.keySet()) { + if (!map2.containsKey(obj)) + return false; + if (map1.get(obj) != map2.get(obj)) + return false; } + return true; } /** - * Get this class available or not + * Parse colors for the YamlConfiguration. * - * @param qualifiedName class qualifiedName - * @return boolean Available + * @param config yaml config */ - public static boolean isClassAvailable(@NotNull String qualifiedName) { - try { - Class.forName(qualifiedName); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - /** - * @param iStack itemstack - * @return potion data, readable - */ - public static String getPotiondata(@NotNull ItemStack iStack) { - if ((iStack.getType() != Material.POTION) && (iStack.getType() != Material.LINGERING_POTION) && (iStack - .getType() != Material.SPLASH_POTION)) { - return null; - } - List pEffects = new ArrayList(); - PotionMeta pMeta = (PotionMeta) iStack.getItemMeta(); - //if (pMeta.getBasePotionData().getType() != null) { - if (!(pMeta.getBasePotionData().isUpgraded())) { - pEffects.add(ChatColor.BLUE + MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType())); - } else { - pEffects.add(ChatColor.BLUE + MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType()) + " II"); - } - - //} - if (pMeta.hasCustomEffects()) { - List cEffects = pMeta.getCustomEffects(); - for (PotionEffect potionEffect : cEffects) { - pEffects.add(MsgUtil.getPotioni18n(potionEffect.getType()) + " " + RomanNumber - .toRoman(potionEffect.getAmplifier())); + public static void parseColours(@NotNull YamlConfiguration config) { + Set keys = config.getKeys(true); + for (String key : keys) { + String filtered = config.getString(key); + if (filtered == null) + continue; + if (filtered.startsWith("MemorySection")) { + continue; } - } - if (!pEffects.isEmpty()) { - StringBuilder result = new StringBuilder(); - for (String effectString : pEffects) { - result.append(effectString); - result.append("\n"); - } - return result.toString(); - } else { - return null; + filtered = ChatColor.translateAlternateColorCodes('&', filtered); + config.set(key, filtered); } } /** - * Send warning message when some plugin calling deprecated method... - * With the trace. - */ - public static void sendDeprecatedMethodWarn() { - QuickShop.instance.getLogger() - .warning("Some plugin is calling a Deprecated method, Please contact the author to tell them to use the new api!"); - StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - for (StackTraceElement stackTraceElement : stackTraceElements) { - QuickShop.instance.getLogger().warning("at " + stackTraceElement.getClassName() + "#" + stackTraceElement - .getMethodName() + " (" + stackTraceElement.getFileName() + ":" + stackTraceElement.getLineNumber() + ")"); - } - } - - /** - * Check QuickShop is running on dev edition or not. + * Parse colors for the Text. * - * @return DevEdition status + * @param text the text + * @return parsed text */ - public static boolean isDevEdition() { - String version = QuickShop.instance.getDescription().getVersion().toLowerCase(); - return (version.contains("dev") || - version.contains("develop") || - version.contains("alpha") || - version.contains("beta") || - version.contains("test") || - version.contains("snapshot") || - version.contains("preview")); + public static String parseColours(@NotNull String text) { + text = ChatColor.translateAlternateColorCodes('&', text); + return text; } /** - * Call this to check items in inventory and remove it. + * Converts a name like IRON_INGOT into Iron Ingot to improve readability * - * @param inv inv + * @param ugly The string such as IRON_INGOT + * @return A nicer version, such as Iron Ingot */ - public static void inventoryCheck(@Nullable Inventory inv) { - if (inv == null) - return; - new BukkitRunnable() { - @Override - public void run() { - try { - for (int i = 0; i < inv.getSize(); i++) { - ItemStack itemStack = inv.getItem(i); - if (itemStack == null) - continue; - if (DisplayItem.checkIsGuardItemStack(itemStack)) { - // Found Item and remove it. - plugin.getSyncTaskWatcher().getInventoryEditQueue() - .offer(new InventoryEditContainer(inv, i, new ItemStack(Material.AIR, 0))); - Util.debugLog("Found a displayitem in an inventory, Scheduling to removeal..."); - String locationS = "Unknown (Plugin GUI?)"; - Location location = inv.getLocation(); - if (location != null) - locationS = location.toString(); - MsgUtil.sendGlobalAlert("[InventoryCheck] Found displayItem in inventory at " + locationS + ", Item is " + itemStack - .getType().name()); - } - } - } catch (Throwable t) { - //Ignore - } - } - }.runTaskAsynchronously(plugin); - } - - public static String getItemStackName(@NotNull ItemStack itemStack) { - if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName()) - return itemStack.getItemMeta().getDisplayName(); - return MsgUtil.getItemi18n(itemStack.getType().name()); - } - - private static Object serverInstance; - private static Field tpsField; - - /** - * Get MinecraftServer's TPS - * - * @return TPS (e.g 19.92) - */ - public static Double getTPS() { - try { - serverInstance = getNMSClass("MinecraftServer").getMethod("getServer").invoke(null); - tpsField = serverInstance.getClass().getField("recentTps"); - } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException e) { - e.printStackTrace(); + public static String prettifyText(@NotNull String ugly) { + String[] nameParts = ugly.split("_"); + if (nameParts.length == 1) { + return firstUppercase(ugly); } - try { - double[] tps = ((double[]) tpsField.get(serverInstance)); - return tps[0]; - } catch (IllegalAccessException e) { - throw new RuntimeException(e); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < nameParts.length; i++) { + sb.append(firstUppercase(nameParts[i])); + if (i + 1 != nameParts.length) + sb.append(" "); + } - - } - - public static Class getNMSClass(@Nullable String className) { - if (className == null) - className = "MinecraftServer"; - String name = Bukkit.getServer().getClass().getPackage().getName(); - String version = name.substring(name.lastIndexOf('.') + 1); - try { - return Class.forName("net.minecraft.server." + version + "." + className); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - - public static String getNMSVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - return name.substring(name.lastIndexOf('.') + 1); - } - - public static boolean isAir(@NotNull Material mat) { - if (mat == Material.AIR) - return true; - /* For 1.13 new AIR */ - try { - if (mat == Material.CAVE_AIR) - return true; - if (mat == Material.VOID_AIR) - return true; - } catch (Throwable t) { - //ignore - } - return false; - } - - public static boolean isDisplayAllowBlock(@NotNull Material mat) { - if (isAir(mat)) - return true; - return isWallSign(mat); - } - - /** - * Print debug log when plugin running on dev mode. - * - * @param logs logs - */ - public static void debugLog(@NotNull String... logs) { - - String className = Thread.currentThread().getStackTrace()[2].getClassName(); - try { - Class c = Class.forName(className); - className = c.getSimpleName(); - if (!c.getSimpleName().isEmpty()) - className = c.getSimpleName(); - } catch (ClassNotFoundException e) { - //Ignore - } - String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); - int codeLine = Thread.currentThread().getStackTrace()[2].getLineNumber(); - - for (String log : logs) { - String text = "[DEBUG] [" + className + "]" + " [" + methodName + "] (" + codeLine + ") " + log; - debugLogs.add(text); - if (debugLogs.size() > 5000) /* Keep debugLogs max can have 5k lines. */ - debugLogs.remove(0); - if (!devMode) - return; - plugin.getLogger().info(text); - } - } - - /** - * Return the Class name. - */ - public static String getClassPrefix() { - - String className = Thread.currentThread().getStackTrace()[2].getClassName(); - try { - Class c = Class.forName(className); - className = c.getSimpleName(); - if (!c.getSimpleName().isEmpty()) - className = c.getSimpleName(); - } catch (ClassNotFoundException e) { - //Ignore - } - String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); - return "[" + className + "-" + methodName + "] "; - } - - /** - * Return the Class name. - */ - public static String getClassPrefix(Class c) { - String callClassName = Thread.currentThread().getStackTrace()[2].getClassName(); - String customClassName = c.getSimpleName(); - return "[" + callClassName + "-" + customClassName + "] "; - } - /** - * Get how many shop in the target world. - * - * @param worldName Target world. - * @return The shops. - */ - public static int getShopsInWorld(@NotNull String worldName) { - int cost = 0; - Iterator iterator = plugin.getShopManager().getShopIterator(); - while (iterator.hasNext()) { - Shop shop = iterator.next(); - if (shop.getLocation().getWorld().getName().equals(worldName)) { - cost++; - } - } - return cost; + return sb.toString(); } /** @@ -899,6 +939,66 @@ public class Util { } } + /** + * Send warning message when some plugin calling deprecated method... + * With the trace. + */ + public static void sendDeprecatedMethodWarn() { + QuickShop.instance.getLogger() + .warning("Some plugin is calling a Deprecated method, Please contact the author to tell them to use the new api!"); + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + for (StackTraceElement stackTraceElement : stackTraceElements) { + QuickShop.instance.getLogger().warning("at " + stackTraceElement.getClassName() + "#" + stackTraceElement + .getMethodName() + " (" + stackTraceElement.getFileName() + ":" + stackTraceElement.getLineNumber() + ")"); + } + } + + /** + * Covert ItemStack to YAML string. + * + * @param iStack target ItemStack + * @return String serialized itemStack + */ + public static String serialize(@NotNull ItemStack iStack) { + YamlConfiguration cfg = new YamlConfiguration(); + cfg.set("item", iStack); + return cfg.saveToString(); + } + + private static byte[] toByteArray(@NotNull InputStream in) throws IOException { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024 * 4]; + int n = 0; + while ((n = in.read(buffer)) != -1) { + out.write(buffer, 0, n); + } + return out.toByteArray(); + } + + /** + * Return the Class name. + */ + public static String getClassPrefix() { + + String className = Thread.currentThread().getStackTrace()[2].getClassName(); + try { + Class c = Class.forName(className); + className = c.getSimpleName(); + if (!c.getSimpleName().isEmpty()) + className = c.getSimpleName(); + } catch (ClassNotFoundException e) { + //Ignore + } + String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); + return "[" + className + "-" + methodName + "] "; + } + + public static String getNMSVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf('.') + 1); + } + /** * Get the sign material using by plugin. * With compatiabily process. @@ -929,129 +1029,26 @@ public class Util { } /** - * Read the InputStream to the byte array. + * Get MinecraftServer's TPS * - * @param filePath Target file - * @return Byte array + * @return TPS (e.g 19.92) */ - public static byte[] inputStream2ByteArray(@NotNull String filePath) { + public static Double getTPS() { try { - InputStream in = new FileInputStream(filePath); - byte[] data = toByteArray(in); - in.close(); - return data; - } catch (IOException e) { - return null; + serverInstance = getNMSClass("MinecraftServer").getMethod("getServer").invoke(null); + tpsField = serverInstance.getClass().getField("recentTps"); + } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException e) { + e.printStackTrace(); } - - } - - /** - * Read the InputStream to the byte array. - * - * @param inputStream Target stream - * @return Byte array - */ - public static byte[] inputStream2ByteArray(@NotNull InputStream inputStream) { try { - byte[] data = toByteArray(inputStream); - inputStream.close(); - return data; - } catch (IOException e) { - return null; + double[] tps = ((double[]) tpsField.get(serverInstance)); + return tps[0]; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); } } - - private static byte[] toByteArray(@NotNull InputStream in) throws IOException { - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024 * 4]; - int n = 0; - while ((n = in.read(buffer)) != -1) { - out.write(buffer, 0, n); - } - return out.toByteArray(); - } - - /** - * Backup shops.db - * - * @return The result for backup - */ - public static boolean backupDatabase() { - if (plugin.getDatabase().getCore() instanceof MySQLCore) - return true; //Backup and logs by MySQL - File dataFolder = plugin.getDataFolder(); - File sqlfile = new File(dataFolder, "shop.db"); - if (!sqlfile.exists()) { - plugin.getLogger().warning("Failed to backup! (File not found)"); - return false; - } - String uuid = UUID.randomUUID().toString().replaceAll("_", ""); - File bksqlfile = new File(dataFolder, "/shop_backup_" + uuid + ".db"); - try { - Files.copy(sqlfile, bksqlfile); - } catch (Exception e1) { - e1.printStackTrace(); - plugin.getLogger().warning("Failed to backup the database."); - return false; - } - return true; - } - - /** - * Convert strArray to String. - * E.g "Foo, Bar" - * - * @param strArray Target array - * @return str - */ - public static String array2String(@NotNull String[] strArray) { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < strArray.length; i++) { - builder.append(strArray[i]); - if (i + 1 != strArray.length) - builder.append(", "); - } - return builder.toString(); - } - - /** - * Convert strList to String. - * E.g "Foo, Bar" - * - * @param strList Target list - * @return str - */ - public static String list2String(@NotNull List strList) { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < strList.size(); i++) { - builder.append(strList.get(i)); - if (i + 1 != strList.size()) - builder.append(", "); - } - return builder.toString(); - } - - /** - * Check a string is or not a UUID string - * - * @param string Target string - * @return is UUID - */ - public static boolean isUUID(@NotNull String string) { - if (string.length() != 36 && string.length() != 32) - return false; - Util.debugLog("Run an extra uuid check for " + string + ". Length: " + string.length()); - try { - //noinspection ResultOfMethodCallIgnored - UUID.fromString(string); - return true; - } catch (IllegalArgumentException e) { - return false; - } - } // // public static void shoppablesCheck(@NotNull Shop shop) { // if (!Util.canBeShop(shop.getLocation().getBlock())) { @@ -1061,6 +1058,22 @@ public class Util { // } // } + /** + * Check QuickShop is running on dev edition or not. + * + * @return DevEdition status + */ + public static boolean isDevEdition() { + String version = QuickShop.instance.getDescription().getVersion().toLowerCase(); + return (version.contains("dev") || + version.contains("develop") || + version.contains("alpha") || + version.contains("beta") || + version.contains("test") || + version.contains("snapshot") || + version.contains("preview")); + } + /** * Get the plugin is under dev-mode(debug mode) * @@ -1069,17 +1082,4 @@ public class Util { public static boolean isDevMode() { return devMode; } - - public static boolean isDoubleChest(@Nullable Block b) { - if (b == null) { - Util.debugLog("The block is NULL."); - return false; - } - if (!(b.getState() instanceof Container)) { - Util.debugLog("Target block not a Container."); - return false; - } - Container container = (Container) b.getState(); - return (container.getInventory() instanceof DoubleChestInventory); - } } diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/DisplayWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/DisplayWatcher.java index e29bac817..0debd3401 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/DisplayWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/DisplayWatcher.java @@ -10,10 +10,23 @@ import org.maxgamer.quickshop.QuickShop; import org.maxgamer.quickshop.Shop.Shop; import org.maxgamer.quickshop.Util.Util; +class DisplayRunnable implements Runnable { + @Override + public void run() { + @SuppressWarnings("unchecked") ArrayList pendingCheckDisplayCopy = (ArrayList) QuickShop.instance + .getDisplayWatcher().getPendingCheckDisplay().clone(); + for (Shop shop : pendingCheckDisplayCopy) { + shop.checkDisplay(); + } + pendingCheckDisplayCopy.clear(); + QuickShop.instance.getDisplayWatcher().getPendingCheckDisplay().clear(); + } +} + @Data public class DisplayWatcher { - private QuickShop plugin; private ArrayList pendingCheckDisplay = new ArrayList<>(); + private QuickShop plugin; public DisplayWatcher(QuickShop plugin) { this.plugin = plugin; @@ -47,16 +60,3 @@ public class DisplayWatcher { } } - -class DisplayRunnable implements Runnable { - @Override - public void run() { - @SuppressWarnings("unchecked") ArrayList pendingCheckDisplayCopy = (ArrayList) QuickShop.instance - .getDisplayWatcher().getPendingCheckDisplay().clone(); - for (Shop shop : pendingCheckDisplayCopy) { - shop.checkDisplay(); - } - pendingCheckDisplayCopy.clear(); - QuickShop.instance.getDisplayWatcher().getPendingCheckDisplay().clear(); - } -} diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/LogWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/LogWatcher.java index 5cf05a50d..686f20b42 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/LogWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/LogWatcher.java @@ -13,8 +13,8 @@ import org.jetbrains.annotations.*; import org.maxgamer.quickshop.QuickShop; public class LogWatcher implements Runnable { - private PrintStream ps; private Queue logs = new LinkedList<>(); + private PrintStream ps; public LogWatcher(QuickShop plugin, File log) { try { @@ -32,6 +32,27 @@ public class LogWatcher implements Runnable { } } + public void add(@NotNull String s) { + new BukkitRunnable() { + public void run() { + logs.add(s); + } + }.runTask(QuickShop.instance); + + } + + public void close() { + if (ps != null) + this.ps.close(); + ps = null; + } + + public void log(@NonNull String log) { + Date date = Calendar.getInstance().getTime(); + Timestamp time = new Timestamp(date.getTime()); + this.add("[" + time.toString() + "] " + log); + } + @Override public void run() { new BukkitRunnable() { @@ -46,24 +67,4 @@ public class LogWatcher implements Runnable { } }.runTask(QuickShop.instance); } - - public void add(@NotNull String s) { - new BukkitRunnable() { - public void run() { - logs.add(s); - } - }.runTask(QuickShop.instance); - - } - public void close() { - if (ps != null) - this.ps.close(); - ps = null; - } - - public void log(@NonNull String log) { - Date date = Calendar.getInstance().getTime(); - Timestamp time = new Timestamp(date.getTime()); - this.add("[" + time.toString() + "] " + log); - } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/SyncTaskWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/SyncTaskWatcher.java index 2cff680d4..4491c1cca 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/SyncTaskWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/SyncTaskWatcher.java @@ -11,10 +11,10 @@ import org.bukkit.scheduler.BukkitRunnable; import org.maxgamer.quickshop.QuickShop; public class SyncTaskWatcher { - private QuickShop plugin; @Getter private Queue entityRemoveQueue = new LinkedList<>(); - @Getter private Queue itemStackRemoveQueue = new LinkedList<>(); @Getter private Queue inventoryEditQueue = new LinkedList<>(); + @Getter private Queue itemStackRemoveQueue = new LinkedList<>(); + private QuickShop plugin; /** * SyncTaskWatcher is a loop task runner, it can be add from async thread and run in Bukkit main thread. diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java index 2488bceaa..88f3452b8 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java @@ -1,137 +1,137 @@ -package org.maxgamer.quickshop.Watcher; - -import java.util.List; -import java.util.Random; - -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; -import org.jetbrains.annotations.*; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.UpdateInfomation; -import org.maxgamer.quickshop.Util.Updater; - -public class UpdateWatcher implements Listener { - private static BukkitTask cronTask = null; - private static boolean hasNewUpdate = false; - private static UpdateInfomation info = null; - - public static void init() { - cronTask = new BukkitRunnable() { - - @Override - public void run() { - info = Updater.checkUpdate(); - - if (info.getVersion() == null) { - hasNewUpdate = false; - return; - } - - if (info.getVersion().equals(QuickShop.getVersion())) { - hasNewUpdate = false; - return; - } - hasNewUpdate = true; - - if (!info.isBeta()) { - QuickShop.instance.getLogger().info("A new version of QuickShop has been released!"); - QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/"); - - Bukkit.getOnlinePlayers().forEach(player -> { - if (player.hasPermission("quickshop.alert")) { - List notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list"); - Random random = new Random(); - int notifyNum = -1; - if (notifys.size() > 1) - notifyNum = random.nextInt(notifys.size()); - String notify; - if (notifyNum > 0) { //Translate bug. - notify = notifys.get(notifyNum); - } else { - notify = "New update {0} now avaliable! Please update!"; - } - notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion()); - TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil - .getMessage("updatenotify.buttontitle")); - TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil - .getMessage("updatenotify.onekeybuttontitle")); - updatenow - .setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/")); - onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update")); - TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate); - player.sendMessage(ChatColor.GREEN + "---------------------------------------------------"); - player.sendMessage(ChatColor.GREEN + notify); - player.spigot().sendMessage(finallyText); - player.sendMessage(ChatColor.GREEN + "---------------------------------------------------"); - } - }); - } else { - QuickShop.instance.getLogger().info("A new BETA version of QuickShop is available!"); - QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/"); - QuickShop.instance.getLogger().info("This is a BETA version, which means you should use it with caution."); - } - - } - }.runTaskTimerAsynchronously(QuickShop.instance, 1, 20 * 60 * 60); - } - - public static void uninit() { - hasNewUpdate = false; - if (cronTask == null) { - return; - } - cronTask.cancel(); - } - - @EventHandler - public void playerJoin(PlayerJoinEvent e) { - new BukkitRunnable() { - @Override - public void run() { - if (hasNewUpdate && e.getPlayer().hasPermission("quickshop.alert")) { - if (!info.isBeta()) { - List notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list"); - Random random = new Random(); - int notifyNum = random.nextInt(notifys.size()); - String notify = notifys.get(notifyNum); - notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion()); - - TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil - .getMessage("updatenotify.buttontitle")); - TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil - .getMessage("updatenotify.onekeybuttontitle")); - updatenow - .setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/")); - onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update")); - TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate); - e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------"); - e.getPlayer().sendMessage(ChatColor.GREEN + notify); - e.getPlayer().spigot().sendMessage(finallyText); - e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------"); - } else { - e.getPlayer().sendMessage(ChatColor.GRAY + "A new BETA version of QuickShop has been released!"); - e.getPlayer().sendMessage(ChatColor.GRAY + "Update here: https://www.spigotmc.org/resources/62575/"); - e.getPlayer() - .sendMessage(ChatColor.GRAY + "This is a BETA version, which means you should use it with caution."); - } - } - - } - }.runTaskLater(QuickShop.instance, 80); - } - - public static String fixVer(@NotNull String originalVer) { - originalVer = originalVer.replaceAll("Reremake", ""); - originalVer = originalVer.trim(); - return originalVer; - } - -} +package org.maxgamer.quickshop.Watcher; + +import java.util.List; +import java.util.Random; + +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.*; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.UpdateInfomation; +import org.maxgamer.quickshop.Util.Updater; + +public class UpdateWatcher implements Listener { + private static BukkitTask cronTask = null; + private static boolean hasNewUpdate = false; + private static UpdateInfomation info = null; + + public static String fixVer(@NotNull String originalVer) { + originalVer = originalVer.replaceAll("Reremake", ""); + originalVer = originalVer.trim(); + return originalVer; + } + + public static void init() { + cronTask = new BukkitRunnable() { + + @Override + public void run() { + info = Updater.checkUpdate(); + + if (info.getVersion() == null) { + hasNewUpdate = false; + return; + } + + if (info.getVersion().equals(QuickShop.getVersion())) { + hasNewUpdate = false; + return; + } + hasNewUpdate = true; + + if (!info.isBeta()) { + QuickShop.instance.getLogger().info("A new version of QuickShop has been released!"); + QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/"); + + Bukkit.getOnlinePlayers().forEach(player -> { + if (player.hasPermission("quickshop.alert")) { + List notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list"); + Random random = new Random(); + int notifyNum = -1; + if (notifys.size() > 1) + notifyNum = random.nextInt(notifys.size()); + String notify; + if (notifyNum > 0) { //Translate bug. + notify = notifys.get(notifyNum); + } else { + notify = "New update {0} now avaliable! Please update!"; + } + notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion()); + TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil + .getMessage("updatenotify.buttontitle")); + TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil + .getMessage("updatenotify.onekeybuttontitle")); + updatenow + .setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/")); + onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update")); + TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate); + player.sendMessage(ChatColor.GREEN + "---------------------------------------------------"); + player.sendMessage(ChatColor.GREEN + notify); + player.spigot().sendMessage(finallyText); + player.sendMessage(ChatColor.GREEN + "---------------------------------------------------"); + } + }); + } else { + QuickShop.instance.getLogger().info("A new BETA version of QuickShop is available!"); + QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/"); + QuickShop.instance.getLogger().info("This is a BETA version, which means you should use it with caution."); + } + + } + }.runTaskTimerAsynchronously(QuickShop.instance, 1, 20 * 60 * 60); + } + + public static void uninit() { + hasNewUpdate = false; + if (cronTask == null) { + return; + } + cronTask.cancel(); + } + + @EventHandler + public void playerJoin(PlayerJoinEvent e) { + new BukkitRunnable() { + @Override + public void run() { + if (hasNewUpdate && e.getPlayer().hasPermission("quickshop.alert")) { + if (!info.isBeta()) { + List notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list"); + Random random = new Random(); + int notifyNum = random.nextInt(notifys.size()); + String notify = notifys.get(notifyNum); + notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion()); + + TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil + .getMessage("updatenotify.buttontitle")); + TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil + .getMessage("updatenotify.onekeybuttontitle")); + updatenow + .setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/")); + onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update")); + TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate); + e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------"); + e.getPlayer().sendMessage(ChatColor.GREEN + notify); + e.getPlayer().spigot().sendMessage(finallyText); + e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------"); + } else { + e.getPlayer().sendMessage(ChatColor.GRAY + "A new BETA version of QuickShop has been released!"); + e.getPlayer().sendMessage(ChatColor.GRAY + "Update here: https://www.spigotmc.org/resources/62575/"); + e.getPlayer() + .sendMessage(ChatColor.GRAY + "This is a BETA version, which means you should use it with caution."); + } + } + + } + }.runTaskLater(QuickShop.instance, 80); + } + +}