diff --git a/src/main/java/org/maxgamer/quickshop/QuickShop.java b/src/main/java/org/maxgamer/quickshop/QuickShop.java index 2ee4e28bb..d8e52db11 100644 --- a/src/main/java/org/maxgamer/quickshop/QuickShop.java +++ b/src/main/java/org/maxgamer/quickshop/QuickShop.java @@ -672,6 +672,22 @@ public class QuickShop extends JavaPlugin { throw new IllegalStateException("Failed to reload QuickShop! Please consider restarting the server. (Plugin was updated)"); } } + // Maybe name changed, try search globally + if (!file.exists()) { + File pluginFolder = new File("plugins"); + if (pluginFolder.isDirectory()) { + //noinspection ConstantConditions + for (File listFile : pluginFolder.listFiles()) { + if (listFile.getName().endsWith(".jar")) { + if (getPluginLoader().loadPlugin(listFile).getName().equals(getDescription().getName())) { + file = listFile; + break; + } + } + } + } + } + if (!file.exists()) { throw new IllegalStateException("Failed to reload QuickShop! Please consider restarting the server. (Failed to find plugin jar)"); } diff --git a/src/main/java/org/maxgamer/quickshop/shop/ContainerShop.java b/src/main/java/org/maxgamer/quickshop/shop/ContainerShop.java index ba148d46f..d2641a539 100644 --- a/src/main/java/org/maxgamer/quickshop/shop/ContainerShop.java +++ b/src/main/java/org/maxgamer/quickshop/shop/ContainerShop.java @@ -164,18 +164,17 @@ public class ContainerShop implements Shop { private void initDisplayItem() { Util.ensureThread(false); if (plugin.isDisplay()) { - Chunk chunk = getLocation().getChunk(); switch (DisplayItem.getNowUsing()) { case REALITEM: - this.displayItem = new RealDisplayItem(this, chunk.getWorld().getName(), chunk.getX(), chunk.getX()); + this.displayItem = new RealDisplayItem(this); break; case VIRTUALITEM: - this.displayItem = new VirtualDisplayItem(this, chunk.getWorld().getName(), chunk.getX(), chunk.getX()); + this.displayItem = new VirtualDisplayItem(this); break; default: Util.debugLog( "Warning: Failed to create a ContainerShop displayItem, the type we didn't know, fallback to RealDisplayItem"); - this.displayItem = new RealDisplayItem(this, chunk.getWorld().getName(), chunk.getX(), chunk.getX()); + this.displayItem = new RealDisplayItem(this); break; } } @@ -303,6 +302,7 @@ public class ContainerShop implements Shop { return; } + //FIXME: This may affect the performance updateAttachedShop(); if (isLeftShop) { @@ -706,28 +706,24 @@ public class ContainerShop implements Shop { this.setSignText(getSignText()); } + private volatile boolean updating = false; + /** - * Upates the shop into the database. + * Updates the shop into the database. */ @Override - public synchronized void update() { - Util.mainThreadRun(this::update0); - } - - private void notifyDisplayItemChange() { - isDisplayItemChanged = true; - if (attachedShop != null && !attachedShop.isDisplayItemChanged) { - attachedShop.notifyDisplayItemChange(); - } - } - - private void update0() { + public void update() { + //TODO: check isDirty() Util.ensureThread(false); + if (updating) { + return; + } ShopUpdateEvent shopUpdateEvent = new ShopUpdateEvent(this); if (Util.fireCancellableEvent(shopUpdateEvent)) { Util.debugLog("The Shop update action was canceled by a plugin."); return; } + updating = true; int x = this.getLocation().getBlockX(); int y = this.getLocation().getBlockY(); int z = this.getLocation().getBlockZ(); @@ -738,11 +734,20 @@ public class ContainerShop implements Shop { .updateShop(ShopModerator.serialize(this.moderator), this.getItem(), unlimited, shopType.toID(), this.getPrice(), x, y, z, world, this.saveExtraToYaml()); + this.dirty = false; } catch (Exception e) { plugin.getLogger().log(Level.WARNING, "Could not update a shop in the database! Changes will revert after a reboot!", e); + } finally { + updating = false; + } + } + + private void notifyDisplayItemChange() { + isDisplayItemChanged = true; + if (attachedShop != null && !attachedShop.isDisplayItemChanged) { + attachedShop.notifyDisplayItemChange(); } - this.dirty = false; } /** @@ -831,24 +836,28 @@ public class ContainerShop implements Shop { // check price restriction PriceLimiter.CheckResult priceRestriction = plugin.getShopManager().getPriceLimiter().check(item, price); + boolean markUpdate = false; if (priceRestriction.getStatus() != PriceLimiter.Status.PASS) { if (priceRestriction.getStatus() == PriceLimiter.Status.NOT_A_WHOLE_NUMBER) { setDirty(); price = Math.floor(price); - this.update(); + markUpdate = true; } else if (priceRestriction.getStatus() == PriceLimiter.Status.NOT_VALID) { setDirty(); price = priceRestriction.getMin(); - this.update(); + markUpdate = true; } if (price < priceRestriction.getMin()) { setDirty(); price = priceRestriction.getMin(); - this.update(); + markUpdate = true; } else if (price > priceRestriction.getMax()) { setDirty(); price = priceRestriction.getMax(); - this.update(); + markUpdate = true; + } + if (markUpdate) { + update(); } } checkDisplay(); diff --git a/src/main/java/org/maxgamer/quickshop/shop/DisplayItem.java b/src/main/java/org/maxgamer/quickshop/shop/DisplayItem.java index 23eda4915..be9737e87 100644 --- a/src/main/java/org/maxgamer/quickshop/shop/DisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/shop/DisplayItem.java @@ -52,15 +52,9 @@ public abstract class DisplayItem { @Nullable protected ItemStack guardedIstack; private boolean pendingRemoval; - protected int chunkX; - protected int chunkZ; - protected String worldName; - protected DisplayItem(Shop shop, String worldName, int chunkX, int chunkZ) { + protected DisplayItem(Shop shop) { this.shop = shop; - this.worldName = worldName; - this.chunkX = chunkX; - this.chunkZ = chunkZ; this.originalItemStack = shop.getItem().clone(); if (displayAllowStacks) { //Prevent stack over the normal size diff --git a/src/main/java/org/maxgamer/quickshop/shop/RealDisplayItem.java b/src/main/java/org/maxgamer/quickshop/shop/RealDisplayItem.java index 45f875f21..0dcfb9ae4 100644 --- a/src/main/java/org/maxgamer/quickshop/shop/RealDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/shop/RealDisplayItem.java @@ -35,6 +35,7 @@ import org.maxgamer.quickshop.util.MsgUtil; import org.maxgamer.quickshop.util.Util; import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.UUID; @@ -49,8 +50,8 @@ public class RealDisplayItem extends DisplayItem { * * @param shop The shop (See Shop) */ - RealDisplayItem(@NotNull Shop shop, @NotNull String worldName, int chunkX, int chunkZ) { - super(shop, worldName, chunkX, chunkZ); + RealDisplayItem(@NotNull Shop shop) { + super(shop); // this.displayLoc = shop.getLocation().clone().add(0.5, 1.2, 0.5); } @@ -113,9 +114,7 @@ public class RealDisplayItem extends DisplayItem { if (shop.isLeftShop()) { return; } - Util.debugLog( - "Fixing moved Item displayItem " + eItem.getUniqueId() + " at " + eItem - .getLocation()); + Util.debugLog("Fixing moved Item displayItem " + eItem.getUniqueId() + " at " + eItem.getLocation()); PaperLib.teleportAsync(entity, Objects.requireNonNull(getDisplayLocation()), PlayerTeleportEvent.TeleportCause.UNKNOWN); return; } @@ -132,8 +131,7 @@ public class RealDisplayItem extends DisplayItem { public void remove() { Util.ensureThread(false); if (this.item == null) { - Util.debugLog( - "Ignore the Item removing because the Item is already gone or it's a left shop."); + Util.debugLog("Ignore the Item removing because the Item is already gone or it's a left shop."); return; } this.item.remove(); @@ -157,7 +155,7 @@ public class RealDisplayItem extends DisplayItem { boolean removed = false; - ArrayList elist = new ArrayList<>(item.getNearbyEntities(1.5, 1.5, 1.5)); + List elist = new ArrayList<>(item.getNearbyEntities(1.5, 1.5, 1.5)); if (shop.isRealDouble()) { elist.addAll(item.getWorld() .getNearbyEntities(Objects.requireNonNull(getDoubleShopDisplayLocations(true)), 1.5, @@ -175,9 +173,7 @@ public class RealDisplayItem extends DisplayItem { UUID displayUUID = this.item.getUniqueId(); if (!eItem.getUniqueId().equals(displayUUID)) { if (DisplayItem.checkIsTargetShopDisplay(eItem.getItemStack(), this.shop)) { - Util.debugLog( - "Removing a duped ItemEntity " + eItem.getUniqueId() + " at " + eItem - .getLocation()); + Util.debugLog("Removing a duped ItemEntity " + eItem.getUniqueId() + " at " + eItem.getLocation()); entity.remove(); removed = true; } @@ -226,8 +222,7 @@ public class RealDisplayItem extends DisplayItem { return; } if (shop.getLocation().getWorld() == null) { - Util.debugLog( - "Canceled the displayItem spawning because the location in the world is null."); + Util.debugLog("Canceled the displayItem spawning because the location in the world is null."); return; } @@ -236,14 +231,12 @@ public class RealDisplayItem extends DisplayItem { return; } if (item != null && item.isValid()) { - Util.debugLog( - "Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!"); + Util.debugLog("Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!"); MsgUtil.debugStackTrace(Thread.currentThread().getStackTrace()); } if (!Util.isDisplayAllowBlock( Objects.requireNonNull(getDisplayLocation()).getBlock().getType())) { - Util.debugLog( - "Can't spawn the displayItem because there is not an AIR block above the shopblock."); + Util.debugLog("Can't spawn the displayItem because there is not an AIR block above the shopblock."); return; } @@ -252,8 +245,7 @@ public class RealDisplayItem extends DisplayItem { plugin.getServer().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"); + Util.debugLog("Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on"); return; } this.guardedIstack = DisplayItem.createGuardItemStack(this.originalItemStack, this.shop); diff --git a/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java b/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java index 658b05491..c3d35eed5 100644 --- a/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java +++ b/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java @@ -25,6 +25,7 @@ import com.google.gson.JsonSyntaxException; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -60,7 +61,6 @@ public class ShopLoader { private final List shopsInDatabase = new CopyOnWriteArrayList<>(); private final List shopRawDatabaseInfoList = new CopyOnWriteArrayList<>(); private int errors; - private int totalLoaded = 0; //private final WarningSender warningSender; /** @@ -84,11 +84,12 @@ public class ShopLoader { */ public void loadShops(@Nullable String worldName) { //boolean backupedDatabaseInDeleteProcess = false; - this.plugin.getLogger().info("Loading shops from the database..."); + this.plugin.getLogger().info("Fetching shops from the database...If plugin stuck there, check your database connection."); int loadAfterChunkLoaded = 0; int loadAfterWorldLoaded = 0; List pendingLoadShops = new ArrayList<>(); try (WarpedResultSet warpRS = plugin.getDatabaseHelper().selectAllShops(); ResultSet rs = warpRS.getResultSet()) { + this.plugin.getLogger().info("Loading shops from the database..."); while (rs.next()) { ShopRawDatabaseInfo origin = new ShopRawDatabaseInfo(rs); shopRawDatabaseInfoList.add(origin); @@ -146,17 +147,21 @@ public class ShopLoader { loadAfterChunkLoaded++; } } - for (Shop shop : pendingLoadShops) { - shop.onLoad(); - shop.update(); - } - this.plugin - .getLogger() - .info( - "Successfully loaded " - + totalLoaded - + " shops!"); - this.plugin.getLogger().info(loadAfterChunkLoaded + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + this.plugin.getLogger().info("Loading the shops in worlds..."); + for (Shop shop : pendingLoadShops) { + shop.onLoad(); + shop.update(); + } + this.plugin + .getLogger() + .info( + "Successfully loaded " + + pendingLoadShops.size() + + " shops!"); + }, 1); + this.plugin.getLogger().info("Scheduled " + pendingLoadShops.size() + " shops to load in next tick, " + loadAfterChunkLoaded + " shops will load after chunk have loaded, " + loadAfterWorldLoaded + " shops will load after the world has loaded."); @@ -165,7 +170,7 @@ public class ShopLoader { } } - private void singleShopLoaded(@NotNull Timer singleShopLoadTimer) { + /* private void singleShopLoaded(@NotNull Timer singleShopLoadTimer) { totalLoaded++; long singleShopLoadTime = singleShopLoadTimer.stopAndGetTimePassed(); loadTimes.add(singleShopLoadTime); @@ -178,7 +183,7 @@ public class ShopLoader { private double calcTimeCost(@NotNull Timer timer) { timeCostCache.putIfAbsent(timer, (double) timer.getPassedTime()); return timer.getPassedTime() - timeCostCache.get(timer); - } + }*/ @SuppressWarnings("ConstantConditions") private boolean shopNullCheck(@Nullable Shop shop) { diff --git a/src/main/java/org/maxgamer/quickshop/shop/VirtualDisplayItem.java b/src/main/java/org/maxgamer/quickshop/shop/VirtualDisplayItem.java index 3afd7716a..c2220239b 100644 --- a/src/main/java/org/maxgamer/quickshop/shop/VirtualDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/shop/VirtualDisplayItem.java @@ -31,6 +31,7 @@ import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.utility.MinecraftVersion; import com.comphenix.protocol.wrappers.WrappedChatComponent; import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; @@ -46,7 +47,7 @@ import org.maxgamer.quickshop.util.Util; import java.lang.reflect.InvocationTargetException; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicInteger; public class VirtualDisplayItem extends DisplayItem { @@ -62,7 +63,7 @@ public class VirtualDisplayItem extends DisplayItem { private final int entityID = counter.decrementAndGet(); //The List which store packet sender - private final Set packetSenders = ConcurrentHashMap.newKeySet(); + private final Set packetSenders = new ConcurrentSkipListSet<>(); private volatile boolean isDisplay; @@ -84,14 +85,11 @@ public class VirtualDisplayItem extends DisplayItem { //cache chunk x and z private volatile ShopChunk chunkLocation; - private volatile int chunkX; - private volatile int chunkZ; - private AsyncListenerHandler asyncListenerHandler; - public VirtualDisplayItem(@NotNull Shop shop, @NotNull String worldName, int chunkX, int chunkZ) throws RuntimeException { - super(shop, worldName, chunkX, chunkZ); + public VirtualDisplayItem(@NotNull Shop shop) throws RuntimeException { + super(shop); } private void initFakeDropItemPacket() { @@ -129,9 +127,11 @@ public class VirtualDisplayItem extends DisplayItem { @Override public void remove() { - sendPacketToAll(fakeItemDestroyPacket); - unload(); - isDisplay = false; + if (isDisplay) { + sendPacketToAll(fakeItemDestroyPacket); + unload(); + isDisplay = false; + } } private void sendPacketToAll(@NotNull PacketContainer packet) { @@ -180,14 +180,7 @@ public class VirtualDisplayItem extends DisplayItem { @Override public void spawn() { Util.ensureThread(false); - if (shop.isLeftShop()) { - return; - } - //lazy initialize - if (!initialized) { - initFakeDropItemPacket(); - } - if (shop.isDeleted() || !shop.isLoaded()) { + if (shop.isLeftShop() || isDisplay || shop.isDeleted() || !shop.isLoaded()) { return; } ShopDisplayItemSpawnEvent shopDisplayItemSpawnEvent = new ShopDisplayItemSpawnEvent(shop, originalItemStack, DisplayType.VIRTUALITEM); @@ -197,6 +190,15 @@ public class VirtualDisplayItem extends DisplayItem { "Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on"); return; } + + //lazy initialize + if (!initialized) { + initFakeDropItemPacket(); + } + if (chunkLocation == null) { + Chunk chunk = shop.getLocation().getChunk(); + chunkLocation = new ShopChunk(chunk.getWorld().getName(), chunk.getX(), chunk.getZ()); + } load(); // Can't rely on the attachedShop cache to be accurate @@ -249,9 +251,6 @@ public class VirtualDisplayItem extends DisplayItem { int x = integerStructureModifier.read(0); //chunk z int z = integerStructureModifier.read(1); - if (chunkLocation == null) { - chunkLocation = new ShopChunk(worldName, chunkX, chunkZ); - } if (chunkLocation.isSame(player.getWorld().getName(), x, z)) { packetSenders.add(player.getUniqueId()); sendFakeItem(player); @@ -267,7 +266,7 @@ public class VirtualDisplayItem extends DisplayItem { packetSenders.clear(); if (packetAdapter != null) { asyncListenerHandler.stop(); - protocolManager.getAsynchronousManager().unregisterAsyncHandler(packetAdapter); + protocolManager.getAsynchronousManager().unregisterAsyncHandler(asyncListenerHandler); //protocolManager.removePacketListener(packetAdapter); //Prevent memory leak asyncListenerHandler = null;