From adaeec4a9a6b9fb0930cd74da2cfb8a2aa17248e Mon Sep 17 00:00:00 2001 From: sandtechnology <20417547+sandtechnology@users.noreply.github.com> Date: Mon, 2 Mar 2020 18:36:04 +0800 Subject: [PATCH] Full async database operation Former-commit-id: 4c754ea13286919c902090b752f654b2fcc22a4e --- .../quickshop/Database/DatabaseHelper.java | 164 ++++++++++-------- .../quickshop/Database/DatabaseManager.java | 37 ++-- .../quickshop/Database/DatabaseTask.java | 21 +++ .../JsonConfiguration/JSONConfiguration.java | 4 +- .../SerializationHelper.java | 8 +- .../quickshop/Shop/ArmorStandDisplayItem.java | 1 - .../quickshop/Shop/ContainerShop.java | 6 +- .../maxgamer/quickshop/Shop/ShopLoader.java | 8 +- .../maxgamer/quickshop/Shop/ShopManager.java | 132 +++++++------- .../quickshop/Util/ChatSheetPrinter.java | 6 +- .../quickshop/Util/FunnyEasterEgg.java | 4 +- .../Util/Logger/QuickShopLogger.java | 4 +- 12 files changed, 198 insertions(+), 197 deletions(-) create mode 100644 src/main/java/org/maxgamer/quickshop/Database/DatabaseTask.java diff --git a/src/main/java/org/maxgamer/quickshop/Database/DatabaseHelper.java b/src/main/java/org/maxgamer/quickshop/Database/DatabaseHelper.java index 074b2e89b..7c7d7230a 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/DatabaseHelper.java +++ b/src/main/java/org/maxgamer/quickshop/Database/DatabaseHelper.java @@ -19,15 +19,20 @@ package org.maxgamer.quickshop.Database; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Shop.Shop; +import org.maxgamer.quickshop.Shop.ShopModerator; +import org.maxgamer.quickshop.Util.Util; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.UUID; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Util.Util; +import java.util.function.Consumer; /** * A Util to execute all SQLs. @@ -60,7 +65,7 @@ public class DatabaseHelper { try { // V3.4.2 ps = db.getConnection().prepareStatement("ALTER TABLE " + QuickShop.instance - .getDbPrefix() + "shops MODIFY COLUMN price double(32,2) NOT NULL AFTER owner"); + .getDbPrefix() + "shops MODIFY COLUMN price double(32,2) NOT NULL AFTER owner"); ps.execute(); ps.close(); } catch (SQLException e) { @@ -69,7 +74,7 @@ public class DatabaseHelper { try { // V3.4.3 ps = db.getConnection().prepareStatement("ALTER TABLE " + QuickShop.instance - .getDbPrefix() + "messages MODIFY COLUMN time BIGINT(32) NOT NULL AFTER message"); + .getDbPrefix() + "messages MODIFY COLUMN time BIGINT(32) NOT NULL AFTER message"); ps.execute(); ps.close(); } catch (SQLException e) { @@ -78,7 +83,7 @@ public class DatabaseHelper { if (QuickShop.instance.getDatabase().getCore() instanceof MySQLCore) { try { ps = db.getConnection().prepareStatement("ALTER TABLE " + QuickShop.instance - .getDbPrefix() + "messages MODIFY COLUMN message text CHARACTER SET utf8mb4 NOT NULL AFTER owner"); + .getDbPrefix() + "messages MODIFY COLUMN message text CHARACTER SET utf8mb4 NOT NULL AFTER owner"); ps.execute(); ps.close(); } catch (SQLException e) { @@ -89,28 +94,22 @@ public class DatabaseHelper { } public void cleanMessage(long weekAgo) { - try { + plugin.getDatabaseManager().add(() -> { //QuickShop.instance.getDB().execute("DELETE FROM " + QuickShop.instance // .getDbPrefix() + "messages WHERE time < ?", weekAgo); String sqlString = "DELETE FROM " + QuickShop.instance - .getDbPrefix() + "messages WHERE time < ?"; + .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 UUID player) { - try { + plugin.getDatabaseManager().add(() -> { 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(); - } + }); } /** @@ -122,31 +121,45 @@ public class DatabaseHelper { private boolean createMessagesTable() throws SQLException { Statement st = db.getConnection().createStatement(); String createTable = "CREATE TABLE " + QuickShop.instance.getDbPrefix() - + "messages (owner VARCHAR(255) NOT NULL, message TEXT(25) NOT NULL, time BIGINT(32) NOT NULL );"; + + "messages (owner VARCHAR(255) NOT NULL, message TEXT(25) NOT NULL, time BIGINT(32) NOT NULL );"; if (plugin.getDatabase().getCore() instanceof MySQLCore) { createTable = "CREATE TABLE " + QuickShop.instance.getDbPrefix() - + "messages (owner VARCHAR(255) NOT NULL, message TEXT(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL , time BIGINT(32) NOT NULL );"; + + "messages (owner VARCHAR(255) NOT NULL, message TEXT(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL , time BIGINT(32) NOT NULL );"; } return st.execute(createTable); } - public void createShop(@NotNull String owner, double price, @NotNull ItemStack item, int unlimited, int shopType, @NotNull String world, int x, int y, int z) - throws SQLException { - removeShop(x, y, z, world); //First purge old exist shop before create new shop. - 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 createShop(Shop shop, Runnable onSuccess, Consumer onFailed) { + plugin.getDatabaseManager().add(new DatabaseTask() { + @Override + public void execute() throws SQLException { + Location location = shop.getLocation(); + plugin.getDatabaseHelper().removeShop(shop); //First purge old exist shop before create new shop. + 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, ShopModerator.serialize(shop.getModerator())); + ps.setDouble(2, shop.getPrice()); + ps.setString(3, Util.serialize(shop.getItem())); + ps.setInt(4, location.getBlockX()); + ps.setInt(5, location.getBlockY()); + ps.setInt(6, location.getBlockZ()); + ps.setString(7, location.getWorld().getName()); + ps.setInt(8, shop.isUnlimited() ? 1 : 0); + ps.setInt(9, shop.getShopType().toID()); + } + + @Override + public void onSuccess() { + onSuccess.run(); + } + + @Override + public void onFailed(SQLException e) { + onFailed.accept(e); + } + }); } /** @@ -157,26 +170,27 @@ public class DatabaseHelper { private void createShopsTable() 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) );"; + .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(int x, int y, int z, @NotNull String worldName) throws SQLException { + public void removeShop(Shop shop) throws SQLException { // db.getConnection().createStatement() // .executeUpdate("DELETE FROM " + QuickShop.instance.getDbPrefix() + "shops WHERE x = " + x + " AND y = " + y // + " AND z = " + z + " AND world = \"" + worldName + "\"" // + (db.getCore() instanceof MySQLCore ? " LIMIT 1" : "")); - String sqlString = "DELETE FROM " + QuickShop.instance - .getDbPrefix() + "shops WHERE x = ? AND y = ? AND z = ? AND world = ?" + (db.getCore() instanceof MySQLCore ? - " LIMIT 1" : - ""); - + plugin.getDatabaseManager().add(() -> { String sqlString = "DELETE FROM " + QuickShop.instance + .getDbPrefix() + "shops WHERE x = ? AND y = ? AND z = ? AND world = ?" + (db.getCore() instanceof MySQLCore ? + " LIMIT 1" : + ""); + Location location = shop.getLocation(); PreparedStatement ps = db.getConnection().prepareStatement(sqlString); - ps.setInt(1, x); - ps.setInt(2, y); - ps.setInt(3, z); - ps.setString(4, worldName); - return ps.execute(); + ps.setInt(1, location.getBlockX()); + ps.setInt(2, location.getBlockY()); + ps.setInt(3, location.getBlockZ()); + ps.setString(4, location.getWorld().getName()); + }); + } public ResultSet selectAllMessages() throws SQLException { @@ -192,43 +206,42 @@ public class DatabaseHelper { } public void sendMessage(@NotNull UUID player, @NotNull String message, long time) { - try { + + plugin.getDatabaseManager().add(() -> { String sqlString = "INSERT INTO " + QuickShop.instance - .getDbPrefix() + "messages (owner, message, time) VALUES (?, ?, ?)"; + .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 String ownerUUID, int x, int y, int z, @NotNull String worldName) - throws SQLException { - //QuickShop.instance.getDB().getConnection().createStatement() - // .executeUpdate("UPDATE " + QuickShop.instance.getDbPrefix() + "shops SET owner = \"" + ownerUUID.toString() - // + "\" WHERE x = " + x + " AND y = " + y + " AND z = " + z - // + " AND world = \"" + worldName + "\" LIMIT 1"); - String sqlString = "UPDATE " + QuickShop.instance - .getDbPrefix() + "shops SET owner = ? WHERE x = ? AND y = ? AND z = ? AND world = ?" + (db - .getCore() instanceof MySQLCore ? " LIMIT 1" : ""); - PreparedStatement ps = db.getConnection().prepareStatement(sqlString); - ps.setString(1, ownerUUID); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - ps.setString(5, worldName); - plugin.getDatabaseManager().add(ps); + throws SQLException { + plugin.getDatabaseManager().add(() -> { + //QuickShop.instance.getDB().getConnection().createStatement() + // .executeUpdate("UPDATE " + QuickShop.instance.getDbPrefix() + "shops SET owner = \"" + ownerUUID.toString() + // + "\" WHERE x = " + x + " AND y = " + y + " AND z = " + z + // + " AND world = \"" + worldName + "\" LIMIT 1"); + String sqlString = "UPDATE " + QuickShop.instance + .getDbPrefix() + "shops SET owner = ? WHERE x = ? AND y = ? AND z = ? AND world = ?" + (db + .getCore() instanceof MySQLCore ? " LIMIT 1" : ""); + PreparedStatement ps = db.getConnection().prepareStatement(sqlString); + ps.setString(1, ownerUUID); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, worldName); + }); } public void updateShop(@NotNull String owner, @NotNull ItemStack item, int unlimited, int shopType, double price, int x, int y, int z, String world) { - try { + plugin.getDatabaseManager().add(() -> { String sqlString = "UPDATE " + QuickShop.instance - .getDbPrefix() + "shops SET owner = ?, itemConfig = ?, unlimited = ?, type = ?, price = ? WHERE x = ? AND y = ? and z = ? and world = ?"; + .getDbPrefix() + "shops SET owner = ?, itemConfig = ?, unlimited = ?, type = ?, price = ? WHERE x = ? AND y = ? and z = ? and world = ?"; PreparedStatement ps = db.getConnection().prepareStatement(sqlString); ps.setString(1, owner); ps.setString(2, Util.serialize(item)); @@ -239,11 +252,8 @@ public class DatabaseHelper { ps.setInt(7, y); ps.setInt(8, z); ps.setString(9, world); - plugin.getDatabaseManager().add(ps); - //db.execute(q, owner, Util.serialize(item), unlimited, shopType, price, x, y, z, world); - } catch (SQLException sqle) { - sqle.printStackTrace(); - } + }); + //db.execute(q, owner, Util.serialize(item), unlimited, shopType, price, x, y, z, world); } } \ 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 df43037e9..337a7a750 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java +++ b/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java @@ -19,7 +19,6 @@ package org.maxgamer.quickshop.Database; -import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; @@ -38,7 +37,7 @@ import org.maxgamer.quickshop.Util.WarningSender; */ public class DatabaseManager { - private final Queue sqlQueue = new LinkedBlockingQueue<>(); + private final Queue sqlQueue = new LinkedBlockingQueue<>(); @NotNull private final Database database; @@ -83,19 +82,15 @@ public class DatabaseManager { } /** - * Add preparedStatement to queue waiting flush to database, + * Add DatabaseTask to queue waiting flush to database, * - * @param ps The ps you want add in queue. + * @param task The DatabaseTask you want add in queue. */ - public void add(@NotNull PreparedStatement ps) { + public void add(DatabaseTask task) { if (useQueue) { - sqlQueue.offer(ps); + sqlQueue.offer(task); } else { - try { - ps.execute(); - } catch (SQLException sqle) { - sqle.printStackTrace(); - } + task.run(); } } @@ -117,24 +112,12 @@ public class DatabaseManager { plugin.getSentryErrorReporter().ignoreThrow(); sqle.printStackTrace(); } - PreparedStatement statement = sqlQueue.poll(); - if (statement == null) { + DatabaseTask task = sqlQueue.poll(); + if (task == null) { break; } - try { - Util.debugLog("Executing the SQL task: " + statement); - statement.execute(); - } catch (SQLException sqle) { - plugin.getSentryErrorReporter().ignoreThrow(); - sqle.printStackTrace(); - } - // Close statement anyway. - try { - statement.close(); - } catch (SQLException sqle) { - plugin.getSentryErrorReporter().ignoreThrow(); - sqle.printStackTrace(); - } + Util.debugLog("Executing the SQL task: " + task); + task.run(); long tookTime = timer.endTimer(); if (tookTime > 5000) { warningSender.sendWarn( diff --git a/src/main/java/org/maxgamer/quickshop/Database/DatabaseTask.java b/src/main/java/org/maxgamer/quickshop/Database/DatabaseTask.java new file mode 100644 index 000000000..3d05104ec --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/Database/DatabaseTask.java @@ -0,0 +1,21 @@ +package org.maxgamer.quickshop.Database; + +import java.sql.SQLException; + +public interface DatabaseTask { + + default void run(){ + try { + execute(); + onSuccess(); + }catch (SQLException e){ + onFailed(e); + } + } + + void execute() throws SQLException; + default void onSuccess(){} + default void onFailed(SQLException e){ + e.printStackTrace(); + } +} diff --git a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/JSONConfiguration.java b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/JSONConfiguration.java index efc98081b..9f7fb36a6 100644 --- a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/JSONConfiguration.java +++ b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/JSONConfiguration.java @@ -155,14 +155,14 @@ public final class JSONConfiguration extends FileConfiguration { public Object read(JsonElement in) { if (in.isJsonArray()) { - List list = new ArrayList(); + List list = new ArrayList<>(); JsonArray arr = in.getAsJsonArray(); for (JsonElement anArr : arr) { list.add(read(anArr)); } return list; } else if (in.isJsonObject()) { - Map map = new LinkedTreeMap(); + Map map = new LinkedTreeMap<>(); JsonObject obj = in.getAsJsonObject(); Set> entitySet = obj.entrySet(); for (Map.Entry entry : entitySet) { diff --git a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/SerializationHelper.java b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/SerializationHelper.java index 816b31010..c6806a630 100644 --- a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/SerializationHelper.java +++ b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/dumbtruckman/JsonConfiguration/SerializationHelper.java @@ -74,7 +74,7 @@ public class SerializationHelper { * @return the object that deserialize */ public static Object deserialize(@NotNull final Map input) { - final Map output = new LinkedHashMap(input.size()); + final Map output = new LinkedHashMap<>(input.size()); for (final Map.Entry e : input.entrySet()) { if (e.getValue() instanceof Map) { output.put(e.getKey().toString(), deserialize((Map) e.getValue())); @@ -110,7 +110,7 @@ public class SerializationHelper { */ @NotNull private static Map buildMap(@NotNull final Map map) { - final Map result = new LinkedHashMap(map.size()); + final Map result = new LinkedHashMap<>(map.size()); try { for (final Map.Entry entry : map.entrySet()) { result.put(entry.getKey().toString(), serialize(entry.getValue())); @@ -135,7 +135,7 @@ public class SerializationHelper { * else: stores it as is in the returned List. */ private static List buildList(@NotNull final Collection collection) { - final List result = new ArrayList(collection.size()); + final List result = new ArrayList<>(collection.size()); try { for (Object o : collection) { result.add(serialize(o)); @@ -154,7 +154,7 @@ public class SerializationHelper { * within lists and maps within lists. */ private static Object deserialize(@NotNull final List input) { - final List output = new ArrayList(input.size()); + final List output = new ArrayList<>(input.size()); for (final Object o : input) { if (o instanceof Map) { output.add(deserialize((Map) o)); diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java index f4914277e..b0f34f8cd 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java @@ -218,7 +218,6 @@ public class ArmorStandDisplayItem extends DisplayItem { Location location = getDisplayLocation(); this.armorStand = - (ArmorStand) this.shop .getLocation() .getWorld() diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java index 54ded711a..58b47aa3f 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java @@ -330,10 +330,6 @@ public class ContainerShop implements Shop { s.getBlock().setType(Material.AIR); } // Delete it from the database - int x = this.getLocation().getBlockX(); - int y = this.getLocation().getBlockY(); - int z = this.getLocation().getBlockZ(); - String world = Objects.requireNonNull(this.getLocation().getWorld()).getName(); // Refund if necessary if (plugin.getConfig().getBoolean("shop.refund")) { plugin.getEconomy().deposit(this.getOwner(), plugin.getConfig().getDouble("shop.cost")); @@ -344,7 +340,7 @@ public class ContainerShop implements Shop { } else { try { plugin.getShopManager().removeShop(this); - plugin.getDatabaseHelper().removeShop(x, y, z, world); + plugin.getDatabaseHelper().removeShop(this); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java index eaa06dc3f..77499e8ad 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java @@ -164,13 +164,7 @@ public class ShopLoader { if (!backupedDatabaseInDeleteProcess) { // Only backup db one time. backupedDatabaseInDeleteProcess = Util.backupDatabase(); } else { - plugin - .getDatabaseHelper() - .removeShop( - shop.getLocation().getBlockX(), - shop.getLocation().getBlockY(), - shop.getLocation().getBlockZ(), - Objects.requireNonNull(shop.getLocation().getWorld()).getName()); + plugin.getDatabaseHelper().removeShop(shop); } singleShopLoaded(singleShopLoadTimer); continue; diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java index 00e242501..69e2f5a4f 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java @@ -20,12 +20,6 @@ package org.maxgamer.quickshop.Shop; import com.google.common.collect.Sets; -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.util.*; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.stream.Collectors; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -46,6 +40,12 @@ import org.maxgamer.quickshop.QuickShop; import org.maxgamer.quickshop.Util.MsgUtil; import org.maxgamer.quickshop.Util.Util; +import java.sql.SQLException; +import java.text.DecimalFormat; +import java.util.*; +import java.util.logging.Level; +import java.util.stream.Collectors; + /** * Manage a lot of shops. */ @@ -76,8 +76,8 @@ public class ShopManager { /** * 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 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. */ @@ -218,58 +218,58 @@ public class ShopManager { Util.debugLog("Cancelled by plugin"); return; } - Location loc = shop.getLocation(); + plugin.getDatabaseHelper().createShop( + shop, + () -> Bukkit.getScheduler().runTask(plugin, () -> { + addShop(shop.getLocation().getWorld().getName(), shop); + // 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; + } - try { - plugin.getDatabaseHelper().createShop(ShopModerator.serialize(shop.getModerator()), shop.getPrice(), shop.getItem(), (shop.isUnlimited() ? 1 : 0), shop.getShopType().toID(), Objects.requireNonNull(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - addShop(loc.getWorld().getName(), shop); - } catch (SQLException e) { - plugin.getLogger().warning("Shop create failed, trying to auto fix the database..."); - boolean backupSuccess = Util.backupDatabase(); - try { - if (backupSuccess) { - plugin.getDatabaseHelper().removeShop(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."); - 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(); - } + 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) { + WallSign signBlockDataType = (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(); + } + }), + e -> Bukkit.getScheduler().runTask(plugin, () -> { + plugin.getLogger().warning("Shop create failed, trying to auto fix the database..."); + boolean backupSuccess = Util.backupDatabase(); + try { + if (backupSuccess) { + plugin.getDatabaseHelper().removeShop(shop); + } 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."); + error2.printStackTrace(); + } + })); } /** @@ -339,7 +339,7 @@ public class ShopManager { public @Nullable Shop getShopIncludeAttached_Classic(@NotNull Location loc) { @Nullable Shop shop; - // Get location's chunk all shops +// Get location's chunk all shops @Nullable HashMap inChunk = getShops(loc.getChunk()); // Found some shops in this chunk. if (inChunk != null) { @@ -362,7 +362,7 @@ public class ShopManager { // Oooops, no any shops matched. } } - // If that chunk nothing we founded, we should check it is attached. +// If that chunk nothing we founded, we should check it is attached. @Nullable Block attachedBlock = Util.getAttached(loc.getBlock()); // Check is attached on some block. if (attachedBlock == null) { @@ -416,7 +416,7 @@ public class ShopManager { * not use this method to create a shop. * * @param world The world the shop is in - * @param shop The shop to load + * @param shop The shop to load */ public void loadShop(@NotNull String world, @NotNull Shop shop) { this.addShop(world, shop); @@ -427,7 +427,7 @@ public class ShopManager { * yourself * * @param world The name of the world - * @param shop The shop to add + * @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)); @@ -482,7 +482,7 @@ public class ShopManager { * * @return All loaded shops. */ - public @Nullable Set getLoadedShops() { + public Set getLoadedShops() { return this.loadedShops; } @@ -616,7 +616,7 @@ public class ShopManager { @SuppressWarnings("deprecation") private void actionCreate(@NotNull Player p, @NotNull HashMap actions2, @NotNull Info info, @NotNull String - message, boolean bypassProtectionChecks) { + message, boolean bypassProtectionChecks) { if (plugin.getEconomy() == null) { p.sendMessage("Error: Economy system not loaded, type /qs main command to get details."); return; @@ -726,7 +726,7 @@ public class ShopManager { } } // Check price restriction - Entry priceRestriction = Util.getPriceRestriction(info.getItem().getType()); + Map.Entry priceRestriction = Util.getPriceRestriction(info.getItem().getType()); if (priceRestriction != null) { if (price < priceRestriction.getKey() || price > priceRestriction.getValue()) { // p.sendMessage(ChatColor.RED+"Restricted prices for diff --git a/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java b/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java index 0859f4454..250eff512 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java @@ -74,10 +74,8 @@ public class ChatSheetPrinter { String[] texts = text.split("\n"); Arrays.asList(texts) .forEach( - (str) -> { - p.sendMessage( - chatColor + MsgUtil.getMessage("tableformat.left_begin", p) + " " + str); - }); + (str) -> p.sendMessage( + chatColor + MsgUtil.getMessage("tableformat.left_begin", p) + " " + str)); } public void printSuggestableCmdLine( diff --git a/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java b/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java index c167d7dcf..44b040a6b 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java +++ b/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java @@ -287,7 +287,7 @@ class LunarCalendar { /** * 使用指定日历日期构造一个农历日历 * - * @param cal + * @param cal 要构造的日历日期 */ public LunarCalendar(Calendar cal) { @SuppressWarnings("unused") @@ -434,7 +434,7 @@ class LunarCalendar { /** * 获得表示农历年月日的日期对象 * - * @return + * @return 表示日期的对象 */ public Date getDate() { Calendar calendar = Calendar.getInstance(); diff --git a/src/main/java/org/maxgamer/quickshop/Util/Logger/QuickShopLogger.java b/src/main/java/org/maxgamer/quickshop/Util/Logger/QuickShopLogger.java index 039951780..4def7de3b 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Logger/QuickShopLogger.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Logger/QuickShopLogger.java @@ -258,7 +258,7 @@ public class QuickShopLogger extends PluginLogger { */ private void registerStyles() { // Initial here for secert optimization - bukkitToAnsi = new HashMap(); + bukkitToAnsi = new HashMap<>(); IGNORE_CASE = "(?i)"; // Colors @@ -341,7 +341,7 @@ public class QuickShopLogger extends PluginLogger { /** * To populate a Ansi with a reset attribute ahead * - * @param ansiColor + * @param ansiColor the Ansi need to add reset attribute * @return Ansi with reset ahead */ private org.fusesource.jansi.Ansi resetWith(org.fusesource.jansi.Ansi.Color ansiColor) {