From 57b341a63fa6c58e587c3fd9f30b7b59caf00ceb Mon Sep 17 00:00:00 2001 From: Ghost_chu <2908803755@qq.com> Date: Sat, 18 Jan 2020 22:05:53 +0800 Subject: [PATCH] Format code and Cleanup imports Former-commit-id: 6d5b0d3c1dd1009e9df7b8e8faf27ea8b95e5f8d --- .../Command/SubCommands/SubCommand_Buy.java | 2 +- .../SubCommands/SubCommand_CleanGhost.java | 18 +- .../SubCommands/SubCommand_Create.java | 20 +- .../Command/SubCommands/SubCommand_Debug.java | 16 +- .../Command/SubCommands/SubCommand_Find.java | 12 +- .../Command/SubCommands/SubCommand_Help.java | 6 +- .../Command/SubCommands/SubCommand_Paste.java | 44 ++-- .../Command/SubCommands/SubCommand_Price.java | 12 +- .../Command/SubCommands/SubCommand_ROOT.java | 2 +- .../Command/SubCommands/SubCommand_Reset.java | 18 +- .../Command/SubCommands/SubCommand_Sell.java | 2 +- .../SubCommands/SubCommand_SetOwner.java | 7 +- .../SubCommands/SubCommand_SilentBuy.java | 4 +- .../SubCommands/SubCommand_SilentEmpty.java | 2 +- .../SubCommands/SubCommand_SilentPreview.java | 2 +- .../SubCommands/SubCommand_SilentRemove.java | 4 +- .../SubCommands/SubCommand_SilentSell.java | 4 +- .../SubCommand_SilentUnlimited.java | 2 +- .../Command/SubCommands/SubCommand_Staff.java | 4 +- .../SubCommands/SubCommand_SuperCreate.java | 10 +- .../quickshop/Database/DatabaseManager.java | 13 +- .../maxgamer/quickshop/Economy/Economy.java | 8 +- .../quickshop/Economy/EconomyType.java | 12 +- .../quickshop/Economy/Economy_Mixed.java | 26 ++- .../org/maxgamer/quickshop/Event/QSEvent.java | 8 +- .../Event/ShopDisplayItemDespawnEvent.java | 2 +- .../Event/ShopSuccessPurchaseEvent.java | 11 +- .../maxgamer/quickshop/File/FileEnvelope.java | 18 +- .../org/maxgamer/quickshop/File/IFile.java | 38 ++-- .../org/maxgamer/quickshop/File/JSONFile.java | 60 ++--- .../org/maxgamer/quickshop/File/YAMLFile.java | 58 ++--- .../InternalListener/InternalListener.java | 6 +- .../Listeners/ClearLaggListener.java | 2 +- .../Listeners/CustomInventoryListener.java | 2 +- .../Listeners/DisplayBugFixListener.java | 8 +- .../Listeners/DisplayProtectionListener.java | 16 +- .../quickshop/Listeners/PlayerListener.java | 8 +- .../java/org/maxgamer/quickshop/Metrics.java | 40 ++-- .../quickshop/Mock/MckFileConfiguration.java | 3 + .../JsonConfiguration/JSONConfiguration.java | 89 ++++---- .../SerializationHelper.java | 43 ++-- .../sk89q/worldedit/util/net/HttpRequest.java | 162 +++++++------- .../de/Keyle/MyPet/api/util/Colorizer.java | 14 +- .../de/Keyle/MyPet/api/util/LogFormat.java | 2 +- .../lucko/spark/common/util/FormatUtil.java | 1 + .../Permission/PermissionProviderType.java | 8 +- .../FactionsUUID/FactionsUUIDIntegration.java | 52 ++--- .../PluginsIntegration/IntegratedPlugin.java | 4 + .../PluginsIntegration/IntegrationStage.java | 1 + .../PlotSquared/PlotSquaredIntegration.java | 12 +- .../Residence/ResidenceIntegration.java | 43 ++-- .../PluginsIntegration/Towny/TownyFlags.java | 2 +- .../Towny/TownyIntegration.java | 24 +- .../WorldGuard/WorldGuardFlags.java | 2 +- .../org/maxgamer/quickshop/QuickShop.java | 205 +++++++++--------- .../quickshop/Shop/ArmorStandDisplayItem.java | 22 +- .../quickshop/Shop/ContainerShop.java | 71 +++--- .../maxgamer/quickshop/Shop/DisplayItem.java | 23 +- .../Shop/DisplayItemPersistentDataType.java | 7 +- .../maxgamer/quickshop/Shop/DisplayType.java | 12 +- .../quickshop/Shop/InventoryPreview.java | 33 ++- .../quickshop/Shop/MatcherWorkMode.java | 12 +- .../quickshop/Shop/RealDisplayItem.java | 11 +- .../org/maxgamer/quickshop/Shop/Shop.java | 14 +- .../maxgamer/quickshop/Shop/ShopLoader.java | 18 +- .../maxgamer/quickshop/Shop/ShopManager.java | 103 +++++---- .../quickshop/Shop/ShopModerator.java | 23 +- .../org/maxgamer/quickshop/Shop/ShopType.java | 12 +- .../quickshop/Util/ChatSheetPrinter.java | 2 +- .../org/maxgamer/quickshop/Util/Copied.java | 4 +- .../quickshop/Util/FunnyEasterEgg.java | 176 ++++++++------- .../maxgamer/quickshop/Util/GameLanguage.java | 75 ++++--- .../quickshop/Util/Github/GithubAPI.java | 9 +- .../Util/Github/ReleaseJsonContainer.java | 2 + .../quickshop/Util/IntegrationHelper.java | 29 +-- .../quickshop/Util/Location/LocationOf.java | 14 +- .../quickshop/Util/Location/StringOf.java | 12 +- .../Util/Logger/QuickShopLogger.java | 190 ++++++++-------- .../quickshop/Util/MojangAPI/AssetJson.java | 38 ++-- .../org/maxgamer/quickshop/Util/MsgUtil.java | 61 +++--- .../maxgamer/quickshop/Util/Paste/Paste.java | 26 ++- .../quickshop/Util/Paste/UbuntuPaster.java | 2 +- .../quickshop/Util/ReflectFactory.java | 4 +- .../quickshop/Util/SentryErrorReporter.java | 18 +- .../ServerForkWrapper/BukkitAPIWrapper.java | 7 +- .../Util/ServerForkWrapper/PaperWrapper.java | 12 +- .../Util/ServerForkWrapper/SpigotWrapper.java | 8 +- .../org/maxgamer/quickshop/Util/Updater.java | 7 +- .../org/maxgamer/quickshop/Util/Util.java | 10 +- .../Watcher/DisplayDupeRemoverWatcher.java | 4 +- .../Watcher/ShopContainerWatcher.java | 6 +- .../quickshop/Watcher/SignUpdateWatcher.java | 9 +- .../quickshop/Watcher/UpdateWatcher.java | 4 +- 93 files changed, 1163 insertions(+), 1121 deletions(-) diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Buy.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Buy.java index 8e5494337..ac37013f6 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Buy.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Buy.java @@ -68,7 +68,7 @@ public class SubCommand_Buy implements CommandProcesser { //shop.setSignText(); shop.update(); sender.sendMessage( - MsgUtil.getMessage("command.now-buying", sender, Util.getItemStackName(shop.getItem()))); + MsgUtil.getMessage("command.now-buying", sender, Util.getItemStackName(shop.getItem()))); return; } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_CleanGhost.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_CleanGhost.java index d526ad746..b684cb9d5 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_CleanGhost.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_CleanGhost.java @@ -44,25 +44,25 @@ public class SubCommand_CleanGhost implements CommandProcesser { @Override public void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { - if(cmdArg.length < 1){ - sender.sendMessage(ChatColor.YELLOW+"This command will purge all data damaged shop, create in disallow world shop, create disallow sell items shop and IN NOT LOADED WORLD SHOPS, make sure you have backup your shops data, and use /qs cleanghost confirm to continue."); + if (cmdArg.length < 1) { + sender.sendMessage(ChatColor.YELLOW + "This command will purge all data damaged shop, create in disallow world shop, create disallow sell items shop and IN NOT LOADED WORLD SHOPS, make sure you have backup your shops data, and use /qs cleanghost confirm to continue."); return; } - if(!"confirm".equalsIgnoreCase(cmdArg[0])){ - sender.sendMessage(ChatColor.YELLOW+"This command will purge all data damaged shop, create in disallow world shop, create disallow sell items shop and IN NOT LOADED WORLD SHOPS, make sure you have backup your shops data, and use /qs cleanghost confirm to continue."); + if (!"confirm".equalsIgnoreCase(cmdArg[0])) { + sender.sendMessage(ChatColor.YELLOW + "This command will purge all data damaged shop, create in disallow world shop, create disallow sell items shop and IN NOT LOADED WORLD SHOPS, make sure you have backup your shops data, and use /qs cleanghost confirm to continue."); return; } - sender.sendMessage(ChatColor.GREEN+"Starting checking the shop be ghost, all does not exist shop will be removed..."); + sender.sendMessage(ChatColor.GREEN + "Starting checking the shop be ghost, all does not exist shop will be removed..."); new BukkitRunnable() { @Override public void run() { - sender.sendMessage(ChatColor.GREEN+"Async thread is started, please wait..."); + sender.sendMessage(ChatColor.GREEN + "Async thread is started, please wait..."); Util.backupDatabase(); //Already warn the user, don't care about backup result. for (Shop shop : plugin.getShopLoader().getShopsInDatabase()) { - sender.sendMessage(ChatColor.GRAY + "Checking the shop " + shop+" metadata and location block state..."); + sender.sendMessage(ChatColor.GRAY + "Checking the shop " + shop + " metadata and location block state..."); if (shop == null) { continue; //WTF } @@ -98,7 +98,7 @@ public class SubCommand_CleanGhost implements CommandProcesser { } //Shop exist check plugin.getServer().getScheduler().runTask(plugin, () -> { - Util.debugLog("Posted to main server thread to continue access Bukkit API for shop "+shop); + Util.debugLog("Posted to main server thread to continue access Bukkit API for shop " + shop); if (!Util.canBeShop(shop.getLocation().getBlock())) { sender.sendMessage(ChatColor.YELLOW + "Shop " + shop + " removing cause target location nolonger is a shop or disallow create the shop."); shop.delete(); @@ -110,7 +110,7 @@ public class SubCommand_CleanGhost implements CommandProcesser { e.printStackTrace(); } } - sender.sendMessage(ChatColor.GREEN+"All shops completed checks."); + sender.sendMessage(ChatColor.GREEN + "All shops completed checks."); } }.runTaskAsynchronously(plugin); } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Create.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Create.java index 4b899f503..58c1bc86a 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Create.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Create.java @@ -89,7 +89,7 @@ public class SubCommand_Create implements CommandProcesser { } if (!plugin.getShopManager().canBuildShop(p, b, - blockFace)) { + blockFace)) { // As of the new checking system, most plugins will tell the // player why they can't create a shop there. // So telling them a message would cause spam etc. @@ -103,20 +103,20 @@ public class SubCommand_Create implements CommandProcesser { } if (Util.isBlacklisted(item) - && !QuickShop.getPermissionManager().hasPermission(p,"quickshop.bypass." + item.getType().name())) { + && !QuickShop.getPermissionManager().hasPermission(p, "quickshop.bypass." + item.getType().name())) { p.sendMessage(MsgUtil.getMessage("blacklisted-item", sender)); return; } // Send creation menu. plugin.getShopManager().getActions().put( - p.getUniqueId(), - new Info( - b.getLocation(), - ShopAction.CREATE, - p.getInventory().getItemInMainHand(), - b.getRelative(p.getFacing().getOppositeFace()) - ) + p.getUniqueId(), + new Info( + b.getLocation(), + ShopAction.CREATE, + p.getInventory().getItemInMainHand(), + b.getRelative(p.getFacing().getOppositeFace()) + ) ); if (cmdArg.length >= 1) { @@ -126,7 +126,7 @@ public class SubCommand_Create implements CommandProcesser { } p.sendMessage( - MsgUtil.getMessage("how-much-to-trade-for", sender, Util.getItemStackName(item))); + MsgUtil.getMessage("how-much-to-trade-for", sender, Util.getItemStackName(item))); return; } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Debug.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Debug.java index e64d987b9..4eef1e897 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Debug.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Debug.java @@ -79,15 +79,15 @@ public class SubCommand_Debug implements CommandProcesser { RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); List arguments = runtimeMxBean.getInputArguments(); - sender.sendMessage(ChatColor.GOLD+"Arguments: "+ChatColor.AQUA+ Util.list2String(arguments)); - sender.sendMessage(ChatColor.GOLD+"Name: "+ChatColor.AQUA+ runtimeMxBean.getName()); - sender.sendMessage(ChatColor.GOLD+"VM Name: "+ChatColor.AQUA+ runtimeMxBean.getVmName()); - sender.sendMessage(ChatColor.GOLD+"Uptime: "+ChatColor.AQUA+ runtimeMxBean.getUptime()); - sender.sendMessage(ChatColor.GOLD+"JVM Ver: "+ChatColor.AQUA+ runtimeMxBean.getVmVersion()); - Map sys = runtimeMxBean.getSystemProperties(); + sender.sendMessage(ChatColor.GOLD + "Arguments: " + ChatColor.AQUA + Util.list2String(arguments)); + sender.sendMessage(ChatColor.GOLD + "Name: " + ChatColor.AQUA + runtimeMxBean.getName()); + sender.sendMessage(ChatColor.GOLD + "VM Name: " + ChatColor.AQUA + runtimeMxBean.getVmName()); + sender.sendMessage(ChatColor.GOLD + "Uptime: " + ChatColor.AQUA + runtimeMxBean.getUptime()); + sender.sendMessage(ChatColor.GOLD + "JVM Ver: " + ChatColor.AQUA + runtimeMxBean.getVmVersion()); + Map sys = runtimeMxBean.getSystemProperties(); List sysData = new ArrayList<>(); - sys.keySet().forEach(key-> sysData.add(key+"="+sys.get(key))); - sender.sendMessage(ChatColor.GOLD+"Sys Pro: "+ChatColor.AQUA+ Util.list2String(sysData)); + sys.keySet().forEach(key -> sysData.add(key + "=" + sys.get(key))); + sender.sendMessage(ChatColor.GOLD + "Sys Pro: " + ChatColor.AQUA + Util.list2String(sysData)); break; default: sender.sendMessage("Error, no correct args given."); diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Find.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Find.java index c3c0048bd..c9e4d0904 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Find.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Find.java @@ -72,13 +72,13 @@ public class SubCommand_Find implements CommandProcesser { final int chunkRadius = (int) minDistance / 16 + 1; Shop closest = null; CompletableFuture future = new CompletableFuture<>(); - plugin.getBukkitAPIWrapper().getChunkAt(loc.getWorld(),loc, future); + plugin.getBukkitAPIWrapper().getChunkAt(loc.getWorld(), loc, future); final Chunk c; try { c = future.get(); - }catch (Exception asyncErr){ + } catch (Exception asyncErr) { sender.sendMessage("Cannot execute the command, see console for details."); - plugin.getSentryErrorReporter().sendError(asyncErr,"Unknown errors"); + plugin.getSentryErrorReporter().sendError(asyncErr, "Unknown errors"); plugin.getSentryErrorReporter().ignoreThrow(); asyncErr.printStackTrace(); return; @@ -111,12 +111,12 @@ public class SubCommand_Find implements CommandProcesser { sender.sendMessage(MsgUtil.getMessage("no-nearby-shop", sender, cmdArg[0])); return; } - + final Location lookat = closest.getLocation().clone().add(0.5, 0.5, 0.5); // Hack fix to make /qs find not used by /back - plugin.getBukkitAPIWrapper().teleportEntity(p,Util.lookAt(loc, lookat).add(0, -1.62, 0), PlayerTeleportEvent.TeleportCause.UNKNOWN); + plugin.getBukkitAPIWrapper().teleportEntity(p, Util.lookAt(loc, lookat).add(0, -1.62, 0), PlayerTeleportEvent.TeleportCause.UNKNOWN); p.sendMessage( - MsgUtil.getMessage("nearby-shop-this-way", sender, "" + (int) Math.floor(Math.sqrt(minDistanceSquared)))); + MsgUtil.getMessage("nearby-shop-this-way", sender, "" + (int) Math.floor(Math.sqrt(minDistanceSquared)))); } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Help.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Help.java index a72eecfbf..d47e5bc98 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Help.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Help.java @@ -55,7 +55,7 @@ public class SubCommand_Help implements CommandProcesser { for (String requirePermission : requirePermissions) { // FIXME: 24/11/2019 You are already checked the null and empty if (requirePermission != null && !requirePermission.isEmpty() && - !QuickShop.getPermissionManager().hasPermission(s, requirePermission)) { + !QuickShop.getPermissionManager().hasPermission(s, requirePermission)) { //noinspection UnnecessaryContinue continue; } @@ -67,8 +67,8 @@ public class SubCommand_Help implements CommandProcesser { } s.sendMessage(ChatColor.GREEN + "/" + commandLabel + " " + container - .getPrefix() + ChatColor.YELLOW + " - " - + MsgUtil.getMessage("command.description." + container.getPrefix(), s)); + .getPrefix() + ChatColor.YELLOW + " - " + + MsgUtil.getMessage("command.description." + container.getPrefix(), s)); } } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Paste.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Paste.java index c986ccb83..9e14d85a3 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Paste.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Paste.java @@ -53,29 +53,29 @@ public class SubCommand_Paste implements CommandProcesser { sender.sendMessage("Please wait, we're uploading the data to the pastebin..."); final Paste paste = new Paste(plugin); final String pasteText = paste.genNewPaste(); - String pasteResult = paste.paste(pasteText); - if(pasteResult != null){ - sender.sendMessage(pasteResult); - }else{ - sender.sendMessage("The paste failed, saving the paste at local location..."); - File file = new File(plugin.getDataFolder(), "paste"); - file.mkdirs(); - file = new File(file, "paste-" + UUID.randomUUID().toString().replaceAll("-", "") + ".txt"); - try { - final boolean createResult = file.createNewFile(); - Util.debugLog("Create paste file: " + file.getCanonicalPath() + " " + createResult); - final FileWriter fwriter = new FileWriter(file); - fwriter.write(pasteText); - fwriter.flush(); - fwriter.close(); - sender.sendMessage("Paste was saved to your server at: " + file.getAbsolutePath()); - } catch (IOException e) { - plugin.getSentryErrorReporter().ignoreThrow(); - e.printStackTrace(); - sender.sendMessage("Saving failed, output to console..."); - plugin.getLogger().info(pasteText); - } + String pasteResult = paste.paste(pasteText); + if (pasteResult != null) { + sender.sendMessage(pasteResult); + } else { + sender.sendMessage("The paste failed, saving the paste at local location..."); + File file = new File(plugin.getDataFolder(), "paste"); + file.mkdirs(); + file = new File(file, "paste-" + UUID.randomUUID().toString().replaceAll("-", "") + ".txt"); + try { + final boolean createResult = file.createNewFile(); + Util.debugLog("Create paste file: " + file.getCanonicalPath() + " " + createResult); + final FileWriter fwriter = new FileWriter(file); + fwriter.write(pasteText); + fwriter.flush(); + fwriter.close(); + sender.sendMessage("Paste was saved to your server at: " + file.getAbsolutePath()); + } catch (IOException e) { + plugin.getSentryErrorReporter().ignoreThrow(); + e.printStackTrace(); + sender.sendMessage("Saving failed, output to console..."); + plugin.getLogger().info(pasteText); } + } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Price.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Price.java index 08b057c9b..d7bd373e6 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Price.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Price.java @@ -130,8 +130,8 @@ public class SubCommand_Price implements CommandProcesser { final Shop shop = plugin.getShopManager().getShop(b.getLocation()); if (shop == null || - (!shop.getModerator().isModerator(((Player) sender).getUniqueId()) && - !QuickShop.getPermissionManager().hasPermission(sender, "quickshop.other.price"))) { + (!shop.getModerator().isModerator(((Player) sender).getUniqueId()) && + !QuickShop.getPermissionManager().hasPermission(sender, "quickshop.other.price"))) { continue; } @@ -143,20 +143,20 @@ public class SubCommand_Price implements CommandProcesser { if (fee > 0 && !plugin.getEconomy().withdraw(p.getUniqueId(), fee)) { sender.sendMessage(MsgUtil.getMessage("you-cant-afford-to-change-price", sender, - plugin.getEconomy().format(fee))); + plugin.getEconomy().format(fee))); return; } if (fee > 0) { sender.sendMessage( - MsgUtil.getMessage("fee-charged-for-price-change", sender, plugin.getEconomy().format(fee))); + MsgUtil.getMessage("fee-charged-for-price-change", sender, plugin.getEconomy().format(fee))); try { plugin.getEconomy().deposit(plugin.getServer().getOfflinePlayer(Objects.requireNonNull(plugin.getConfig().getString("tax-account"))) - .getUniqueId(), fee); + .getUniqueId(), fee); } catch (Exception e) { e.getMessage(); plugin.getLogger().log(Level.WARNING, - "QuickShop can't pay tax to the account in config.yml, please set the tax account name to an existing player!"); + "QuickShop can't pay tax to the account in config.yml, please set the tax account name to an existing player!"); } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_ROOT.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_ROOT.java index b80163dfe..3e88ec010 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_ROOT.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_ROOT.java @@ -49,7 +49,7 @@ public class SubCommand_ROOT implements CommandProcesser { for (String requirePermission : requirePermissions) { if (requirePermission != null && !requirePermission.isEmpty() && !QuickShop.getPermissionManager().hasPermission(sender, requirePermission)) { Util.debugLog("Sender " + sender - .getName() + " trying tab-complete the command: " + commandLabel + ", but no permission " + requirePermission); + .getName() + " trying tab-complete the command: " + commandLabel + ", but no permission " + requirePermission); return new ArrayList<>(); } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Reset.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Reset.java index 12b925044..d1cebb89d 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Reset.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Reset.java @@ -54,32 +54,32 @@ public class SubCommand_Reset implements CommandProcesser { return; } - switch (cmdArg[0]){ + switch (cmdArg[0]) { case "lang": - File item = new File(plugin.getDataFolder(),"itemi18n.yml"); - File ench = new File(plugin.getDataFolder(),"enchi18n.yml"); - File potion = new File(plugin.getDataFolder(),"potioni18n.yml"); + File item = new File(plugin.getDataFolder(), "itemi18n.yml"); + File ench = new File(plugin.getDataFolder(), "enchi18n.yml"); + File potion = new File(plugin.getDataFolder(), "potioni18n.yml"); item.delete(); ench.delete(); potion.delete(); MsgUtil.loadItemi18n(); MsgUtil.loadEnchi18n(); MsgUtil.loadPotioni18n(); - sender.sendMessage(MsgUtil.getMessage("complete",sender)); + sender.sendMessage(MsgUtil.getMessage("complete", sender)); break; case "config": - File config = new File(plugin.getDataFolder(),"config.yml"); + File config = new File(plugin.getDataFolder(), "config.yml"); config.delete(); plugin.saveDefaultConfig(); Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin); - sender.sendMessage(MsgUtil.getMessage("complete",sender)); + sender.sendMessage(MsgUtil.getMessage("complete", sender)); break; case "messages": - File msgs = new File(plugin.getDataFolder(),"messages.json"); + File msgs = new File(plugin.getDataFolder(), "messages.json"); msgs.delete(); MsgUtil.loadCfgMessages(); - sender.sendMessage(MsgUtil.getMessage("complete",sender)); + sender.sendMessage(MsgUtil.getMessage("complete", sender)); break; } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Sell.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Sell.java index f98a2e4ac..e16f5bb09 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Sell.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Sell.java @@ -71,7 +71,7 @@ public class SubCommand_Sell implements CommandProcesser { //shop.setSignText(); shop.update(); sender.sendMessage(MsgUtil - .getMessage("command.now-selling", sender, Util.getItemStackName(shop.getItem()))); + .getMessage("command.now-selling", sender, Util.getItemStackName(shop.getItem()))); return; } sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SetOwner.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SetOwner.java index 71ab0aba1..cbe700e84 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SetOwner.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SetOwner.java @@ -70,11 +70,10 @@ public class SubCommand_SetOwner implements CommandProcesser { continue; } - @SuppressWarnings("deprecation") - final OfflinePlayer p = plugin.getServer().getOfflinePlayer(cmdArg[0]); + @SuppressWarnings("deprecation") final OfflinePlayer p = plugin.getServer().getOfflinePlayer(cmdArg[0]); final String shopOwner = plugin.getServer().getOfflinePlayer(shop.getOwner()).getName(); - if(shopOwner == null){ - sender.sendMessage(MsgUtil.getMessage("unknown-player",null)); + if (shopOwner == null) { + sender.sendMessage(MsgUtil.getMessage("unknown-player", null)); return; } shop.setOwner(p.getUniqueId()); diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentBuy.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentBuy.java index b2801dc80..cedb4ca4b 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentBuy.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentBuy.java @@ -51,7 +51,7 @@ public class SubCommand_SilentBuy implements CommandProcesser { } final Shop shop = plugin.getShopManager().getShop(new Location(plugin.getServer().getWorld(cmdArg[0]), Integer.parseInt(cmdArg[1]), - Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); + Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); if (shop == null || !shop.getModerator().isModerator(((Player) sender).getUniqueId())) { sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); @@ -63,6 +63,6 @@ public class SubCommand_SilentBuy implements CommandProcesser { shop.update(); MsgUtil.sendControlPanelInfo(sender, shop); sender.sendMessage(MsgUtil - .getMessage("command.now-buying", sender, Util.getItemStackName(shop.getItem()))); + .getMessage("command.now-buying", sender, Util.getItemStackName(shop.getItem()))); } } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentEmpty.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentEmpty.java index 463987cef..7c488127c 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentEmpty.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentEmpty.java @@ -51,7 +51,7 @@ public class SubCommand_SilentEmpty implements CommandProcesser { } final Shop shop = plugin.getShopManager().getShop(new Location(plugin.getServer().getWorld(cmdArg[0]), Integer.parseInt(cmdArg[1]), - Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); + Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); if (!(shop instanceof ContainerShop)) { sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentPreview.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentPreview.java index cbbe14023..474e086b0 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentPreview.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentPreview.java @@ -57,7 +57,7 @@ public class SubCommand_SilentPreview implements CommandProcesser { } final Shop shop = plugin.getShopManager().getShop(new Location(plugin.getServer().getWorld(cmdArg[0]), - Integer.parseInt(cmdArg[1]), Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); + Integer.parseInt(cmdArg[1]), Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); if (!(shop instanceof ContainerShop)) { sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentRemove.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentRemove.java index b3fcaf0c2..c06936481 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentRemove.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentRemove.java @@ -52,7 +52,7 @@ public class SubCommand_SilentRemove implements CommandProcesser { final Player p = (Player) sender; final Shop shop = plugin.getShopManager().getShop(new Location(plugin.getServer().getWorld(cmdArg[0]), Integer.parseInt(cmdArg[1]), - Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); + Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); if (shop == null) { sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); @@ -60,7 +60,7 @@ public class SubCommand_SilentRemove implements CommandProcesser { } if (!shop.getModerator().isModerator(p.getUniqueId()) && - !QuickShop.getPermissionManager().hasPermission(sender, "quickshop.other.destroy")) { + !QuickShop.getPermissionManager().hasPermission(sender, "quickshop.other.destroy")) { sender.sendMessage(ChatColor.RED + MsgUtil.getMessage("no-permission", sender)); return; } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentSell.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentSell.java index 76e11bdfa..75d126947 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentSell.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentSell.java @@ -51,7 +51,7 @@ public class SubCommand_SilentSell implements CommandProcesser { } final Shop shop = plugin.getShopManager().getShop(new Location(plugin.getServer().getWorld(cmdArg[0]), Integer.parseInt(cmdArg[1]), - Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); + Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); if (shop == null || !shop.getModerator().isModerator(((Player) sender).getUniqueId())) { sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); @@ -63,7 +63,7 @@ public class SubCommand_SilentSell implements CommandProcesser { shop.update(); MsgUtil.sendControlPanelInfo(sender, shop); sender.sendMessage(MsgUtil - .getMessage("command.now-selling", sender, Util.getItemStackName(shop.getItem()))); + .getMessage("command.now-selling", sender, Util.getItemStackName(shop.getItem()))); } diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentUnlimited.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentUnlimited.java index a56f03353..0646b669e 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentUnlimited.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SilentUnlimited.java @@ -48,7 +48,7 @@ public class SubCommand_SilentUnlimited implements CommandProcesser { } final Shop shop = plugin.getShopManager().getShop(new Location(plugin.getServer().getWorld(cmdArg[0]), Integer.parseInt(cmdArg[1]), - Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); + Integer.parseInt(cmdArg[2]), Integer.parseInt(cmdArg[3]))); if (shop == null) { sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Staff.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Staff.java index 6989ac64d..1e91ea7f4 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Staff.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_Staff.java @@ -140,13 +140,13 @@ public class SubCommand_Staff implements CommandProcesser { if (staffs.isEmpty()) { sender.sendMessage(ChatColor.GREEN + MsgUtil - .getMessage("tableformat.left_begin", sender) + "Empty"); + .getMessage("tableformat.left_begin", sender) + "Empty"); return; } for (UUID uuid : staffs) { sender.sendMessage(ChatColor.GREEN + MsgUtil.getMessage("tableformat.left_begin", sender) + Bukkit - .getOfflinePlayer(uuid).getName()); + .getOfflinePlayer(uuid).getName()); } return; diff --git a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SuperCreate.java b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SuperCreate.java index 14029389e..a1a5f6b6b 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SuperCreate.java +++ b/src/main/java/org/maxgamer/quickshop/Command/SubCommands/SubCommand_SuperCreate.java @@ -86,7 +86,7 @@ public class SubCommand_SuperCreate implements CommandProcesser { } if (!plugin.getShopManager().canBuildShop(p, b, - blockFace)) { + blockFace)) { // As of the new checking system, most plugins will tell the // player why they can't create a shop there. // So telling them a message would cause spam etc. @@ -100,7 +100,7 @@ public class SubCommand_SuperCreate implements CommandProcesser { } if (Util.isBlacklisted(item) - && !QuickShop.getPermissionManager().hasPermission(p, "quickshop.bypass." + item.getType().name())) { + && !QuickShop.getPermissionManager().hasPermission(p, "quickshop.bypass." + item.getType().name())) { p.sendMessage(MsgUtil.getMessage("blacklisted-item", sender)); return; } @@ -111,12 +111,12 @@ public class SubCommand_SuperCreate implements CommandProcesser { } // Send creation menu. final Info info = new Info(b.getLocation(), ShopAction.CREATE, - p.getInventory().getItemInMainHand(), - b.getRelative(p.getFacing().getOppositeFace())); + p.getInventory().getItemInMainHand(), + b.getRelative(p.getFacing().getOppositeFace())); plugin.getShopManager().getActions().put(p.getUniqueId(), info); p.sendMessage( - MsgUtil.getMessage("how-much-to-trade-for", sender, Util.getItemStackName(item))); + MsgUtil.getMessage("how-much-to-trade-for", sender, Util.getItemStackName(item))); return; } sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop", sender)); diff --git a/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java b/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java index 5e3c2b53f..38ce204ba 100644 --- a/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java +++ b/src/main/java/org/maxgamer/quickshop/Database/DatabaseManager.java @@ -47,14 +47,11 @@ public class DatabaseManager { @NotNull private final QuickShop plugin; - - @Nullable - private BukkitTask task; - - private boolean useQueue; - @NotNull private final WarningSender warningSender; + @Nullable + private BukkitTask task; + private boolean useQueue; /** * Queued database manager. @@ -143,10 +140,10 @@ public class DatabaseManager { } try { this.database.getConnection().commit(); - }catch (SQLException e){ + } catch (SQLException e) { try { this.database.getConnection().rollback(); - }catch (SQLException ignored){ + } catch (SQLException ignored) { } } } diff --git a/src/main/java/org/maxgamer/quickshop/Economy/Economy.java b/src/main/java/org/maxgamer/quickshop/Economy/Economy.java index 2fd578f74..aa72cd066 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/Economy.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/Economy.java @@ -38,15 +38,15 @@ public class Economy implements EconomyCore { this.core = core; } + public static EconomyType getNowUsing() { + return EconomyType.fromID(QuickShop.instance.getConfig().getInt("economy-type")); + } + @Override public String toString() { return core.getClass().getName().split("_")[1]; } - public static EconomyType getNowUsing() { - return EconomyType.fromID(QuickShop.instance.getConfig().getInt("economy-type")); - } - /** * Checks that this economy is valid. Returns false if it is not valid. * diff --git a/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java b/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java index b3190e012..41afd4760 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/EconomyType.java @@ -29,6 +29,12 @@ public enum EconomyType { * */ UNKNOWN(-1), VAULT(0), RESERVE(1), MIXED(2); + private int id; + + EconomyType(int id) { + this.id = id; + } + public static EconomyType fromID(int id) { for (EconomyType type : EconomyType.values()) { if (type.id == id) { @@ -42,12 +48,6 @@ 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_Mixed.java b/src/main/java/org/maxgamer/quickshop/Economy/Economy_Mixed.java index b9315efdd..24cb29f4a 100644 --- a/src/main/java/org/maxgamer/quickshop/Economy/Economy_Mixed.java +++ b/src/main/java/org/maxgamer/quickshop/Economy/Economy_Mixed.java @@ -28,15 +28,17 @@ import java.util.UUID; public class Economy_Mixed implements EconomyCore { EconomyCore core; - public Economy_Mixed(){ + + public Economy_Mixed() { core = new Economy_Vault(); } + @Override public boolean deposit(UUID name, double amount) { - if(getBalance(name) < amount){ + if (getBalance(name) < amount) { return false; } - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), MsgUtil.fillArgs(QuickShop.instance.getConfig().getString("mixedeconomy.deposit"),Bukkit.getOfflinePlayer(name).getName(),String.valueOf(amount))); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), MsgUtil.fillArgs(QuickShop.instance.getConfig().getString("mixedeconomy.deposit"), Bukkit.getOfflinePlayer(name).getName(), String.valueOf(amount))); return true; } @@ -53,28 +55,28 @@ public class Economy_Mixed implements EconomyCore { @Override public boolean transfer(UUID from, UUID to, double amount) { boolean result; - result = withdraw(from,amount); - if(!result){ - deposit(from,amount); + result = withdraw(from, amount); + if (!result) { + deposit(from, amount); } - result = deposit(to,amount); - if(!result){ - withdraw(to,amount); + result = deposit(to, amount); + if (!result) { + withdraw(to, amount); } return true; } @Override public boolean withdraw(UUID name, double amount) { - if(getBalance(name) > amount){ + if (getBalance(name) > amount) { return false; } - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), MsgUtil.fillArgs(QuickShop.instance.getConfig().getString("mixedeconomy.withdraw"),Bukkit.getOfflinePlayer(name).getName(),String.valueOf(amount))); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), MsgUtil.fillArgs(QuickShop.instance.getConfig().getString("mixedeconomy.withdraw"), Bukkit.getOfflinePlayer(name).getName(), String.valueOf(amount))); return true; } @Override public boolean isValid() { - return core.isValid() ; + return core.isValid(); } } diff --git a/src/main/java/org/maxgamer/quickshop/Event/QSEvent.java b/src/main/java/org/maxgamer/quickshop/Event/QSEvent.java index fde6c99d7..696d6b82b 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/QSEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/QSEvent.java @@ -27,14 +27,14 @@ public abstract class QSEvent extends Event { private static final HandlerList handlers = new HandlerList(); + public static HandlerList getHandlerList() { + return handlers; + } + @NotNull @Override public HandlerList getHandlers() { return handlers; } - public static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemDespawnEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemDespawnEvent.java index 9786d2a35..62d48fdf0 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemDespawnEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopDisplayItemDespawnEvent.java @@ -51,7 +51,7 @@ public class ShopDisplayItemDespawnEvent extends QSEvent implements Cancellable * This event is called before the shop display item created * * @param shop Target shop - * @param itemStack Target itemstacck + * @param itemStack Target itemstacck * @param displayType The displayType */ public ShopDisplayItemDespawnEvent(@NotNull Shop shop, @NotNull ItemStack itemStack, diff --git a/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java b/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java index 57efbbfdc..3a0348086 100644 --- a/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java +++ b/src/main/java/org/maxgamer/quickshop/Event/ShopSuccessPurchaseEvent.java @@ -27,24 +27,21 @@ import org.maxgamer.quickshop.Shop.Shop; public class ShopSuccessPurchaseEvent extends QSEvent implements Cancellable { + @Getter + @NotNull + public final Shop shop; @Getter private final int amount; - @Getter @NotNull private final Player player; - - @Getter - @NotNull - public final Shop shop; - @Getter private final double tax; private final double total; //Don't use getter, we have important notice need told dev in javadoc. private boolean cancelled; - + /** * Builds a new shop purchase event diff --git a/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java b/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java index f5c01ceb0..fe493eda6 100644 --- a/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java +++ b/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java @@ -21,23 +21,19 @@ import java.io.InputStream; import java.util.List; import java.util.Objects; import java.util.Optional; + @ToString public abstract class FileEnvelope implements IFile { - @NotNull - private final Plugin plugin; - @NotNull protected final File file; - + protected final boolean loadDefault; + @NotNull + private final Plugin plugin; @NotNull private final Copied copied; - @NotNull private final String resourcePath; - - protected final boolean loadDefault; - @NotNull protected FileConfiguration fileConfiguration = new MckFileConfiguration(); @@ -142,15 +138,15 @@ public abstract class FileEnvelope implements IFile { @Override public Location getLocation(@NotNull String path) { return new LocationOf( - getString(path).orElse("") + getString(path).orElse("") ).value(); } @Override public void setLocation(@NotNull String path, @NotNull Location location) { set( - path, - new StringOf(location).asString() + path, + new StringOf(location).asString() ); } diff --git a/src/main/java/org/maxgamer/quickshop/File/IFile.java b/src/main/java/org/maxgamer/quickshop/File/IFile.java index 6d740f600..77519ec6f 100644 --- a/src/main/java/org/maxgamer/quickshop/File/IFile.java +++ b/src/main/java/org/maxgamer/quickshop/File/IFile.java @@ -40,6 +40,7 @@ public interface IFile { /** * Loads from the data + * * @param data the data */ void loadFromString(@NotNull String data) throws InvalidConfigurationException; @@ -56,7 +57,7 @@ public interface IFile { /** * Gets the object with fallback * - * @param path object path to get + * @param path object path to get * @param fallback fallback object to get if path does not exist * @return if path does not exist returns fallback object */ @@ -66,13 +67,12 @@ public interface IFile { /** * Gets or sets the object * - * @param path object path to get + * @param path object path to get * @param fallback fallback object to get if path does not exist - * @param object type + * @param object type * @return if path does not exist returns and set the path with fallback object */ - @NotNull - T getOrSet(@NotNull final String path, @NotNull T fallback); + @NotNull T getOrSet(@NotNull final String path, @NotNull T fallback); /** * Gets location @@ -86,25 +86,25 @@ public interface IFile { /** * Sets location into the path * - * @param path location path to set + * @param path location path to set * @param location {@link Location} */ void setLocation(@NotNull final String path, @NotNull final Location location); /** * Pattern: - * + *

* path: - * (material): 'DIAMOND' - * [amount]: 1 - * [data]: 0 - * [display-name]: 'Diamond Sword' - * [enchants]: - * DAMAGE_ALL: 10 - * FIRE_ASPECT: 2 - * [lore]: - * - 'Lore 1' - * - 'Lore 2' + * (material): 'DIAMOND' + * [amount]: 1 + * [data]: 0 + * [display-name]: 'Diamond Sword' + * [enchants]: + * DAMAGE_ALL: 10 + * FIRE_ASPECT: 2 + * [lore]: + * - 'Lore 1' + * - 'Lore 2' * * @param path itemstack path to get * @return {@link ItemStack} @@ -115,7 +115,7 @@ public interface IFile { /** * Sets custom itemstack to path * - * @param path itemstack path to set + * @param path itemstack path to set * @param itemStack {@link ItemStack} */ void setCustomItemStack(@NotNull final String path, @NotNull final ItemStack itemStack); @@ -132,7 +132,7 @@ public interface IFile { /** * Sets object to path * - * @param path object path to set + * @param path object path to set * @param object {@link Object} */ void set(@NotNull final String path, @Nullable final Object object); diff --git a/src/main/java/org/maxgamer/quickshop/File/JSONFile.java b/src/main/java/org/maxgamer/quickshop/File/JSONFile.java index 033afb17d..320a27641 100644 --- a/src/main/java/org/maxgamer/quickshop/File/JSONFile.java +++ b/src/main/java/org/maxgamer/quickshop/File/JSONFile.java @@ -11,42 +11,42 @@ import java.nio.charset.StandardCharsets; public final class JSONFile extends FileEnvelope { public JSONFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath, - boolean loadDefault) { + boolean loadDefault) { super( - plugin, - file, - resourcePath.endsWith(".json") - ? resourcePath - : resourcePath + ".json", - loadDefault + plugin, + file, + resourcePath.endsWith(".json") + ? resourcePath + : resourcePath + ".json", + loadDefault ); } public JSONFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath) { super( - plugin, - file, - resourcePath.endsWith(".json") - ? resourcePath - : resourcePath + ".json", - true + plugin, + file, + resourcePath.endsWith(".json") + ? resourcePath + : resourcePath + ".json", + true ); } public JSONFile(@NotNull final Plugin plugin, @NotNull final String resourcePath, @NotNull final String fileName) { this( - plugin, - new File( - plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") - ? resourcePath - : "/" + resourcePath), - fileName.endsWith(".json") ? fileName : fileName + ".json" - ), - resourcePath.isEmpty() - ? fileName - : resourcePath.endsWith("/") - ? resourcePath + fileName - : resourcePath + "/" + fileName + plugin, + new File( + plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") + ? resourcePath + : "/" + resourcePath), + fileName.endsWith(".json") ? fileName : fileName + ".json" + ), + resourcePath.isEmpty() + ? fileName + : resourcePath.endsWith("/") + ? resourcePath + fileName + : resourcePath + "/" + fileName ); } @@ -59,12 +59,12 @@ public final class JSONFile extends FileEnvelope { fileConfiguration = JSONConfiguration.loadConfiguration(file); if (loadDefault) { fileConfiguration.setDefaults( - JSONConfiguration.loadConfiguration( - new InputStreamReader( - getInputStream(), - StandardCharsets.UTF_8 + JSONConfiguration.loadConfiguration( + new InputStreamReader( + getInputStream(), + StandardCharsets.UTF_8 + ) ) - ) ); } } diff --git a/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java b/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java index 56b26e8fd..9fca0f653 100644 --- a/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java +++ b/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java @@ -10,42 +10,42 @@ import java.io.InputStreamReader; public final class YAMLFile extends FileEnvelope { public YAMLFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath, - boolean loadDefault) { + boolean loadDefault) { super( - plugin, - file, - resourcePath.endsWith(".yml") - ? resourcePath - : resourcePath + ".yml", - loadDefault + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + loadDefault ); } public YAMLFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath) { super( - plugin, - file, - resourcePath.endsWith(".yml") - ? resourcePath - : resourcePath + ".yml", - true + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + true ); } public YAMLFile(@NotNull final Plugin plugin, @NotNull final String resourcePath, @NotNull final String fileName) { this( - plugin, - new File( - plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") - ? resourcePath - : "/" + resourcePath), - fileName.endsWith(".yml") ? fileName : fileName + ".yml" - ), - resourcePath.isEmpty() - ? fileName - : resourcePath.endsWith("/") - ? resourcePath + fileName - : resourcePath + "/" + fileName + plugin, + new File( + plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") + ? resourcePath + : "/" + resourcePath), + fileName.endsWith(".yml") ? fileName : fileName + ".yml" + ), + resourcePath.isEmpty() + ? fileName + : resourcePath.endsWith("/") + ? resourcePath + fileName + : resourcePath + "/" + fileName ); } @@ -58,11 +58,11 @@ public final class YAMLFile extends FileEnvelope { fileConfiguration = YamlConfiguration.loadConfiguration(file); if (loadDefault) { fileConfiguration.setDefaults( - YamlConfiguration.loadConfiguration( - new InputStreamReader( - getInputStream() + YamlConfiguration.loadConfiguration( + new InputStreamReader( + getInputStream() + ) ) - ) ); } } diff --git a/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java b/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java index fae89e2ae..037f97f81 100644 --- a/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java +++ b/src/main/java/org/maxgamer/quickshop/InternalListener/InternalListener.java @@ -71,16 +71,16 @@ public class InternalListener implements Listener { return; } if (event.getShop().getShopType() == ShopType.BUYING) { - plugin.log("Player " + event.getPlayer().getName() + " sold " + event.getShop().ownerName() + " shop "+event.getShop()+" for items x" + event + plugin.log("Player " + event.getPlayer().getName() + " sold " + event.getShop().ownerName() + " shop " + event.getShop() + " for items x" + event .getAmount() + " for " + plugin.getEconomy().format(event.getBalance()) + " (" + plugin.getEconomy() .format(event.getTax()) + " tax)."); } if (event.getShop().getShopType() == ShopType.SELLING) { - plugin.log("Player " + event.getPlayer().getName() + " bought " + event.getShop().ownerName() + " shop "+event.getShop()+" for items x" + event + plugin.log("Player " + event.getPlayer().getName() + " bought " + event.getShop().ownerName() + " shop " + event.getShop() + " for items 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/ClearLaggListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/ClearLaggListener.java index 959153a69..d234f24f4 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/ClearLaggListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/ClearLaggListener.java @@ -43,7 +43,7 @@ public class ClearLaggListener implements Listener { for (Entity entity : entities) { if (!(entity instanceof Item) || - !DisplayItem.checkIsGuardItemStack(((Item) entity).getItemStack())) { + !DisplayItem.checkIsGuardItemStack(((Item) entity).getItemStack())) { continue; } diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/CustomInventoryListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/CustomInventoryListener.java index dceb2546a..1a1e5ffb0 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/CustomInventoryListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/CustomInventoryListener.java @@ -90,7 +90,7 @@ public class CustomInventoryListener implements Listener { } if (InventoryPreview.isPreviewItem(e.getCursor()) || - InventoryPreview.isPreviewItem(e.getOldCursor())) { + InventoryPreview.isPreviewItem(e.getOldCursor())) { e.setCancelled(true); e.setResult(Result.DENY); } diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/DisplayBugFixListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/DisplayBugFixListener.java index af27f4ea2..73940a916 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/DisplayBugFixListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/DisplayBugFixListener.java @@ -42,9 +42,9 @@ public class DisplayBugFixListener implements Listener { @EventHandler(ignoreCancelled = true) public void canBuild(BlockCanBuildEvent e) { if (ListenerHelper.isDisabled(e.getClass()) || - !plugin.isDisplay() || - DisplayItem.getNowUsing() != DisplayType.ARMORSTAND || - e.isBuildable()) { + !plugin.isDisplay() || + DisplayItem.getNowUsing() != DisplayType.ARMORSTAND || + e.isBuildable()) { return; } @@ -52,7 +52,7 @@ public class DisplayBugFixListener implements Listener { for (Entity entity : entities) { if (!(entity instanceof ArmorStand) || - !DisplayItem.checkIsGuardItemStack(((ArmorStand) entity).getItemInHand())) { + !DisplayItem.checkIsGuardItemStack(((ArmorStand) entity).getItemInHand())) { continue; } diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/DisplayProtectionListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/DisplayProtectionListener.java index 66e69b8ed..4429a9f8c 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/DisplayProtectionListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/DisplayProtectionListener.java @@ -78,7 +78,7 @@ public class DisplayProtectionListener implements Listener { return; } event.setCancelled(true); - if(shop.getDisplay() != null){ + if (shop.getDisplay() != null) { shop.getDisplay().remove(); } sendAlert("[DisplayGuard] Liuqid " + targetBlock.getLocation() + " trying flow to top of shop, QuickShop already cancel it."); @@ -113,7 +113,7 @@ public class DisplayProtectionListener implements Listener { if (shop != null) { event.setCancelled(true); sendAlert("[DisplayGuard] Piston " + event.getBlock().getLocation() + " trying push somethings on the shop top, QuickShop already cancel it."); - if(shop.getDisplay() != null){ + if (shop.getDisplay() != null) { shop.getDisplay().remove(); } return; @@ -122,12 +122,12 @@ public class DisplayProtectionListener implements Listener { Block otherBlock = oBlock.getRelative(event.getDirection()).getRelative(BlockFace.DOWN); if (Util.canBeShop(otherBlock)) { shop = plugin.getShopManager().getShopIncludeAttached(otherBlock.getLocation()); - if (shop != null) { + if (shop != null) { event.setCancelled(true); sendAlert("[DisplayGuard] Piston " + event.getBlock().getLocation() + " trying push somethings on the shop top, QuickShop already cancel it."); - if(shop.getDisplay() != null){ - shop.getDisplay().remove(); - } + if (shop.getDisplay() != null) { + shop.getDisplay().remove(); + } return; } } @@ -147,7 +147,7 @@ public class DisplayProtectionListener implements Listener { if (shop != null) { event.setCancelled(true); sendAlert("[DisplayGuard] Piston " + event.getBlock().getLocation() + " trying pull somethings on the shop top, QuickShop already cancel it."); - if(shop.getDisplay() != null){ + if (shop.getDisplay() != null) { shop.getDisplay().remove(); } return; @@ -159,7 +159,7 @@ public class DisplayProtectionListener implements Listener { if (shop != null) { event.setCancelled(true); sendAlert("[DisplayGuard] Piston " + event.getBlock().getLocation() + " trying push somethings on the shop top, QuickShop already cancel it."); - if(shop.getDisplay() != null){ + if (shop.getDisplay() != null) { shop.getDisplay().remove(); } return; diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java index e51b8064f..aa0777c24 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java @@ -261,20 +261,20 @@ public class PlayerListener implements Listener { @Nullable Inventory inventory = e.getInventory(); // Possibly wrong tag @Nullable Location location = null; - + try { // This will cause NPE when the internal getLocation method // itself NPE, which should be a server issue. location = inventory.getLocation(); } catch (NullPointerException npe) { return; // ignored as workaround, GH-303 - } - + } + if (location == null) return; final Shop shop = plugin.getShopManager().getShopIncludeAttached(location); - + if (shop != null) shop.setSignText(); } diff --git a/src/main/java/org/maxgamer/quickshop/Metrics.java b/src/main/java/org/maxgamer/quickshop/Metrics.java index 51a553f99..31c89667a 100644 --- a/src/main/java/org/maxgamer/quickshop/Metrics.java +++ b/src/main/java/org/maxgamer/quickshop/Metrics.java @@ -59,31 +59,10 @@ public class Metrics { // 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. - */ - @Nullable - 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. * @@ -147,6 +126,25 @@ public class Metrics { } } + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + @Nullable + 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(); + } + /** * Adds a custom chart. * diff --git a/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java b/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java index 4344ddd99..96a3bae3f 100644 --- a/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java +++ b/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java @@ -3,6 +3,7 @@ package org.maxgamer.quickshop.Mock; import lombok.ToString; import org.bukkit.configuration.file.FileConfiguration; import org.jetbrains.annotations.NotNull; + @ToString public final class MckFileConfiguration extends FileConfiguration { @NotNull @@ -10,9 +11,11 @@ public final class MckFileConfiguration extends FileConfiguration { public String saveToString() { return ""; } + @Override public void loadFromString(@NotNull String s) { } + @NotNull @Override protected String buildHeader() { 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 61b5b1b7c..9e1a29ac6 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 @@ -25,13 +25,41 @@ public final class JSONConfiguration extends FileConfiguration { protected static final String BLANK_CONFIG = "{}\n"; + @NotNull + public static JSONConfiguration loadConfiguration(@NotNull File file) { + final JSONConfiguration config = new JSONConfiguration(); + + try { + config.load(file); + } catch (FileNotFoundException ignored) { + // ignored... + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } + + return config; + } + + @NotNull + public static JSONConfiguration loadConfiguration(@NotNull Reader reader) { + final JSONConfiguration config = new JSONConfiguration(); + + try { + config.load(reader); + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } + + return config; + } + @NotNull @Override public String saveToString() { final GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping(); //if (!options().prettyPrint()) { - gsonBuilder.setPrettyPrinting(); + gsonBuilder.setPrettyPrinting(); //} final Gson gson = gsonBuilder.create(); final Object value = SerializationHelper.serialize(getValues(false)); @@ -54,10 +82,12 @@ public final class JSONConfiguration extends FileConfiguration { try { final Gson gson = new GsonBuilder() - .registerTypeAdapter(new TypeToken>(){}.getType(), - new MapDeserializerDoubleAsIntFix()) - .create(); - input = gson.fromJson(contents, new TypeToken>(){}.getType()); + .registerTypeAdapter(new TypeToken>() { + }.getType(), + new MapDeserializerDoubleAsIntFix()) + .create(); + input = gson.fromJson(contents, new TypeToken>() { + }.getType()); } catch (JsonSyntaxException e) { throw new InvalidConfigurationException("Invalid JSON detected.", e); } catch (ClassCastException e) { @@ -108,72 +138,45 @@ public final class JSONConfiguration extends FileConfiguration { return (JSONConfigurationOptions) options; } - @NotNull - public static JSONConfiguration loadConfiguration(@NotNull File file) { - final JSONConfiguration config = new JSONConfiguration(); - - try { - config.load(file); - } catch (FileNotFoundException ignored) { - // ignored... - } catch (IOException | InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); - } - - return config; - } - - @NotNull - public static JSONConfiguration loadConfiguration(@NotNull Reader reader) { - final JSONConfiguration config = new JSONConfiguration(); - - try { - config.load(reader); - } catch (IOException | InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); - } - - return config; - } - public static class MapDeserializerDoubleAsIntFix implements JsonDeserializer> { - @Override @SuppressWarnings("unchecked") + @Override + @SuppressWarnings("unchecked") public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return (Map) read(json); } public Object read(JsonElement in) { - if(in.isJsonArray()){ + if (in.isJsonArray()) { List list = new ArrayList(); JsonArray arr = in.getAsJsonArray(); for (JsonElement anArr : arr) { list.add(read(anArr)); } return list; - }else if(in.isJsonObject()){ + } else if (in.isJsonObject()) { Map map = new LinkedTreeMap(); JsonObject obj = in.getAsJsonObject(); Set> entitySet = obj.entrySet(); - for(Map.Entry entry: entitySet){ + for (Map.Entry entry : entitySet) { map.put(entry.getKey(), read(entry.getValue())); } return map; - }else if( in.isJsonPrimitive()){ + } else if (in.isJsonPrimitive()) { JsonPrimitive prim = in.getAsJsonPrimitive(); - if(prim.isBoolean()){ + if (prim.isBoolean()) { return prim.getAsBoolean(); - }else if(prim.isString()){ + } else if (prim.isString()) { return prim.getAsString(); - }else if(prim.isNumber()){ + } else if (prim.isNumber()) { Number num = prim.getAsNumber(); // here you can handle double int/long values // and return any type you want // this solution will transform 3.0 float to long values - if(Math.ceil(num.doubleValue()) == num.longValue()) + if (Math.ceil(num.doubleValue()) == num.longValue()) return num.longValue(); - else{ + else { return num.doubleValue(); } } 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 780533410..7974585f0 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 @@ -64,16 +64,16 @@ public class SerializationHelper { /** * Takes a Map and parses through the values, to ensure that, before saving, all objects are as appropriate as * possible for storage in most data formats. - * + *

* Specifically it does the following: - * for Map: calls this method recursively on the Map before putting it in the returned Map. - * for List: calls {@link #buildList(java.util.Collection)} which functions similar to this method. - * for ConfigurationSection: gets the values as a map and calls this method recursively on the Map before putting - * it in the returned Map. - * for ConfigurationSerializable: add the {@link ConfigurationSerialization#SERIALIZED_TYPE_KEY} to a new Map - * along with the Map given by {@link org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()} - * and calls this method recursively on the new Map before putting it in the returned Map. - * for Everything else: stores it as is in the returned Map. + * for Map: calls this method recursively on the Map before putting it in the returned Map. + * for List: calls {@link #buildList(java.util.Collection)} which functions similar to this method. + * for ConfigurationSection: gets the values as a map and calls this method recursively on the Map before putting + * it in the returned Map. + * for ConfigurationSerializable: add the {@link ConfigurationSerialization#SERIALIZED_TYPE_KEY} to a new Map + * along with the Map given by {@link org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()} + * and calls this method recursively on the new Map before putting it in the returned Map. + * for Everything else: stores it as is in the returned Map. */ @NotNull private static Map buildMap(@NotNull final Map map) { @@ -91,16 +91,16 @@ public class SerializationHelper { /** * Takes a Collection and parses through the values, to ensure that, before saving, all objects are as appropriate * as possible for storage in most data formats. - * + *

* Specifically it does the following: - * for Map: calls {@link #buildMap(java.util.Map)} on the Map before adding to the returned list. - * for List: calls this method recursively on the List. - * for ConfigurationSection: gets the values as a map and calls {@link #buildMap(java.util.Map)} on the Map - * before adding to the returned list. - * for ConfigurationSerializable: add the {@link ConfigurationSerialization#SERIALIZED_TYPE_KEY} to a new Map - * along with the Map given by {@link org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()} - * and calls {@link #buildMap(java.util.Map)} on the new Map before adding to the returned list. - * for Everything else: stores it as is in the returned List. + * for Map: calls {@link #buildMap(java.util.Map)} on the Map before adding to the returned list. + * for List: calls this method recursively on the List. + * for ConfigurationSection: gets the values as a map and calls {@link #buildMap(java.util.Map)} on the Map + * before adding to the returned list. + * for ConfigurationSerializable: add the {@link ConfigurationSerialization#SERIALIZED_TYPE_KEY} to a new Map + * along with the Map given by {@link org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()} + * and calls {@link #buildMap(java.util.Map)} on the new Map before adding to the returned list. + * for Everything else: stores it as is in the returned List. */ private static List buildList(@NotNull final Collection collection) { final List result = new ArrayList(collection.size()); @@ -116,10 +116,11 @@ public class SerializationHelper { /** * Parses through the input map to deal with serialized objects a la {@link ConfigurationSerializable}. - * + *

* Called recursively first on Maps and Lists before passing the parsed input over to * {@link ConfigurationSerialization#deserializeObject(java.util.Map)}. Basically this means it will deserialize * the most nested objects FIRST and the top level object LAST. + * * @param input the input * @return the object that deserialize */ @@ -128,7 +129,7 @@ public class SerializationHelper { for (final Map.Entry e : input.entrySet()) { if (e.getValue() instanceof Map) { output.put(e.getKey().toString(), deserialize((Map) e.getValue())); - } else if (e.getValue() instanceof List) { + } else if (e.getValue() instanceof List) { output.put(e.getKey().toString(), deserialize((List) e.getValue())); } else { output.put(e.getKey().toString(), e.getValue()); @@ -146,7 +147,7 @@ public class SerializationHelper { /** * Parses through the input list to deal with serialized objects a la {@link ConfigurationSerializable}. - * + *

* Functions similarly to {@link #deserialize(java.util.Map)} but only for detecting lists within * lists and maps within lists. */ diff --git a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/sk89q/worldedit/util/net/HttpRequest.java b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/sk89q/worldedit/util/net/HttpRequest.java index 56f28f4c5..c0baf31ec 100644 --- a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/sk89q/worldedit/util/net/HttpRequest.java +++ b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/com/sk89q/worldedit/util/net/HttpRequest.java @@ -55,6 +55,72 @@ public class HttpRequest implements Closeable { this.url = url; } + /** + * Perform a GET request. + * + * @param url the URL + * @return a new request object + */ + public static HttpRequest get(URL url) { + return request("GET", url); + } + + /** + * Perform a POST request. + * + * @param url the URL + * @return a new request object + */ + public static HttpRequest post(URL url) { + return request("POST", url); + } + + /** + * Perform a request. + * + * @param method the method + * @param url the URL + * @return a new request object + */ + public static HttpRequest request(String method, URL url) { + return new HttpRequest(method, url); + } + + /** + * Create a new {@link java.net.URL} and throw a {@link RuntimeException} if the URL + * is not valid. + * + * @param url the url + * @return a URL object + * @throws RuntimeException if the URL is invalid + */ + public static URL url(String url) { + try { + return new URL(url); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + /** + * URL may contain spaces and other nasties that will cause a failure. + * + * @param existing the existing URL to transform + * @return the new URL, or old one if there was a failure + */ + private static URL reformat(URL existing) { + try { + URL url = new URL(existing.toString()); + URI uri = new URI( + url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), + url.getPath(), url.getQuery(), url.getRef()); + url = uri.toURL(); + return url; + } catch (MalformedURLException | URISyntaxException e) { + return existing; + } + } + /** * Submit data. * @@ -96,7 +162,7 @@ public class HttpRequest implements Closeable { /** * Execute the request. - * + *

* After execution, {@link #close()} should be called. * * @return this object @@ -198,7 +264,7 @@ public class HttpRequest implements Closeable { * Buffer the returned response. * * @return the buffered response - * @throws java.io.IOException on I/O error + * @throws java.io.IOException on I/O error */ public BufferedResponse returnContent() throws IOException { if (inputStream == null) { @@ -222,7 +288,7 @@ public class HttpRequest implements Closeable { * * @param file the file * @return this object - * @throws java.io.IOException on I/O error + * @throws java.io.IOException on I/O error */ public HttpRequest saveContent(File file) throws IOException { @@ -241,7 +307,7 @@ public class HttpRequest implements Closeable { * * @param out the output stream * @return this object - * @throws java.io.IOException on I/O error + * @throws java.io.IOException on I/O error */ public HttpRequest saveContent(OutputStream out) throws IOException { BufferedInputStream bis; @@ -278,72 +344,6 @@ public class HttpRequest implements Closeable { if (conn != null) conn.disconnect(); } - /** - * Perform a GET request. - * - * @param url the URL - * @return a new request object - */ - public static HttpRequest get(URL url) { - return request("GET", url); - } - - /** - * Perform a POST request. - * - * @param url the URL - * @return a new request object - */ - public static HttpRequest post(URL url) { - return request("POST", url); - } - - /** - * Perform a request. - * - * @param method the method - * @param url the URL - * @return a new request object - */ - public static HttpRequest request(String method, URL url) { - return new HttpRequest(method, url); - } - - /** - * Create a new {@link java.net.URL} and throw a {@link RuntimeException} if the URL - * is not valid. - * - * @param url the url - * @return a URL object - * @throws RuntimeException if the URL is invalid - */ - public static URL url(String url) { - try { - return new URL(url); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - /** - * URL may contain spaces and other nasties that will cause a failure. - * - * @param existing the existing URL to transform - * @return the new URL, or old one if there was a failure - */ - private static URL reformat(URL existing) { - try { - URL url = new URL(existing.toString()); - URI uri = new URI( - url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), - url.getPath(), url.getQuery(), url.getRef()); - url = uri.toURL(); - return url; - } catch (MalformedURLException | URISyntaxException e) { - return existing; - } - } - /** * Used with {@link #bodyForm(Form)}. */ @@ -353,6 +353,15 @@ public class HttpRequest implements Closeable { private Form() { } + /** + * Create a new form. + * + * @return a new form + */ + public static Form create() { + return new Form(); + } + /** * Add a key/value to the form. * @@ -384,15 +393,6 @@ public class HttpRequest implements Closeable { } return builder.toString(); } - - /** - * Create a new form. - * - * @return a new form - */ - public static Form create() { - return new Form(); - } } /** @@ -430,7 +430,7 @@ public class HttpRequest implements Closeable { * * @param file the file * @return this object - * @throws java.io.IOException on I/O error + * @throws java.io.IOException on I/O error */ public BufferedResponse saveContent(File file) throws IOException { @@ -450,7 +450,7 @@ public class HttpRequest implements Closeable { * * @param out the output stream * @return this object - * @throws java.io.IOException on I/O error + * @throws java.io.IOException on I/O error */ public BufferedResponse saveContent(OutputStream out) throws IOException { out.write(data); diff --git a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/Colorizer.java b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/Colorizer.java index eeb7d000d..97558b56e 100644 --- a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/Colorizer.java +++ b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/Colorizer.java @@ -29,6 +29,13 @@ public class Colorizer { private static Map colorCodes = new HashMap<>(); + static { + for (ChatColor color : ChatColor.values()) { + colorCodes.put(color.name().replace("_", ""), String.valueOf(color.getChar())); + colorCodes.put(color.name(), String.valueOf(color.getChar())); + } + } + public static String setColors(String text) { for (String color : colorCodes.keySet()) { text = text.replaceAll("(?i)<" + color + ">", ChatColor.COLOR_CHAR + colorCodes.get(color)); @@ -46,11 +53,4 @@ public class Colorizer { text = ChatColor.stripColor(text); return text; } - - static { - for (ChatColor color : ChatColor.values()) { - colorCodes.put(color.name().replace("_", ""), String.valueOf(color.getChar())); - colorCodes.put(color.name(), String.valueOf(color.getChar())); - } - } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/LogFormat.java b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/LogFormat.java index e225f8f5e..78127566c 100644 --- a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/LogFormat.java +++ b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/de/Keyle/MyPet/api/util/LogFormat.java @@ -31,7 +31,7 @@ import java.util.logging.LogRecord; public class LogFormat extends Formatter { @Override public String format(LogRecord record) { - String text = "["+new SimpleDateFormat("HH:mm:ss").format(new Date(record.getMillis())); + String text = "[" + new SimpleDateFormat("HH:mm:ss").format(new Date(record.getMillis())); Level level = record.getLevel(); if (level == Level.WARNING) { diff --git a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/me/lucko/spark/common/util/FormatUtil.java b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/me/lucko/spark/common/util/FormatUtil.java index e702bb79f..6db8dfb93 100644 --- a/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/me/lucko/spark/common/util/FormatUtil.java +++ b/src/main/java/org/maxgamer/quickshop/NonQuickShopStuffs/me/lucko/spark/common/util/FormatUtil.java @@ -2,6 +2,7 @@ package org.maxgamer.quickshop.NonQuickShopStuffs.me.lucko.spark.common.util; public enum FormatUtil { ; + public static String percent(double value, double max) { double percent = (value * 100d) / max; return (int) percent + "%"; diff --git a/src/main/java/org/maxgamer/quickshop/Permission/PermissionProviderType.java b/src/main/java/org/maxgamer/quickshop/Permission/PermissionProviderType.java index bdbfecad7..d55e85eaa 100644 --- a/src/main/java/org/maxgamer/quickshop/Permission/PermissionProviderType.java +++ b/src/main/java/org/maxgamer/quickshop/Permission/PermissionProviderType.java @@ -28,10 +28,6 @@ public enum PermissionProviderType { this.id = id; } - public int toID() { - return this.id; - } - public static PermissionProviderType fromID(int id) throws IllegalArgumentException { for (PermissionProviderType child : PermissionProviderType.values()) { if (child.toID() == id) { @@ -40,4 +36,8 @@ public enum PermissionProviderType { } throw new IllegalArgumentException("Type not exists"); } + + public int toID() { + return this.id; + } } diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/FactionsUUID/FactionsUUIDIntegration.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/FactionsUUID/FactionsUUIDIntegration.java index 49567cd9f..554925e7b 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/FactionsUUID/FactionsUUIDIntegration.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/FactionsUUID/FactionsUUIDIntegration.java @@ -52,7 +52,7 @@ public class FactionsUUIDIntegration implements IntegratedPlugin { private boolean tradeRequireOwn; private boolean tradeRequireWarZone; - public FactionsUUIDIntegration(QuickShop plugin){ + public FactionsUUIDIntegration(QuickShop plugin) { this.createFlags = plugin.getConfig().getStringList("integration.factions.create.flags"); this.tradeFlags = plugin.getConfig().getStringList("integration.factions.trade.flags"); @@ -84,39 +84,39 @@ public class FactionsUUIDIntegration implements IntegratedPlugin { @Override public boolean canCreateShopHere(@NotNull Player player, @NotNull Location location) { Faction faction = Board.getInstance().getFactionAt(new FLocation(location)); - if(faction == null){ + if (faction == null) { return true; } - if(createRequireOpen && !faction.getOpen()){ + if (createRequireOpen && !faction.getOpen()) { return false; } - if(createRequireSafeZone && !faction.isSafeZone()){ + if (createRequireSafeZone && !faction.isSafeZone()) { return false; } - if(createRequirePermanent && !faction.isPermanent()){ + if (createRequirePermanent && !faction.isPermanent()) { return false; } - if(createRequirePeaceful && !faction.isPeaceful()){ + if (createRequirePeaceful && !faction.isPeaceful()) { return false; } - if(createRequireWilderness && !faction.isWilderness()){ + if (createRequireWilderness && !faction.isWilderness()) { return false; } - if(createRequireOpen && !faction.getOpen()){ + if (createRequireOpen && !faction.getOpen()) { return false; } - if(createRequireWarZone && !faction.isWarZone()){ + if (createRequireWarZone && !faction.isWarZone()) { return false; } - if(createRequireNormal && !faction.isNormal()){ + if (createRequireNormal && !faction.isNormal()) { return false; } - if(createRequireOwn && !faction.getOwnerList(new FLocation(location)).contains(player.getName())){ + if (createRequireOwn && !faction.getOwnerList(new FLocation(location)).contains(player.getName())) { return false; } - for (String flag: - createFlags) { - if(!faction.hasAccess(FPlayers.getInstance().getByPlayer(player),PermissibleAction.fromString(flag))){ + for (String flag : + createFlags) { + if (!faction.hasAccess(FPlayers.getInstance().getByPlayer(player), PermissibleAction.fromString(flag))) { return false; } @@ -128,39 +128,39 @@ public class FactionsUUIDIntegration implements IntegratedPlugin { public boolean canTradeShopHere(@NotNull Player player, @NotNull Location location) { Faction faction = Board.getInstance().getFactionAt(new FLocation(location)); - if(faction == null){ + if (faction == null) { return true; } - if(tradeRequireOpen && !faction.getOpen()){ + if (tradeRequireOpen && !faction.getOpen()) { return false; } - if(tradeRequireSafeZone && !faction.isSafeZone()){ + if (tradeRequireSafeZone && !faction.isSafeZone()) { return false; } - if(tradeRequirePermanent && !faction.isPermanent()){ + if (tradeRequirePermanent && !faction.isPermanent()) { return false; } - if(tradeRequirePeaceful && !faction.isPeaceful()){ + if (tradeRequirePeaceful && !faction.isPeaceful()) { return false; } - if(tradeRequireWilderness && !faction.isWilderness()){ + if (tradeRequireWilderness && !faction.isWilderness()) { return false; } - if(tradeRequireOpen && !faction.getOpen()){ + if (tradeRequireOpen && !faction.getOpen()) { return false; } - if(tradeRequireWarZone && !faction.isWarZone()){ + if (tradeRequireWarZone && !faction.isWarZone()) { return false; } - if(tradeRequireNormal && !faction.isNormal()){ + if (tradeRequireNormal && !faction.isNormal()) { return false; } - if(tradeRequireOwn && !faction.getOwnerList(new FLocation(location)).contains(player.getName())){ + if (tradeRequireOwn && !faction.getOwnerList(new FLocation(location)).contains(player.getName())) { return false; } - for (String flag: + for (String flag : tradeFlags) { - if(!faction.hasAccess(FPlayers.getInstance().getByPlayer(player),PermissibleAction.fromString(flag))){ + if (!faction.hasAccess(FPlayers.getInstance().getByPlayer(player), PermissibleAction.fromString(flag))) { return false; } diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegratedPlugin.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegratedPlugin.java index 807d4f34f..41bf8b9e9 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegratedPlugin.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegratedPlugin.java @@ -25,8 +25,12 @@ import org.jetbrains.annotations.NotNull; public interface IntegratedPlugin { @NotNull String getName(); + boolean canCreateShopHere(@NotNull Player player, @NotNull Location location); + boolean canTradeShopHere(@NotNull Player player, @NotNull Location location); + void load(); + void unload(); } diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegrationStage.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegrationStage.java index ff5c7adef..733b32933 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegrationStage.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/IntegrationStage.java @@ -27,5 +27,6 @@ import java.lang.annotation.*; @Inherited public @interface IntegrationStage { IntegrateStage loadStage() default IntegrateStage.onEnableAfter; + IntegrateStage unloadStage() default IntegrateStage.onUnloadBegin; } diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/PlotSquared/PlotSquaredIntegration.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/PlotSquared/PlotSquaredIntegration.java index 41ac0cabe..7a510c938 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/PlotSquared/PlotSquaredIntegration.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/PlotSquared/PlotSquaredIntegration.java @@ -40,10 +40,12 @@ public class PlotSquaredIntegration implements IntegratedPlugin { private BooleanFlag createFlag; private BooleanFlag tradeFlag; private QuickShop plugin; - public PlotSquaredIntegration(QuickShop plugin){ + + public PlotSquaredIntegration(QuickShop plugin) { this.plugin = plugin; this.plotAPI = new PlotAPI(); } + @Override public @NotNull String getName() { return "PlotSquared"; @@ -51,14 +53,14 @@ public class PlotSquaredIntegration implements IntegratedPlugin { @Override public boolean canCreateShopHere(@NotNull Player player, @NotNull Location location) { - com.github.intellectualsites.plotsquared.plot.object.Location pLocation = new com.github.intellectualsites.plotsquared.plot.object.Location(location.getWorld().getName(),location.getBlockX(),location.getBlockY(),location.getBlockZ()); + com.github.intellectualsites.plotsquared.plot.object.Location pLocation = new com.github.intellectualsites.plotsquared.plot.object.Location(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); Plot plot = pLocation.getPlot(); return this.createFlag.isTrue(plot); } @Override public boolean canTradeShopHere(@NotNull Player player, @NotNull Location location) { - com.github.intellectualsites.plotsquared.plot.object.Location pLocation = new com.github.intellectualsites.plotsquared.plot.object.Location(location.getWorld().getName(),location.getBlockX(),location.getBlockY(),location.getBlockZ()); + com.github.intellectualsites.plotsquared.plot.object.Location pLocation = new com.github.intellectualsites.plotsquared.plot.object.Location(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); Plot plot = pLocation.getPlot(); return this.tradeFlag.isFalse(plot); } @@ -69,8 +71,8 @@ public class PlotSquaredIntegration implements IntegratedPlugin { this.tradeFlag = new BooleanFlag("quickshop-trade"); Flags.registerFlag(this.createFlag); Flags.registerFlag(this.tradeFlag); - plugin.getLogger().info(ChatColor.GREEN+getName()+" flags register successfully."); - Util.debugLog("Success register "+getName()+" flags."); + plugin.getLogger().info(ChatColor.GREEN + getName() + " flags register successfully."); + Util.debugLog("Success register " + getName() + " flags."); } @Override diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Residence/ResidenceIntegration.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Residence/ResidenceIntegration.java index 76a60c99c..38f4382d6 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Residence/ResidenceIntegration.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Residence/ResidenceIntegration.java @@ -36,10 +36,11 @@ public class ResidenceIntegration implements IntegratedPlugin { List createLimits; List tradeLimits; - public ResidenceIntegration(QuickShop plugin){ + public ResidenceIntegration(QuickShop plugin) { this.createLimits = plugin.getConfig().getStringList("integration.residence.create"); this.tradeLimits = plugin.getConfig().getStringList("integration.residence.trade"); } + @Override public @NotNull String getName() { return "Residence"; @@ -50,27 +51,27 @@ public class ResidenceIntegration implements IntegratedPlugin { ClaimedResidence residence = Residence.getInstance().getResidenceManager().getByLoc(location); - for (String limit:this.createLimits) { - if("FLAG".equalsIgnoreCase(limit)){ - if(residence == null){ + for (String limit : this.createLimits) { + if ("FLAG".equalsIgnoreCase(limit)) { + if (residence == null) { //Check world permission - if(!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag("quickshop-create"), false)){ + if (!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag("quickshop-create"), false)) { return false; } - }else{ - if(!residence.getPermissions().playerHas(player,Flags.getFlag("quickshop-create"),false)){ + } else { + if (!residence.getPermissions().playerHas(player, Flags.getFlag("quickshop-create"), false)) { return false; } } } //Not flag - if(residence == null){ - if(!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag(limit), false)){ + if (residence == null) { + if (!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag(limit), false)) { return false; } - }else{ - if(!residence.getPermissions().playerHas(player,Flags.getFlag(limit),false)){ + } else { + if (!residence.getPermissions().playerHas(player, Flags.getFlag(limit), false)) { return false; } } @@ -84,27 +85,27 @@ public class ResidenceIntegration implements IntegratedPlugin { ClaimedResidence residence = Residence.getInstance().getResidenceManager().getByLoc(location); - for (String limit:this.createLimits) { - if("FLAG".equalsIgnoreCase(limit)){ - if(residence == null){ + for (String limit : this.createLimits) { + if ("FLAG".equalsIgnoreCase(limit)) { + if (residence == null) { //Check world permission - if(!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag("quickshop-trade"), false)){ + if (!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag("quickshop-trade"), false)) { return false; } - }else{ - if(!residence.getPermissions().playerHas(player,Flags.getFlag("quickshop-trade"),true)){ + } else { + if (!residence.getPermissions().playerHas(player, Flags.getFlag("quickshop-trade"), true)) { return false; } } } //Not flag - if(residence == null){ - if(!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag(limit), false)){ + if (residence == null) { + if (!Residence.getInstance().getWorldFlags().getPerms(location.getWorld().getName()).playerHas(player, Flags.getFlag(limit), false)) { return false; } - }else{ - if(!residence.getPermissions().playerHas(player,Flags.getFlag(limit),false)){ + } else { + if (!residence.getPermissions().playerHas(player, Flags.getFlag(limit), false)) { return false; } } diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyFlags.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyFlags.java index 12292955c..e020c1b4e 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyFlags.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyFlags.java @@ -23,7 +23,7 @@ import java.util.ArrayList; import java.util.List; public enum TownyFlags { - OWN,MODIFY,SHOPTYPE; + OWN, MODIFY, SHOPTYPE; public static List deserialize(List list) { List result = new ArrayList<>(); diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyIntegration.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyIntegration.java index 724005dd8..1230d795b 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyIntegration.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/Towny/TownyIntegration.java @@ -35,10 +35,12 @@ import java.util.List; public class TownyIntegration implements IntegratedPlugin { private List createFlags; private List tradeFlags; - public TownyIntegration(QuickShop plugin){ + + public TownyIntegration(QuickShop plugin) { createFlags = TownyFlags.deserialize(plugin.getConfig().getStringList("integration.towny.create")); tradeFlags = TownyFlags.deserialize(plugin.getConfig().getStringList("integration.towny.trade")); } + @Override public @NotNull String getName() { return "Towny"; @@ -46,20 +48,20 @@ public class TownyIntegration implements IntegratedPlugin { @Override public boolean canCreateShopHere(@NotNull Player player, @NotNull Location location) { - for(TownyFlags flag : createFlags){ - switch (flag){ + for (TownyFlags flag : createFlags) { + switch (flag) { case OWN: - if(!ShopPlotUtil.doesPlayerOwnShopPlot(player,location)){ + if (!ShopPlotUtil.doesPlayerOwnShopPlot(player, location)) { return false; } break; case MODIFY: - if(!ShopPlotUtil.doesPlayerHaveAbilityToEditShopPlot(player,location)){ + if (!ShopPlotUtil.doesPlayerHaveAbilityToEditShopPlot(player, location)) { return false; } break; case SHOPTYPE: - if(!ShopPlotUtil.isShopPlot(location)){ + if (!ShopPlotUtil.isShopPlot(location)) { return false; } default: @@ -71,20 +73,20 @@ public class TownyIntegration implements IntegratedPlugin { @Override public boolean canTradeShopHere(@NotNull Player player, @NotNull Location location) { - for(TownyFlags flag : tradeFlags){ - switch (flag){ + for (TownyFlags flag : tradeFlags) { + switch (flag) { case OWN: - if(!ShopPlotUtil.doesPlayerOwnShopPlot(player,location)){ + if (!ShopPlotUtil.doesPlayerOwnShopPlot(player, location)) { return false; } break; case MODIFY: - if(!ShopPlotUtil.doesPlayerHaveAbilityToEditShopPlot(player,location)){ + if (!ShopPlotUtil.doesPlayerHaveAbilityToEditShopPlot(player, location)) { return false; } break; case SHOPTYPE: - if(!ShopPlotUtil.isShopPlot(location)){ + if (!ShopPlotUtil.isShopPlot(location)) { return false; } default: diff --git a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/WorldGuard/WorldGuardFlags.java b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/WorldGuard/WorldGuardFlags.java index 88bfc0766..436b21048 100644 --- a/src/main/java/org/maxgamer/quickshop/PluginsIntegration/WorldGuard/WorldGuardFlags.java +++ b/src/main/java/org/maxgamer/quickshop/PluginsIntegration/WorldGuard/WorldGuardFlags.java @@ -23,7 +23,7 @@ import java.util.ArrayList; import java.util.List; public enum WorldGuardFlags { - FLAG, BUILD, CHEST_ACCESS,INTERACT; + FLAG, BUILD, CHEST_ACCESS, INTERACT; public static List deserialize(List list) { List result = new ArrayList<>(); diff --git a/src/main/java/org/maxgamer/quickshop/QuickShop.java b/src/main/java/org/maxgamer/quickshop/QuickShop.java index f3717af71..a124a00be 100644 --- a/src/main/java/org/maxgamer/quickshop/QuickShop.java +++ b/src/main/java/org/maxgamer/quickshop/QuickShop.java @@ -72,7 +72,10 @@ public class QuickShop extends JavaPlugin { * The active instance of QuickShop */ public static QuickShop instance; - + /** + * The manager to check permissions. + */ + private static PermissionManager permissionManager; private IntegrationHelper integrationHelper; // Listeners (These don't) private BlockListener blockListener; @@ -190,10 +193,6 @@ public class QuickShop extends JavaPlugin { */ private HashSet warnings = new HashSet<>(); private WorldListener worldListener; - /** - * The manager to check permissions. - */ - private static PermissionManager permissionManager; private OngoingFeeWatcher ongoingFeeWatcher; private SignUpdateWatcher signUpdateWatcher; private ShopContainerWatcher shopContainerWatcher; @@ -201,6 +200,26 @@ public class QuickShop extends JavaPlugin { private BukkitAPIWrapper bukkitAPIWrapper; private boolean isUtilInited = false; + /** + * Returns QS version, this method only exist on QSRR forks If running other + * QSRR forks,, result may not is "Reremake x.x.x" If running QS offical, Will + * throw exception. + * + * @return Plugin Version + */ + public static String getVersion() { + return QuickShop.instance.getDescription().getVersion(); + } + + /** + * Get the permissionManager as static + * + * @return the permission Manager. + */ + public static PermissionManager getPermissionManager() { + return permissionManager; + } + /** * Get the Player's Shop limit. * @@ -289,7 +308,7 @@ public class QuickShop extends JavaPlugin { Util.debugLog("No any economy provider selected."); break; } - if(core == null){ + if (core == null) { return false; } if (!core.isValid()) { @@ -358,10 +377,10 @@ public class QuickShop extends JavaPlugin { getLogger().info("Loading up integration modules."); this.integrationHelper = new IntegrationHelper(); this.integrationHelper.callIntegrationsLoad(IntegrateStage.onLoadBegin); - if(getConfig().getBoolean("integration.worldguard.enable")){ + if (getConfig().getBoolean("integration.worldguard.enable")) { Plugin wg = Bukkit.getPluginManager().getPlugin("WorldGuard"); Util.debugLogHeavy("Check WG plugin..."); - if(wg != null){ + if (wg != null) { Util.debugLogHeavy("Loading WG modules."); this.integrationHelper.register(new WorldGuardIntegration(this)); //WG require register flags when onLoad called. } @@ -598,7 +617,7 @@ public class QuickShop extends JavaPlugin { shopVaildWatcher.runTaskTimer(this, 0, 20 * 60); signUpdateWatcher.runTaskTimer(this, 0, 120); shopContainerWatcher.runTaskTimer(this, 0, 5); - displayDupeRemoverWatcher.runTaskTimerAsynchronously(this,0,1); + displayDupeRemoverWatcher.runTaskTimerAsynchronously(this, 0, 1); if (logWatcher != null) { logWatcher.runTaskTimerAsynchronously(this, 10, 10); getLogger().info("Log actions is enabled, actions will log in the qs.log file!"); @@ -615,40 +634,40 @@ public class QuickShop extends JavaPlugin { } registerIntegrations(); this.integrationHelper.callIntegrationsLoad(IntegrateStage.onEnableAfter); - String[] easterEgg =new FunnyEasterEgg().getRandomEasterEgg(); - if(!(easterEgg == null)){ - Arrays.stream(easterEgg).forEach(str->getLogger().info(str)); + String[] easterEgg = new FunnyEasterEgg().getRandomEasterEgg(); + if (!(easterEgg == null)) { + Arrays.stream(easterEgg).forEach(str -> getLogger().info(str)); } } - private void registerIntegrations(){ - if(getConfig().getBoolean("integration.towny.enable")){ + private void registerIntegrations() { + if (getConfig().getBoolean("integration.towny.enable")) { Plugin towny = Bukkit.getPluginManager().getPlugin("Towny"); - if(towny != null && towny.isEnabled()){ + if (towny != null && towny.isEnabled()) { this.integrationHelper.register(new TownyIntegration(this)); } } - if(getConfig().getBoolean("integration.worldguard.enable")){ + if (getConfig().getBoolean("integration.worldguard.enable")) { Plugin worldGuard = Bukkit.getPluginManager().getPlugin("WorldGuard"); - if(worldGuard != null && worldGuard.isEnabled()){ + if (worldGuard != null && worldGuard.isEnabled()) { this.integrationHelper.register(new WorldGuardIntegration(this)); } } - if(getConfig().getBoolean("integration.plotsquared.enable")){ + if (getConfig().getBoolean("integration.plotsquared.enable")) { Plugin plotSquared = Bukkit.getPluginManager().getPlugin("PlotSquared"); - if(plotSquared != null && plotSquared.isEnabled()){ + if (plotSquared != null && plotSquared.isEnabled()) { this.integrationHelper.register(new PlotSquaredIntegration(this)); } } - if(getConfig().getBoolean("integration.residence.enable")){ + if (getConfig().getBoolean("integration.residence.enable")) { Plugin residence = Bukkit.getPluginManager().getPlugin("Residence"); - if(residence != null && residence.isEnabled()){ + if (residence != null && residence.isEnabled()) { this.integrationHelper.register(new ResidenceIntegration(this)); } } - if(getConfig().getBoolean("integration.factions.enable")){ + if (getConfig().getBoolean("integration.factions.enable")) { Plugin factions = Bukkit.getPluginManager().getPlugin("Factions"); - if(factions != null && factions.isEnabled()){ + if (factions != null && factions.isEnabled()) { this.integrationHelper.register(new FactionsUUIDIntegration(this)); } } @@ -671,7 +690,7 @@ public class QuickShop extends JavaPlugin { throw new RuntimeException("Server must be Spigot based, Don't use CraftBukkit!"); } - if (getServer().getName().toLowerCase().contains("catserver") || Util.isClassAvailable("moe.luohuayu.CatServer") ||Util.isClassAvailable("catserver.server.CatServer")) { + if (getServer().getName().toLowerCase().contains("catserver") || Util.isClassAvailable("moe.luohuayu.CatServer") || Util.isClassAvailable("catserver.server.CatServer")) { // Send FATAL ERROR TO CatServer's users. getLogger().severe("FATAL: QSRR can't run on CatServer Community/Personal/Pro/Async"); throw new RuntimeException("QuickShop doen't support CatServer"); @@ -694,7 +713,7 @@ public class QuickShop extends JavaPlugin { IncompatibleChecker incompatibleChecker = new IncompatibleChecker(); getLogger().info("Running QuickShop-Reremake on NMS version " + nmsVersion + " For Minecraft version " + ReflectFactory.getServerVersion()); if (incompatibleChecker.isIncompatible(nmsVersion)) { - throw new RuntimeException("Your Minecraft version is nolonger supported: " + ReflectFactory.getServerVersion()+" ("+nmsVersion+")"); + throw new RuntimeException("Your Minecraft version is nolonger supported: " + ReflectFactory.getServerVersion() + " (" + nmsVersion + ")"); } } @@ -750,6 +769,51 @@ public class QuickShop extends JavaPlugin { return true; } +// public void configVaildate() { +// YamlConfiguration attached = YamlConfiguration.loadConfiguration(new InputStreamReader(Objects.requireNonNull(getResource("config.yml")))); +// Set keysA = new HashSet<>(attached.getKeys(true)); +// Set keysB = new HashSet<>(getConfig().getKeys(true)); +// Set ignoreCheckKeys = new HashSet<>(); +// ignoreCheckKeys.add("server-uuid"); +// final String msgForConfiguration = "Missing options in config.yml, the key [%key%] not exist in config.yml, it may cause plugin errors, please fix it! There is guide for you to fix: \n" + +// ".....\n" + +// "%data%\n" + +// ".....\n" + +// "Tips: Add \"auto-fix-configuration: true\" in config.yml to allow QuickShop automatic fix your configuration!"; +// keysA.stream().filter((key) -> !keysB.contains(key)).filter((key) -> !ignoreCheckKeys.contains(key)).collect(Collectors.toList()).forEach((miss) -> { +// if(!getConfig().getBoolean("auto-fix-configuration",false)){ +// String theMsg = msgForConfiguration; +// theMsg = theMsg.replace("%key%", miss); +// List tiers = new ArrayList<>(Arrays.asList(miss.split("\\."))); +// StringBuilder miss2Yaml = new StringBuilder(); +// int spaces = 2; +// Iterator iterator = tiers.iterator(); +// while (true) { +// String tier = iterator.next(); +// miss2Yaml.append(tier); +// if (iterator.hasNext()) { +// miss2Yaml.append(": "); +// miss2Yaml.append("\n"); +// for (int i = 0; i < spaces; i++) { +// miss2Yaml.append(" "); +// } +// spaces += 2; +// } else { +// miss2Yaml.append(": "); +// miss2Yaml.append(attached.get(miss)); +// break; +// } +// } +// theMsg = theMsg.replace("%data%", miss2Yaml.toString()); +// getLogger().warning(theMsg); +// }else{ +// getConfig().set(miss,attached.get(miss)); +// } +// +// +// }); +// } + private void submitMeritcs() { if (!getConfig().getBoolean("disabled-metrics")) { String serverVer = Bukkit.getVersion(); @@ -1215,9 +1279,9 @@ public class QuickShop extends JavaPlugin { selectedVersion = 72; } if (selectedVersion == 72) { - if(getConfig().getBoolean("use-deciaml-format")){ + if (getConfig().getBoolean("use-deciaml-format")) { getConfig().set("use-decimal-format", getConfig().getBoolean("use-deciaml-format")); - }else{ + } else { getConfig().set("use-decimal-format", false); } getConfig().set("use-deciaml-format", null); @@ -1234,19 +1298,19 @@ public class QuickShop extends JavaPlugin { selectedVersion = 74; } if (selectedVersion == 74) { - String langUtilsLanguage = getConfig().getString("langutils-language"); + String langUtilsLanguage = getConfig().getString("langutils-language"); getConfig().set("langutils-language", null); - if("en_us".equals(langUtilsLanguage)){ + if ("en_us".equals(langUtilsLanguage)) { langUtilsLanguage = "default"; } getConfig().set("game-language", langUtilsLanguage); - getConfig().set("maximum-digits-in-price",-1); + getConfig().set("maximum-digits-in-price", -1); getConfig().set("config-version", 75); selectedVersion = 75; } if (selectedVersion == 75) { getConfig().set("langutils-language", null); - if(getConfig().getString("game-language") == null){ + if (getConfig().getString("game-language") == null) { getConfig().set("game-language", "default"); } getConfig().set("config-version", 76); @@ -1256,27 +1320,27 @@ public class QuickShop extends JavaPlugin { getConfig().set("database.auto-fix-encoding-issue-in-database", false); getConfig().set("send-shop-protection-alert", false); getConfig().set("send-display-item-protection-alert", false); - getConfig().set("shop.use-fast-shop-search-algorithm",false); + getConfig().set("shop.use-fast-shop-search-algorithm", false); getConfig().set("config-version", 77); selectedVersion = 77; } if (selectedVersion == 77) { getConfig().set("integration.towny.enable", false); - getConfig().set("integration.towny.create", new String[] {"SHOPTYPE","MODIFY"}); + getConfig().set("integration.towny.create", new String[]{"SHOPTYPE", "MODIFY"}); getConfig().set("integration.towny.trade", new String[]{}); getConfig().set("integration.worldguard.enable", false); - getConfig().set("integration.worldguard.create", new String[] {"FLAG","CHEST_ACCESS"}); + getConfig().set("integration.worldguard.create", new String[]{"FLAG", "CHEST_ACCESS"}); getConfig().set("integration.worldguard.trade", new String[]{}); getConfig().set("integration.plotsquared.enable", false); getConfig().set("integration.plotsquared.enable", false); getConfig().set("integration.plotsquared.enable", false); getConfig().set("integration.residence.enable", false); - getConfig().set("integration.residence.create", new String[] {"FLAG","interact","use"}); - getConfig().set("integration.residence.trade", new String[] {}); + getConfig().set("integration.residence.create", new String[]{"FLAG", "interact", "use"}); + getConfig().set("integration.residence.trade", new String[]{}); getConfig().set("integration.factions.enable", false); - getConfig().set("integration.factions.create.flag", new String[] {}); - getConfig().set("integration.factions.trade.flag", new String[] {}); + getConfig().set("integration.factions.create.flag", new String[]{}); + getConfig().set("integration.factions.trade.flag", new String[]{}); getConfig().set("integration.factions.create.require.open", false); getConfig().set("integration.factions.create.require.normal", true); getConfig().set("integration.factions.create.require.wilderness", false); @@ -1309,51 +1373,6 @@ public class QuickShop extends JavaPlugin { //configVaildate(); } -// public void configVaildate() { -// YamlConfiguration attached = YamlConfiguration.loadConfiguration(new InputStreamReader(Objects.requireNonNull(getResource("config.yml")))); -// Set keysA = new HashSet<>(attached.getKeys(true)); -// Set keysB = new HashSet<>(getConfig().getKeys(true)); -// Set ignoreCheckKeys = new HashSet<>(); -// ignoreCheckKeys.add("server-uuid"); -// final String msgForConfiguration = "Missing options in config.yml, the key [%key%] not exist in config.yml, it may cause plugin errors, please fix it! There is guide for you to fix: \n" + -// ".....\n" + -// "%data%\n" + -// ".....\n" + -// "Tips: Add \"auto-fix-configuration: true\" in config.yml to allow QuickShop automatic fix your configuration!"; -// keysA.stream().filter((key) -> !keysB.contains(key)).filter((key) -> !ignoreCheckKeys.contains(key)).collect(Collectors.toList()).forEach((miss) -> { -// if(!getConfig().getBoolean("auto-fix-configuration",false)){ -// String theMsg = msgForConfiguration; -// theMsg = theMsg.replace("%key%", miss); -// List tiers = new ArrayList<>(Arrays.asList(miss.split("\\."))); -// StringBuilder miss2Yaml = new StringBuilder(); -// int spaces = 2; -// Iterator iterator = tiers.iterator(); -// while (true) { -// String tier = iterator.next(); -// miss2Yaml.append(tier); -// if (iterator.hasNext()) { -// miss2Yaml.append(": "); -// miss2Yaml.append("\n"); -// for (int i = 0; i < spaces; i++) { -// miss2Yaml.append(" "); -// } -// spaces += 2; -// } else { -// miss2Yaml.append(": "); -// miss2Yaml.append(attached.get(miss)); -// break; -// } -// } -// theMsg = theMsg.replace("%data%", miss2Yaml.toString()); -// getLogger().warning(theMsg); -// }else{ -// getConfig().set(miss,attached.get(miss)); -// } -// -// -// }); -// } - /** * Return the QSRR's fork edition name, you can modify this if you want create yourself fork. * @@ -1363,26 +1382,6 @@ public class QuickShop extends JavaPlugin { return "Reremake"; } - /** - * Returns QS version, this method only exist on QSRR forks If running other - * QSRR forks,, result may not is "Reremake x.x.x" If running QS offical, Will - * throw exception. - * - * @return Plugin Version - */ - public static String getVersion() { - return QuickShop.instance.getDescription().getVersion(); - } - - /** - * Get the permissionManager as static - * - * @return the permission Manager. - */ - public static PermissionManager getPermissionManager() { - return permissionManager; - } - private void replaceLogger() { try { Field logger = ReflectionUtil.getField(JavaPlugin.class, "logger"); diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java index 67c9a33e4..fb734a948 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ArmorStandDisplayItem.java @@ -44,11 +44,6 @@ import java.util.Objects; @ToString public class ArmorStandDisplayItem implements DisplayItem { - private static boolean isTool(Material material) { - String nlc = material.name().toLowerCase(); - return nlc.contains("sword") || nlc.contains("shovel") || nlc.contains("axe"); - } - @Nullable private ArmorStand armorStand; @Nullable @@ -56,13 +51,17 @@ public class ArmorStandDisplayItem implements DisplayItem { private ItemStack originalItemStack; private QuickShop plugin = QuickShop.instance; private Shop shop; - ArmorStandDisplayItem(@NotNull Shop shop) { this.shop = shop; this.originalItemStack = shop.getItem().clone(); this.originalItemStack.setAmount(1); } + private static boolean isTool(Material material) { + String nlc = material.name().toLowerCase(); + return nlc.contains("sword") || nlc.contains("shovel") || nlc.contains("axe"); + } + @Override public boolean checkIsShopEntity(@NotNull Entity entity) { if (!(entity instanceof ArmorStand)) { @@ -151,7 +150,8 @@ public class ArmorStandDisplayItem implements DisplayItem { armorStand.setItemInHand(guardedIstack); try { armorStand.getPersistentDataContainer().set(new NamespacedKey(plugin, "displayMark"), DisplayItemPersistentDataType.INSTANCE, DisplayItem.createShopProtectionFlag(this.originalItemStack, shop)); - }catch (Throwable ignored){} + } catch (Throwable ignored) { + } } @Override @@ -266,13 +266,13 @@ public class ArmorStandDisplayItem implements DisplayItem { @Override public void fixDisplayMoved() { Location location = this.getDisplayLocation(); - if(this.armorStand != null){ - if(location != null){ + if (this.armorStand != null) { + if (location != null) { this.armorStand.teleport(location); - }else{ + } else { fixDisplayMovedOld(); } - }else{ + } else { fixDisplayMovedOld(); } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java index 12b9602b2..0c80d220d 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java @@ -51,16 +51,13 @@ import java.util.logging.Level; */ @EqualsAndHashCode public class ContainerShop implements Shop { + @NotNull + private final ItemStack item; + @NotNull + private final Location location; private DisplayItem displayItem; @EqualsAndHashCode.Exclude private boolean isLoaded = false; - - @NotNull - private final ItemStack item; - - @NotNull - private final Location location; - private ShopModerator moderator; private QuickShop plugin; private double price; @@ -82,7 +79,7 @@ public class ContainerShop implements Shop { /** * Adds a new shop. * - * @param location The location of the chest block + * @param location The location of the chest block * @param price The cost per item * @param item The itemstack with the properties we want. This is .cloned, no * need to worry about references @@ -257,6 +254,19 @@ public class ContainerShop implements Shop { return this.moderator.getOwner(); } + /** + * Changes the owner of this shop to the given player. + * + * @param owner the new owner + */ + @Override + public void setOwner(@NotNull UUID owner) { + this.moderator.setOwner(owner); + Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); + this.setSignText(); + update(); + } + /** * @return Returns a dummy itemstack of the item this shop is selling. */ @@ -459,19 +469,6 @@ public class ContainerShop implements Shop { this.setSignText(); } - /** - * Changes the owner of this shop to the given player. - * - * @param owner the new owner - */ - @Override - public void setOwner(@NotNull UUID owner) { - this.moderator.setOwner(owner); - Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator)); - this.setSignText(); - update(); - } - /** * @return The list of players who can manage the shop. */ @@ -630,6 +627,11 @@ public class ContainerShop implements Shop { } } + @Override + public boolean isUnlimited() { + return this.unlimited; + } + @Override public void setUnlimited(boolean unlimited) { this.unlimited = unlimited; @@ -637,26 +639,11 @@ public class ContainerShop implements Shop { update(); } - @Override - public boolean isUnlimited() { - return this.unlimited; - } - @Override public @NotNull ShopType getShopType() { return this.shopType; } - @Override - public boolean isBuying() { - return this.shopType == ShopType.BUYING; - } - - @Override - public boolean isSelling() { - return this.shopType == ShopType.SELLING; - } - /** * Changes a shop type to Buying or Selling. Also updates the signs nearby. * @@ -669,6 +656,16 @@ public class ContainerShop implements Shop { update(); } + @Override + public boolean isBuying() { + return this.shopType == ShopType.BUYING; + } + + @Override + public boolean isSelling() { + return this.shopType == ShopType.SELLING; + } + /** * Updates signs attached to the shop */ @@ -850,7 +847,7 @@ public class ContainerShop implements Shop { * Check the container still there and we can keep use it. */ public void checkContainer() { - if(!this.isLoaded){ + if (!this.isLoaded) { return; } if (!Util.canBeShop(this.getLocation().getBlock())) { diff --git a/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java index 84c6339e3..22dff7e50 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/DisplayItem.java @@ -41,6 +41,7 @@ import java.util.Objects; */ public interface DisplayItem { Gson gson = new GsonBuilder().create(); + /** * Check the itemStack is contains protect flag. * @@ -57,14 +58,14 @@ public interface DisplayItem { return false; } ItemMeta iMeta = itemStack.getItemMeta(); - if(iMeta == null){ + if (iMeta == null) { return false; } if (!iMeta.hasLore()) { return false; } List lores = iMeta.getLore(); - if(lores != null){ + if (lores != null) { String defaultMark = ShopProtectionFlag.getDefaultMark(); for (String lore : lores) { try { @@ -183,6 +184,15 @@ public interface DisplayItem { return new ShopProtectionFlag(shop.getLocation().toString(), Util.serialize(itemStack)); } + /** + * Get plugin now is using which one DisplayType + * + * @return Using displayType. + */ + static DisplayType getNowUsing() { + return DisplayType.fromID(QuickShop.instance.getConfig().getInt("shop.display-type")); + } + /** * Check the display is or not moved. * @@ -260,15 +270,6 @@ public interface DisplayItem { */ Location getDisplayLocation(); - /** - * Get plugin now is using which one DisplayType - * - * @return Using displayType. - */ - static DisplayType getNowUsing() { - return DisplayType.fromID(QuickShop.instance.getConfig().getInt("shop.display-type")); - } - /** * Check the display is or not already spawned * diff --git a/src/main/java/org/maxgamer/quickshop/Shop/DisplayItemPersistentDataType.java b/src/main/java/org/maxgamer/quickshop/Shop/DisplayItemPersistentDataType.java index af7a89c86..b4a641e43 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/DisplayItemPersistentDataType.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/DisplayItemPersistentDataType.java @@ -28,9 +28,8 @@ import org.jetbrains.annotations.NotNull; import org.maxgamer.quickshop.Util.Util; public class DisplayItemPersistentDataType implements PersistentDataType { - private static Gson gson = new Gson(); - static final DisplayItemPersistentDataType INSTANCE = new DisplayItemPersistentDataType(); + private static Gson gson = new Gson(); @Override public @NotNull Class getPrimitiveType() { @@ -47,7 +46,7 @@ public class DisplayItemPersistentDataType implements PersistentDataType lores = stack.getItemMeta().getLore(); - for (String string : lores) { - if ("QuickShop GUI preview item".equals(string)) { - return true; - } - } - return false; - } - @Nullable private Inventory inventory; private ItemStack itemStack; private Player player; - /** * Create a preview item GUI for a player. * @@ -90,6 +73,22 @@ public class InventoryPreview implements Listener { } } + 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 ("QuickShop GUI preview item".equals(string)) { + return true; + } + } + return false; + } + public void close() { if (inventory == null) { return; diff --git a/src/main/java/org/maxgamer/quickshop/Shop/MatcherWorkMode.java b/src/main/java/org/maxgamer/quickshop/Shop/MatcherWorkMode.java index 63a7c0a21..652243c7c 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/MatcherWorkMode.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/MatcherWorkMode.java @@ -24,6 +24,12 @@ import org.jetbrains.annotations.NotNull; public enum MatcherWorkMode { QSMATCHER(0), BUKKITMATCHER(1), JAVAMATCHER(2); + private int id; + + MatcherWorkMode(int id) { + this.id = id; + } + public static @NotNull MatcherWorkMode fromID(int id) { for (MatcherWorkMode workMode : MatcherWorkMode.values()) { if (workMode.id == id) { @@ -37,12 +43,6 @@ public enum MatcherWorkMode { return workMode.id; } - MatcherWorkMode(int id) { - this.id = id; - } - - private int id; - public int toID() { return id; } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java b/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java index ad44382b5..d92e92d85 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/RealDisplayItem.java @@ -93,13 +93,13 @@ public class RealDisplayItem implements DisplayItem { @Override public void fixDisplayMoved() { Location location = this.getDisplayLocation(); - if(this.item != null){ - if(location != null){ + if (this.item != null) { + if (location != null) { this.item.teleport(location); - }else{ + } else { fixDisplayMovedOld(); } - }else{ + } else { fixDisplayMovedOld(); } } @@ -113,7 +113,7 @@ public class RealDisplayItem implements DisplayItem { if (eItem.getUniqueId().equals(Objects.requireNonNull(this.item).getUniqueId())) { Util.debugLog("Fixing moved Item displayItem " + eItem.getUniqueId() + " at " + eItem .getLocation()); - plugin.getBukkitAPIWrapper().teleportEntity(eItem,Objects.requireNonNull(getDisplayLocation()), PlayerTeleportEvent.TeleportCause.UNKNOWN); + plugin.getBukkitAPIWrapper().teleportEntity(eItem, Objects.requireNonNull(getDisplayLocation()), PlayerTeleportEvent.TeleportCause.UNKNOWN); return; } } @@ -136,6 +136,7 @@ public class RealDisplayItem implements DisplayItem { ShopDisplayItemDespawnEvent shopDisplayItemDepawnEvent = new ShopDisplayItemDespawnEvent(shop, originalItemStack, DisplayType.REALITEM); Bukkit.getPluginManager().callEvent(shopDisplayItemDepawnEvent); } + @Override public boolean removeDupe() { if (this.item == null) { diff --git a/src/main/java/org/maxgamer/quickshop/Shop/Shop.java b/src/main/java/org/maxgamer/quickshop/Shop/Shop.java index 8b8829537..c7d38a94d 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/Shop.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/Shop.java @@ -158,13 +158,6 @@ public interface Shop { */ 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. * @@ -256,6 +249,13 @@ public interface Shop { */ @NotNull ShopType getShopType(); + /** + * Set new shop type for this shop + * + * @param paramShopType New shop type + */ + void setShopType(ShopType paramShopType); + /** * Get shop signs, may have multi signs * diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java index 46eaa2d40..e3d88eb2b 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopLoader.java @@ -53,8 +53,10 @@ public class ShopLoader { private QuickShop plugin; private int totalLoaded = 0; /* This may contains broken shop, must use null check before load it. */ - @Getter private List shopsInDatabase = new ArrayList<>(); - @Getter private List originShopsInDatabase = new ArrayList<>(); + @Getter + private List shopsInDatabase = new ArrayList<>(); + @Getter + private List originShopsInDatabase = new ArrayList<>(); /** * The shop load allow plugin load shops fast and simply. @@ -145,9 +147,9 @@ public class ShopLoader { Util.debugLog("Target block can't be a shop, removing it from the database..."); //shop.delete(); plugin.getShopManager().removeShop(shop); //Remove from Mem - if(!backupedDatabaseInDeleteProcess){ //Only backup db one time. + if (!backupedDatabaseInDeleteProcess) { //Only backup db one time. backupedDatabaseInDeleteProcess = Util.backupDatabase(); - }else{ + } else { plugin.getDatabaseHelper().removeShop(shop.getLocation().getBlockX(), shop .getLocation().getBlockY(), shop.getLocation().getBlockZ(), Objects.requireNonNull(shop.getLocation().getWorld()) .getName()); @@ -215,7 +217,7 @@ public class ShopLoader { Util.debugLog("Shop Owner is null"); return true; } - if(Bukkit.getOfflinePlayer(shop.getOwner()).getName() == null){ + if (Bukkit.getOfflinePlayer(shop.getOwner()).getName() == null) { Util.debugLog("Shop owner not exist on this server, did you reset the playerdata?"); } return false; @@ -228,7 +230,7 @@ public class ShopLoader { Util.debugLog("Loaded shop used time " + singleShopLoadTime + "ms"); } - @Data + @Data public class ShopDatabaseInfo { private ItemStack item; private Location location; @@ -272,13 +274,13 @@ public class ShopLoader { private @Nullable ShopModerator deserializeModerator(@NotNull String moderatorJson) { ShopModerator shopModerator; if (Util.isUUID(moderatorJson)) { - Util.debugLog("Updating old shop data... for "+moderatorJson); + Util.debugLog("Updating old shop data... for " + moderatorJson); shopModerator = new ShopModerator(UUID.fromString(moderatorJson)); //New one } else { try { shopModerator = ShopModerator.deserialize(moderatorJson); } catch (JsonSyntaxException ex) { - Util.debugLog("Updating old shop data... for "+moderatorJson); + Util.debugLog("Updating old shop data... for " + moderatorJson); moderatorJson = Bukkit.getOfflinePlayer(moderatorJson).getUniqueId().toString(); shopModerator = new ShopModerator(UUID.fromString(moderatorJson)); //New one } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java index e6d72d81f..c25e7f920 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java @@ -53,19 +53,16 @@ import java.util.stream.Collectors; @SuppressWarnings("WeakerAccess") public class ShopManager { - private HashMap actions = new HashMap<>(); - - private QuickShop plugin; - private final HashMap>> shops = new HashMap<>(); - + private HashMap actions = new HashMap<>(); + private QuickShop plugin; private Set loadedShops = new CopyOnWriteArraySet<>(); private boolean useFastShopSearchAlgorithm = false; public ShopManager(@NotNull QuickShop plugin) { this.plugin = plugin; - this.useFastShopSearchAlgorithm = plugin.getConfig().getBoolean("shop.use-fast-shop-search-algorithm",false); + this.useFastShopSearchAlgorithm = plugin.getConfig().getBoolean("shop.use-fast-shop-search-algorithm", false); } @SuppressWarnings("deprecation") @@ -109,7 +106,7 @@ public class ShopManager { // Money handling double tax = plugin.getConfig().getDouble("tax"); double total = amount * shop.getPrice(); - if (QuickShop.getPermissionManager().hasPermission(p,"quickshop.tax")) { + if (QuickShop.getPermissionManager().hasPermission(p, "quickshop.tax")) { tax = 0; Util.debugLog("Disable the Tax for player " + p.getName() + " cause they have permission quickshop.tax"); } @@ -239,12 +236,12 @@ public class ShopManager { } } else { price = Double.parseDouble(message); - String strFormat = new DecimalFormat("#.#########").format(Math.abs(price)).replace(",","."); + String strFormat = new DecimalFormat("#.#########").format(Math.abs(price)).replace(",", "."); String[] processedDouble = strFormat.split("."); - if(processedDouble.length > 1){ - int maximumDigitsLimit = plugin.getConfig().getInt("maximum-digits-in-price",-1); - if(processedDouble[1].length() > maximumDigitsLimit && maximumDigitsLimit!=-1){ - p.sendMessage(MsgUtil.getMessage("digits-reach-the-limit",p,String.valueOf(maximumDigitsLimit))); + if (processedDouble.length > 1) { + int maximumDigitsLimit = plugin.getConfig().getInt("maximum-digits-in-price", -1); + if (processedDouble[1].length() > maximumDigitsLimit && maximumDigitsLimit != -1) { + p.sendMessage(MsgUtil.getMessage("digits-reach-the-limit", p, String.valueOf(maximumDigitsLimit))); return; } } @@ -297,7 +294,7 @@ public class ShopManager { // This must be called after the event has been called. // Else, if the event is cancelled, they won't get their // money back. - if(QuickShop.getPermissionManager().hasPermission(p,"quickshop.bypasscreatefee")){ + if (QuickShop.getPermissionManager().hasPermission(p, "quickshop.bypasscreatefee")) { createCost = 0; } if (createCost > 0) { @@ -323,7 +320,7 @@ public class ShopManager { shop.onUnload(); return; } - if(!plugin.getIntegrationHelper().callIntegrationsCanCreate(p,info.getLocation())){ + if (!plugin.getIntegrationHelper().callIntegrationsCanCreate(p, info.getLocation())) { shop.onUnload(); Util.debugLog("Cancelled by integrations"); return; @@ -395,7 +392,7 @@ public class ShopManager { // Money handling double tax = plugin.getConfig().getDouble("tax"); double total = amount * shop.getPrice(); - if (QuickShop.getPermissionManager().hasPermission(p,"quickshop.tax")) { + if (QuickShop.getPermissionManager().hasPermission(p, "quickshop.tax")) { tax = 0; Util.debugLog("Disable the Tax for player " + p.getName() + " cause they have permission quickshop.tax"); } @@ -455,7 +452,7 @@ public class ShopManager { p.sendMessage("Error: Economy system not loaded, type /qs main command to get details."); return; } - if(!plugin.getIntegrationHelper().callIntegrationsCanTrade(p,info.getLocation())){ + if (!plugin.getIntegrationHelper().callIntegrationsCanTrade(p, info.getLocation())) { Util.debugLog("Cancel by integrations."); return; } @@ -483,7 +480,7 @@ public class ShopManager { // Check if shop owner has enough money double ownerBalance = eco.getBalance(shop.getOwner()); int ownerCanAfford; - + if (shop.getPrice() != 0) { ownerCanAfford = (int) (ownerBalance / shop.getPrice()); } else { @@ -799,12 +796,13 @@ public class ShopManager { return null; } - if(this.useFastShopSearchAlgorithm){ + if (this.useFastShopSearchAlgorithm) { return getShopIncludeAttached_Fast(loc); - }else{ + } else { return getShopIncludeAttached_Classic(loc); } } + public @Nullable Shop getShopIncludeAttached_Classic(@Nullable Location loc) { if (loc == null) { Util.debugLog("Location is null."); @@ -861,7 +859,8 @@ public class ShopManager { return null; } - private @Nullable Shop getShopIncludeAttached_Fast(@Nullable Location loc){ + + private @Nullable Shop getShopIncludeAttached_Fast(@Nullable Location loc) { if (loc == null) { Util.debugLog("Location is null."); return null; @@ -869,13 +868,13 @@ public class ShopManager { Util.debugLog("Use fast shop search algorithm to searching the shops..."); @Nullable Shop shop; shop = getShop(loc); - if(shop != null){ + if (shop != null) { return shop; } @Nullable Block attachedBlock = Util.getAttached(loc.getBlock()); - if(attachedBlock != null){ + if (attachedBlock != null) { return getShop(attachedBlock.getLocation()); - }else{ + } else { return null; } } @@ -1025,6 +1024,35 @@ public class ShopManager { return this.shops; } + /** + * Get all loaded shops. + * + * @return All loaded shops. + */ + public @Nullable Set getLoadedShops() { + return this.loadedShops; + } + + /** + * Get a players all shops. + * + * @param playerUUID The player's uuid. + * @return The list have this player's all shops. + */ + public @NotNull List getPlayerAllShops(@NotNull UUID playerUUID) { + return getAllShops().stream().filter(shop -> shop.getOwner().equals(playerUUID)).collect(Collectors.toList()); + } + + /** + * Get the all shops in the world. + * + * @param world The world you want get the shops. + * @return The list have this world all shops + */ + public @NotNull List getShopsInWorld(@NotNull World world) { + return getAllShops().stream().filter(shop -> Objects.equals(shop.getLocation().getWorld(), world)).collect(Collectors.toList()); + } + public class ShopIterator implements Iterator { private Iterator> chunks; private Iterator shops; @@ -1080,33 +1108,4 @@ public class ShopManager { return shops.next(); } } - - /** - * Get all loaded shops. - * - * @return All loaded shops. - */ - public @Nullable Set getLoadedShops() { - return this.loadedShops; - } - - /** - * Get a players all shops. - * - * @param playerUUID The player's uuid. - * @return The list have this player's all shops. - */ - public @NotNull List getPlayerAllShops(@NotNull UUID playerUUID) { - return getAllShops().stream().filter(shop -> shop.getOwner().equals(playerUUID)).collect(Collectors.toList()); - } - - /** - * Get the all shops in the world. - * - * @param world The world you want get the shops. - * @return The list have this world all shops - */ - public @NotNull List getShopsInWorld(@NotNull World world) { - return getAllShops().stream().filter(shop -> Objects.equals(shop.getLocation().getWorld(), world)).collect(Collectors.toList()); - } } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java index 56ca89780..8849fc48e 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopModerator.java @@ -33,20 +33,8 @@ import java.util.UUID; */ @EqualsAndHashCode public class ShopModerator { - public static ShopModerator deserialize(@NotNull String serilized) throws JsonSyntaxException { - //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 - } - @NonNull private UUID owner; - @NonNull private ArrayList staffs; @@ -76,6 +64,17 @@ public class ShopModerator { this.staffs = staffs; } + public static ShopModerator deserialize(@NotNull String serilized) throws JsonSyntaxException { + //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 + } + /** * Add moderators staff to staff list * diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java index 66f13be47..fa7c877d3 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopType.java @@ -25,6 +25,12 @@ public enum ShopType { //SELLING = SELLMODE BUYING = BUY MODE SELLING(0), BUYING(1); + private int id; + + ShopType(int id) { + this.id = id; + } + public static @NotNull ShopType fromID(int id) { for (ShopType type : ShopType.values()) { if (type.id == id) { @@ -38,12 +44,6 @@ 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 1b72e11d7..d35c1bb7b 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ChatSheetPrinter.java @@ -67,7 +67,7 @@ public class ChatSheetPrinter { public void printLine(@NotNull String text) { String[] texts = text.split("\n"); - Arrays.asList(texts).forEach((str)->{ + Arrays.asList(texts).forEach((str) -> { p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_begin", p) + " " + str); }); diff --git a/src/main/java/org/maxgamer/quickshop/Util/Copied.java b/src/main/java/org/maxgamer/quickshop/Util/Copied.java index 35c567cbb..0a7e49261 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Copied.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Copied.java @@ -38,11 +38,11 @@ public final class Copied implements Consumer { @Override public void accept(@NotNull InputStream inputStream) { - try(final OutputStream out = new FileOutputStream(file)) { + try (final OutputStream out = new FileOutputStream(file)) { final byte[] buf = new byte[1024]; int len; - while((len = inputStream.read(buf)) > 0) { + while ((len = inputStream.read(buf)) > 0) { out.write(buf, 0, len); } diff --git a/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java b/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java index 5507c16a8..0a62a3eac 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java +++ b/src/main/java/org/maxgamer/quickshop/Util/FunnyEasterEgg.java @@ -42,10 +42,12 @@ public class FunnyEasterEgg { if (chineseSpringDay()) { return this.getChineseNewYear().split("\n"); } - }catch (Exception ignored){} + } catch (Exception ignored) { + } return null; } - private String getChineseNewYear(){ + + private String getChineseNewYear() { return " 88 88 88 88 88 HHHHHHH\n" + "888888888888888888888888888888 88888888888888 88888888888 AAAAAAA\n" + " 88 88 88 88 88 88 PPPPPPP\n" + @@ -76,7 +78,8 @@ public class FunnyEasterEgg { " 88 88 88 88 88 88 88 88 888888888888 OOOOOOO\n" + " 88 88 88 88 88 88 88 88 88 88 UUUUUUU\n" + " 88 88 88 88 88 88 888888888888 !!!!!!!\n"; - }; + } + private String getXMas() { return " * * () * *\n" + "* * /\\ *\n" + @@ -98,10 +101,7 @@ public class FunnyEasterEgg { if (chineseCalender.getMonth() == Calendar.DECEMBER && chineseCalender.getDay() == 31) { return true; } - if (chineseCalender.getMonth() == Calendar.JANUARY && chineseCalender.getDay() == 1) { - return true; - } - return false; + return chineseCalender.getMonth() == Calendar.JANUARY && chineseCalender.getDay() == 1; } private boolean easterDay() { @@ -222,20 +222,10 @@ public class FunnyEasterEgg { } class LunarCalendar { - private int year;// 农历年 - private int month;// 农历月 - private int day;// 农历日 - private boolean leap;// 农历闰年 - // 上面4个值在构造方法中根据传入日期计算所得 - /** * 中文月名称 */ - final static String chineseNumber[] = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"}; - /** - * 中文日期格式 - */ - static SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy年MM月dd日"); + final static String[] chineseNumber = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"}; /** * 农历数据, 1901 ~ 2100 年之间正确 */ @@ -252,60 +242,15 @@ class LunarCalendar { 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0}; - - // ====== 传回农历 y年的总天数 - final private static int yearDays(int y) { - int i, sum = 348; - for (i = 0x8000; i > 0x8; i >>= 1) { - if ((lunarInfo[y - 1900] & i) != 0) - sum += 1; - } - return (sum + leapDays(y)); - } - - // ====== 传回农历 y年闰月的天数 - final private static int leapDays(int y) { - if (leapMonth(y) != 0) { - if ((lunarInfo[y - 1900] & 0x10000) != 0) - return 30; - else - return 29; - } else - return 0; - } - - // ====== 传回农历 y年闰哪个月 1-12 , 没闰传回 0 - final private static int leapMonth(int y) { - return (int) (lunarInfo[y - 1900] & 0xf); - } - - // ====== 传回农历 y年m月的总天数 - final private static int monthDays(int y, int m) { - if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0) - return 29; - else - return 30; - } - - // ====== 传回农历 y年的生肖 - final public String animalsYear() { - final String[] Animals = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"}; - return Animals[(year - 4) % 12]; - } - - // ====== 传入 月日的offset 传回干支, 0=甲子 - final private static String cyclicalm(int num) { - final String[] Gan = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}; - final String[] Zhi = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}; - return (Gan[num % 10] + Zhi[num % 12]); - } - - // ====== 传入 offset 传回干支, 0=甲子 - final public String cyclical() { - int num = year - 1900 + 36; - return (cyclicalm(num)); - } - + /** + * 中文日期格式 + */ + static SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy年MM月dd日"); + private int year;// 农历年 + // 上面4个值在构造方法中根据传入日期计算所得 + private int month;// 农历月 + private int day;// 农历日 + private boolean leap;// 农历闰年 /** * 构造一个表示当前日期的农历日历 @@ -321,12 +266,6 @@ class LunarCalendar { this(date2calendar(date)); } - private static Calendar date2calendar(Date date) { - Calendar tmpCale = Calendar.getInstance(); - tmpCale.setTime(date); - return tmpCale; - } - /** * 使用指定日历日期构造一个农历日历 * @@ -407,6 +346,76 @@ class LunarCalendar { day = offset + 1; } + // ====== 传回农历 y年的总天数 + final private static int yearDays(int y) { + int i, sum = 348; + for (i = 0x8000; i > 0x8; i >>= 1) { + if ((lunarInfo[y - 1900] & i) != 0) + sum += 1; + } + return (sum + leapDays(y)); + } + + // ====== 传回农历 y年闰月的天数 + final private static int leapDays(int y) { + if (leapMonth(y) != 0) { + if ((lunarInfo[y - 1900] & 0x10000) != 0) + return 30; + else + return 29; + } else + return 0; + } + + // ====== 传回农历 y年闰哪个月 1-12 , 没闰传回 0 + final private static int leapMonth(int y) { + return (int) (lunarInfo[y - 1900] & 0xf); + } + + // ====== 传回农历 y年m月的总天数 + final private static int monthDays(int y, int m) { + if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0) + return 29; + else + return 30; + } + + // ====== 传入 月日的offset 传回干支, 0=甲子 + final private static String cyclicalm(int num) { + final String[] Gan = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}; + final String[] Zhi = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}; + return (Gan[num % 10] + Zhi[num % 12]); + } + + private static Calendar date2calendar(Date date) { + Calendar tmpCale = Calendar.getInstance(); + tmpCale.setTime(date); + return tmpCale; + } + + public static String getChinaDayString(int day) { + String[] chineseTen = {"初", "十", "廿", "卅"}; + int n = day % 10 == 0 ? 9 : day % 10 - 1; + if (day > 30) + return ""; + if (day == 10) + return "初十"; + else + return chineseTen[day / 10] + chineseNumber[n]; + } + + // ====== 传回农历 y年的生肖 + final public String animalsYear() { + final String[] Animals = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"}; + return Animals[(year - 4) % 12]; + } + + // ====== 传入 offset 传回干支, 0=甲子 + final public String cyclical() { + int num = year - 1900 + 36; + return (cyclicalm(num)); + } + /** * 获得表示农历年月日的日期对象 * @@ -420,17 +429,6 @@ class LunarCalendar { return calendar.getTime(); } - public static String getChinaDayString(int day) { - String chineseTen[] = {"初", "十", "廿", "卅"}; - int n = day % 10 == 0 ? 9 : day % 10 - 1; - if (day > 30) - return ""; - if (day == 10) - return "初十"; - else - return chineseTen[day / 10] + chineseNumber[n]; - } - public String toString() { return year + "年" + (leap ? "闰" : "") + chineseNumber[month - 1] + "月" + getChinaDayString(day); } diff --git a/src/main/java/org/maxgamer/quickshop/Util/GameLanguage.java b/src/main/java/org/maxgamer/quickshop/Util/GameLanguage.java index 84dc9d708..dea5a5b47 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/GameLanguage.java +++ b/src/main/java/org/maxgamer/quickshop/Util/GameLanguage.java @@ -43,6 +43,7 @@ import java.util.Locale; public class GameLanguage extends Thread { private @Nullable JsonObject lang = null; private GameLanguageLoadThread loadThread; + @SneakyThrows public GameLanguage(@NotNull String languageCode) { loadThread = new GameLanguageLoadThread(); @@ -50,15 +51,15 @@ public class GameLanguage extends Thread { loadThread.setMainThreadWaiting(true); //Told thread we're waiting him loadThread.start(); int count = 0; - while (count < 20){ - if(loadThread.isAlive()){ - count ++; + while (count < 20) { + if (loadThread.isAlive()) { + count++; Thread.sleep(1000); - if(count >= 20){ + if (count >= 20) { Util.debugLog("No longer waiting file downloading because it now timed out, now downloading in background."); QuickShop.instance.getLogger().info("No longer waiting file downloading because it now timed out, now downloading in background, please reset itemi18n.yml, potioni18n.yml and enchi18n.yml after download completed."); } - }else{ + } else { break; } } @@ -66,7 +67,7 @@ public class GameLanguage extends Thread { loadThread.setMainThreadWaiting(false); //Told thread it now move to background, thread should told user reset files. } - public void loadLimited(@NotNull String languageCode){ + public void loadLimited(@NotNull String languageCode) { try { File cacheFile = new File(Util.getCacheFolder(), "lang.cache"); //Load cache file if (!cacheFile.exists()) { @@ -94,7 +95,7 @@ public class GameLanguage extends Thread { cachingServerVersion = serverVersion; needUpdateCache = true; } - if(cachingLanguageHash == null || cachingLanguageHash.isEmpty()){ + if (cachingLanguageHash == null || cachingLanguageHash.isEmpty()) { needUpdateCache = true; } if (needUpdateCache) { @@ -108,15 +109,15 @@ public class GameLanguage extends Thread { String langJson = mojangAPI.downloadTextFileFromMojang(hash); if (langJson != null) { new Copied(new File(Util.getCacheFolder(), hash)).accept(new ByteArrayInputStream(langJson.getBytes(StandardCharsets.UTF_8))); - }else{ + } else { Util.debugLog("Cannot download file."); QuickShop.instance.getLogger().warning("Cannot download require files, some items/blocks/potions/enchs language will use default English name."); } - }else{ - Util.debugLog("Cannot get file hash for language "+ languageCode1); + } else { + Util.debugLog("Cannot get file hash for language " + languageCode1); QuickShop.instance.getLogger().warning("Cannot download require files, some items/blocks/potions/enchs language will use default English name."); } - }else{ + } else { Util.debugLog("Cannot get version json."); QuickShop.instance.getLogger().warning("Cannot download require files, some items/blocks/potions/enchs language will use default English name."); } @@ -128,12 +129,12 @@ public class GameLanguage extends Thread { String json = null; if (cachingLanguageHash != null) { json = Util.readToString(new File(Util.getCacheFolder(), cachingLanguageHash)); - }else{ + } else { Util.debugLog("Caching LanguageHash is null"); } if (json != null && !json.isEmpty()) { lang = new JsonParser().parse(json).getAsJsonObject(); - }else{ + } else { Util.debugLog("json is null"); } } catch (Exception e) { @@ -144,6 +145,7 @@ public class GameLanguage extends Thread { /** * Get item and block translations, if not found, it will both call getBlock() + * * @param material The material * @return The translations for material */ @@ -155,18 +157,20 @@ public class GameLanguage extends Thread { } String jsonName; try { - JsonElement element = lang.get("item.minecraft."+material.name().toLowerCase()); - if(element == null){ + JsonElement element = lang.get("item.minecraft." + material.name().toLowerCase()); + if (element == null) { return getBlock(material); - }else{ + } else { return element.getAsString(); } } catch (NullPointerException npe) { return name; } } + /** * Get block only translations, if not found, it WON'T call getItem() + * * @param material The material * @return The translations for material */ @@ -177,13 +181,15 @@ public class GameLanguage extends Thread { return name; } try { - return lang.get("block.minecraft."+material.name().toLowerCase()).getAsString(); + return lang.get("block.minecraft." + material.name().toLowerCase()).getAsString(); } catch (NullPointerException e) { return name; } } + /** * Get entity translations. + * * @param entity The entity name * @return The translations for entity */ @@ -194,13 +200,15 @@ public class GameLanguage extends Thread { return name; } try { - return lang.get("entity.minecraft."+entity.getType().name().toLowerCase()).getAsString(); + return lang.get("entity.minecraft." + entity.getType().name().toLowerCase()).getAsString(); } catch (NullPointerException e) { return name; } } + /** * Get potion/effect translations. + * * @param effect The potion/effect name * @return The translations for effect/potions */ @@ -211,13 +219,15 @@ public class GameLanguage extends Thread { return name; } try { - return lang.get("effect.minecraft."+effect.getName().toLowerCase()).getAsString(); + return lang.get("effect.minecraft." + effect.getName().toLowerCase()).getAsString(); } catch (NullPointerException e) { return name; } } + /** * Get enchantment translations. + * * @param enchantmentName The enchantment name * @return The translations for enchantment */ @@ -228,13 +238,15 @@ public class GameLanguage extends Thread { return name; } try { - return lang.get("enchantment.minecraft."+enchantmentName.toLowerCase()).getAsString(); + return lang.get("enchantment.minecraft." + enchantmentName.toLowerCase()).getAsString(); } catch (NullPointerException e) { return name; } } + /** * Get custom translations. + * * @param node The target node path * @return The translations for you custom node path */ @@ -243,21 +255,22 @@ public class GameLanguage extends Thread { if (lang == null) { return null; } - try{ + try { return lang.get(node).getAsString(); } catch (NullPointerException e) { return null; } } } + @Getter @Setter -class GameLanguageLoadThread extends Thread{ +class GameLanguageLoadThread extends Thread { private JsonObject lang; private String languageCode; private boolean mainThreadWaiting; - public void run(@NotNull String languageCode){ + public void run(@NotNull String languageCode) { try { File cacheFile = new File(Util.getCacheFolder(), "lang.cache"); //Load cache file if (!cacheFile.exists()) { @@ -285,7 +298,7 @@ class GameLanguageLoadThread extends Thread{ cachingServerVersion = serverVersion; needUpdateCache = true; } - if(cachingLanguageHash == null || cachingLanguageHash.isEmpty()){ + if (cachingLanguageHash == null || cachingLanguageHash.isEmpty()) { needUpdateCache = true; } if (needUpdateCache) { @@ -299,15 +312,15 @@ class GameLanguageLoadThread extends Thread{ String langJson = mojangAPI.downloadTextFileFromMojang(hash); if (langJson != null) { new Copied(new File(Util.getCacheFolder(), hash)).accept(new ByteArrayInputStream(langJson.getBytes(StandardCharsets.UTF_8))); - }else{ + } else { Util.debugLog("Cannot download file."); QuickShop.instance.getLogger().warning("Cannot download require files, some items/blocks/potions/enchs language will use default English name."); } - }else{ - Util.debugLog("Cannot get file hash for language "+ languageCode1); + } else { + Util.debugLog("Cannot get file hash for language " + languageCode1); QuickShop.instance.getLogger().warning("Cannot download require files, some items/blocks/potions/enchs language will use default English name."); } - }else{ + } else { Util.debugLog("Cannot get version json."); QuickShop.instance.getLogger().warning("Cannot download require files, some items/blocks/potions/enchs language will use default English name."); } @@ -319,19 +332,19 @@ class GameLanguageLoadThread extends Thread{ String json = null; if (cachingLanguageHash != null) { json = Util.readToString(new File(Util.getCacheFolder(), cachingLanguageHash)); - }else{ + } else { Util.debugLog("Caching LanguageHash is null"); } if (json != null && !json.isEmpty()) { lang = new JsonParser().parse(json).getAsJsonObject(); - }else{ + } else { Util.debugLog("json is null"); } } catch (Exception e) { QuickShop.instance.getSentryErrorReporter().ignoreThrow(); e.printStackTrace(); } - if(!this.mainThreadWaiting){ + if (!this.mainThreadWaiting) { QuickShop.instance.getLogger().info("Download completed, please execute /qs reset lang to generate localized language files."); } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Github/GithubAPI.java b/src/main/java/org/maxgamer/quickshop/Util/Github/GithubAPI.java index 2adffd6c5..9e2b7a090 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Github/GithubAPI.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Github/GithubAPI.java @@ -28,12 +28,13 @@ import java.net.URL; public class GithubAPI { private Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + @Nullable - public ReleaseJsonContainer.AssetsBean getLatestRelease() throws Exception{ + public ReleaseJsonContainer.AssetsBean getLatestRelease() throws Exception { String json = HttpRequest.get(new URL("https://api.github.com/repos/Ghost-chu/QuickShop-Reremake/releases/latest")).execute().returnContent().asString("UTF-8"); - ReleaseJsonContainer result = gson.fromJson(json,ReleaseJsonContainer.class); - for (ReleaseJsonContainer.AssetsBean asset: - result.getAssets()) { + ReleaseJsonContainer result = gson.fromJson(json, ReleaseJsonContainer.class); + for (ReleaseJsonContainer.AssetsBean asset : + result.getAssets()) { if (asset.getName().contains("original-")) { continue; } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Github/ReleaseJsonContainer.java b/src/main/java/org/maxgamer/quickshop/Util/Github/ReleaseJsonContainer.java index 74dfc57db..1abac4e8b 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Github/ReleaseJsonContainer.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Github/ReleaseJsonContainer.java @@ -20,6 +20,7 @@ package org.maxgamer.quickshop.Util.Github; import java.util.List; + public class ReleaseJsonContainer { /** * url : https://api.github.com/repos/octocat/Hello-World/releases/1 @@ -53,6 +54,7 @@ public class ReleaseJsonContainer { public void setId(int id) { this.id = id; } + public String getName() { return name; } diff --git a/src/main/java/org/maxgamer/quickshop/Util/IntegrationHelper.java b/src/main/java/org/maxgamer/quickshop/Util/IntegrationHelper.java index 44be44888..8cf329c42 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/IntegrationHelper.java +++ b/src/main/java/org/maxgamer/quickshop/Util/IntegrationHelper.java @@ -29,6 +29,7 @@ import org.maxgamer.quickshop.PluginsIntegration.IntegrationStage; import java.util.HashSet; import java.util.Set; + @Getter public class IntegrationHelper { private Set integrations = new HashSet<>(); @@ -37,7 +38,7 @@ public class IntegrationHelper { if (!isIntegrationClass(clazz)) { throw new InvaildIntegratedPluginClass(); } - Util.debugLogHeavy("Registering "+clazz.getName()); + Util.debugLogHeavy("Registering " + clazz.getName()); integrations.add(clazz); } @@ -46,17 +47,17 @@ public class IntegrationHelper { if (!isIntegrationClass(clazz)) { throw new InvaildIntegratedPluginClass(); } - Util.debugLogHeavy("Unregistering "+clazz.getName()); + Util.debugLogHeavy("Unregistering " + clazz.getName()); integrations.remove(clazz); } public void callIntegrationsLoad(@NotNull IntegrateStage stage) { integrations.forEach(integratedPlugin -> { if (integratedPlugin.getClass().getDeclaredAnnotation(IntegrationStage.class).loadStage() == stage) { - Util.debugLogHeavy("Calling for load "+integratedPlugin.getName()); + Util.debugLogHeavy("Calling for load " + integratedPlugin.getName()); integratedPlugin.load(); - }else{ - Util.debugLogHeavy("Ignored calling because "+integratedPlugin.getName()+" stage is "+integratedPlugin.getClass().getDeclaredAnnotation(IntegrationStage.class).loadStage()); + } else { + Util.debugLogHeavy("Ignored calling because " + integratedPlugin.getName() + " stage is " + integratedPlugin.getClass().getDeclaredAnnotation(IntegrationStage.class).loadStage()); } }); } @@ -64,18 +65,18 @@ public class IntegrationHelper { public void callIntegrationsUnload(@NotNull IntegrateStage stage) { integrations.forEach(integratedPlugin -> { if (integratedPlugin.getClass().getDeclaredAnnotation(IntegrationStage.class).loadStage() == stage) { - Util.debugLogHeavy("Calling for unload "+integratedPlugin.getName()); + Util.debugLogHeavy("Calling for unload " + integratedPlugin.getName()); integratedPlugin.unload(); - }else{ - Util.debugLogHeavy("Ignored calling because "+integratedPlugin.getName()+" stage is "+integratedPlugin.getClass().getDeclaredAnnotation(IntegrationStage.class).loadStage()); + } else { + Util.debugLogHeavy("Ignored calling because " + integratedPlugin.getName() + " stage is " + integratedPlugin.getClass().getDeclaredAnnotation(IntegrationStage.class).loadStage()); } }); } public boolean callIntegrationsCanCreate(@NotNull Player player, @NotNull Location location) { - for(IntegratedPlugin plugin : integrations){ - if (!plugin.canCreateShopHere(player,location)) { - Util.debugLogHeavy("Cancelled by "+plugin.getName()); + for (IntegratedPlugin plugin : integrations) { + if (!plugin.canCreateShopHere(player, location)) { + Util.debugLogHeavy("Cancelled by " + plugin.getName()); return false; } } @@ -83,9 +84,9 @@ public class IntegrationHelper { } public boolean callIntegrationsCanTrade(@NotNull Player player, @NotNull Location location) { - for(IntegratedPlugin plugin : integrations){ - if (!plugin.canTradeShopHere(player,location)) { - Util.debugLogHeavy("Cancelled by "+plugin.getName()); + for (IntegratedPlugin plugin : integrations) { + if (!plugin.canTradeShopHere(player, location)) { + Util.debugLogHeavy("Cancelled by " + plugin.getName()); return false; } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Location/LocationOf.java b/src/main/java/org/maxgamer/quickshop/Util/Location/LocationOf.java index a36158683..a820fd6d3 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Location/LocationOf.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Location/LocationOf.java @@ -11,7 +11,7 @@ public final class LocationOf { @NotNull private static final Pattern PATTERN = - Pattern.compile("((?[^:/]+)[:/])?(?[\\-0-9.]+),(?[\\-0-9.]+),(?[\\-0-9.]+)(:(?[\\-0-9.]+):(?[\\-0-9.]+))?"); + Pattern.compile("((?[^:/]+)[:/])?(?[\\-0-9.]+),(?[\\-0-9.]+),(?[\\-0-9.]+)(:(?[\\-0-9.]+):(?[\\-0-9.]+))?"); @NotNull private final String text; @@ -26,12 +26,12 @@ public final class LocationOf { if (match.matches()) return new Location( - Bukkit.getWorld(match.group("world")), - Double.parseDouble(match.group("x")), - Double.parseDouble(match.group("y")), - Double.parseDouble(match.group("z")), - match.group("yaw") != null ? Float.parseFloat(match.group("yaw")) : 0F, - match.group("pitch") != null ? Float.parseFloat(match.group("pitch")) : 0F + Bukkit.getWorld(match.group("world")), + Double.parseDouble(match.group("x")), + Double.parseDouble(match.group("y")), + Double.parseDouble(match.group("z")), + match.group("yaw") != null ? Float.parseFloat(match.group("yaw")) : 0F, + match.group("pitch") != null ? Float.parseFloat(match.group("pitch")) : 0F ); throw new IllegalStateException("Location string has wrong style!"); diff --git a/src/main/java/org/maxgamer/quickshop/Util/Location/StringOf.java b/src/main/java/org/maxgamer/quickshop/Util/Location/StringOf.java index 8800a1b07..e82873ac2 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Location/StringOf.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Location/StringOf.java @@ -28,16 +28,16 @@ public final class StringOf { String s = world.getName() + ":"; s += String.format( - Locale.ENGLISH, - "%.2f,%.2f,%.2f", - location.getX(), location.getY(), location.getZ() + Locale.ENGLISH, + "%.2f,%.2f,%.2f", + location.getX(), location.getY(), location.getZ() ); if (location.getYaw() != 0f || location.getPitch() != 0f) { s += String.format( - Locale.ENGLISH, - ":%.2f:%.2f", - location.getYaw(), location.getPitch() + Locale.ENGLISH, + ":%.2f:%.2f", + location.getYaw(), location.getPitch() ); } return s; 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 708accaac..99cb28ee9 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Logger/QuickShopLogger.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Logger/QuickShopLogger.java @@ -41,10 +41,10 @@ import static org.bukkit.ChatColor.*; /* * Originally take from Mypet which is a awesome project, * extends PluginLogger in order to replace the default logger. - * + * * This is generally a new built logger system that * rely on the Java logger to provide better customization. - * + * * It is possible to switch to Log4j for better performance in the future. */ public class QuickShopLogger extends PluginLogger { @@ -65,107 +65,110 @@ public class QuickShopLogger extends PluginLogger { //private FileHandler debugLogFileHandler = null; private boolean AnsiSupported = true; - @SneakyThrows + @SneakyThrows public QuickShopLogger(Plugin plugin) { - super(plugin); + super(plugin); - // Ansi setup - try { - if (Ansi.isEnabled()) - registerStyles(); - } catch (NoClassDefFoundError e) { - AnsiSupported = false; - info("Your server doesn't support ANSI color, disabled color formatter."); - } + // Ansi setup + try { + if (Ansi.isEnabled()) + registerStyles(); + } catch (NoClassDefFoundError e) { + AnsiSupported = false; + info("Your server doesn't support ANSI color, disabled color formatter."); + } - // Logger re-naming - String prefix = plugin.getDescription().getPrefix(); - String pluginName = prefix != null ? - "[" + ChatColor.YELLOW + prefix + ChatColor.RESET + "] " : - "[" + ChatColor.YELLOW + plugin.getDescription().getName() + ChatColor.RESET + "] "; - pluginName = AnsiSupported ? applyStyles(pluginName) : pluginName; - - // Apply plugin name for BukkitLogger - Field pluginNameField = PluginLogger.class.getDeclaredField("pluginName"); - pluginNameField.setAccessible(true); // private - pluginNameField.set(this, pluginName); - - // Remove logger name from package name - Field nameField = Logger.class.getDeclaredField("name"); - nameField.setAccessible(true); // private - nameField.set(this, ""); + // Logger re-naming + String prefix = plugin.getDescription().getPrefix(); + String pluginName = prefix != null ? + "[" + ChatColor.YELLOW + prefix + ChatColor.RESET + "] " : + "[" + ChatColor.YELLOW + plugin.getDescription().getName() + ChatColor.RESET + "] "; + pluginName = AnsiSupported ? applyStyles(pluginName) : pluginName; - this.config(); - //super.setUseParentHandlers(false); + // Apply plugin name for BukkitLogger + Field pluginNameField = PluginLogger.class.getDeclaredField("pluginName"); + pluginNameField.setAccessible(true); // private + pluginNameField.set(this, pluginName); + + // Remove logger name from package name + Field nameField = Logger.class.getDeclaredField("name"); + nameField.setAccessible(true); // private + nameField.set(this, ""); + + this.config(); + //super.setUseParentHandlers(false); } // Logging stuffs @Override public void log(LogRecord logRecord) { - String message = logRecord.getMessage(); + String message = logRecord.getMessage(); - if (message != null && AnsiSupported) { - if (logRecord.getLevel() == Level.WARNING) { - message = ChatColor.YELLOW + message; - } - if (logRecord.getLevel() == Level.SEVERE) { - message = ChatColor.RED + message; - } - message = applyStyles(message); - logRecord.setMessage(message); - } - super.log(logRecord); + if (message != null && AnsiSupported) { + if (logRecord.getLevel() == Level.WARNING) { + message = ChatColor.YELLOW + message; + } + if (logRecord.getLevel() == Level.SEVERE) { + message = ChatColor.RED + message; + } + message = applyStyles(message); + logRecord.setMessage(message); + } + super.log(logRecord); } - + /** - * Collect params as a string with blank spaces between + * Collect params as a string with blank spaces between + * * @param params * @return collected string */ public String collectParams(Object... params) { - return Arrays.stream(params).map(String::valueOf).collect(Collectors.joining(" ")); + return Arrays.stream(params).map(String::valueOf).collect(Collectors.joining(" ")); } public void info(Object... params) { - this.info(collectParams(params)); + this.info(collectParams(params)); } public void warning(Object... params) { - this.warning(collectParams(params)); + this.warning(collectParams(params)); } public void severe(Object... params) { - this.severe(collectParams(params)); + this.severe(collectParams(params)); } public void config(Object... params) { - this.config(collectParams(params)); + this.config(collectParams(params)); } public void fine(Object... params) { - this.fine(collectParams(params)); + this.fine(collectParams(params)); } public void finer(Object... params) { - this.finer(collectParams(params)); + this.finer(collectParams(params)); } public void finest(Object... params) { - this.finest(collectParams(params)); + this.finest(collectParams(params)); } // Style stuffs + /** * Apply Ansi styples to the specific message if it contains, * internally converting Bukkit style color text to Ansi code. + * * @param message to apply styles * @return text maybe applied styles */ public String applyStyles(String message) { - for (Entry entry : bukkitToAnsi.entrySet()) - message = entry.getKey().matcher(message).replaceAll(entry.getValue()); + for (Entry entry : bukkitToAnsi.entrySet()) + message = entry.getKey().matcher(message).replaceAll(entry.getValue()); - return message.concat(Ansi.ansi().reset().toString()); + return message.concat(Ansi.ansi().reset().toString()); } /* @@ -173,56 +176,56 @@ public class QuickShopLogger extends PluginLogger { * and stringify Ansi as the value, then register in to the system. */ private void registerStyles() { - // Initial here for secert optimization - bukkitToAnsi = new HashMap(); - IGNORE_CASE = "(?i)"; + // Initial here for secert optimization + bukkitToAnsi = new HashMap(); + IGNORE_CASE = "(?i)"; - // Colors - regAnsiMapping(BLACK, Ansi.Color.BLACK); - regAnsiMapping(DARK_BLUE, Ansi.Color.BLUE); - regAnsiMapping(DARK_GREEN, Ansi.Color.GREEN); - regAnsiMapping(DARK_AQUA, Ansi.Color.CYAN); - regAnsiMapping(DARK_RED, Ansi.Color.RED); - regAnsiMapping(DARK_PURPLE, Ansi.Color.MAGENTA); - regAnsiMapping(GOLD, Ansi.Color.YELLOW); - regAnsiMapping(GRAY, Ansi.Color.WHITE); - regAnsiMapping(DARK_GRAY, Ansi.Color.BLACK, true); - regAnsiMapping(BLUE, Ansi.Color.BLUE, true); - regAnsiMapping(GREEN, Ansi.Color.GREEN, true); - regAnsiMapping(AQUA, Ansi.Color.CYAN, true); - regAnsiMapping(RED, Ansi.Color.RED, true); - regAnsiMapping(LIGHT_PURPLE, Ansi.Color.MAGENTA, true); - regAnsiMapping(YELLOW, Ansi.Color.YELLOW, true); - regAnsiMapping(WHITE, Ansi.Color.WHITE, true); + // Colors + regAnsiMapping(BLACK, Ansi.Color.BLACK); + regAnsiMapping(DARK_BLUE, Ansi.Color.BLUE); + regAnsiMapping(DARK_GREEN, Ansi.Color.GREEN); + regAnsiMapping(DARK_AQUA, Ansi.Color.CYAN); + regAnsiMapping(DARK_RED, Ansi.Color.RED); + regAnsiMapping(DARK_PURPLE, Ansi.Color.MAGENTA); + regAnsiMapping(GOLD, Ansi.Color.YELLOW); + regAnsiMapping(GRAY, Ansi.Color.WHITE); + regAnsiMapping(DARK_GRAY, Ansi.Color.BLACK, true); + regAnsiMapping(BLUE, Ansi.Color.BLUE, true); + regAnsiMapping(GREEN, Ansi.Color.GREEN, true); + regAnsiMapping(AQUA, Ansi.Color.CYAN, true); + regAnsiMapping(RED, Ansi.Color.RED, true); + regAnsiMapping(LIGHT_PURPLE, Ansi.Color.MAGENTA, true); + regAnsiMapping(YELLOW, Ansi.Color.YELLOW, true); + regAnsiMapping(WHITE, Ansi.Color.WHITE, true); - // Effects - regAnsiMapping(MAGIC, Ansi.Attribute.BLINK_SLOW); - regAnsiMapping(BOLD, Ansi.Attribute.UNDERLINE_DOUBLE); - regAnsiMapping(STRIKETHROUGH, Ansi.Attribute.STRIKETHROUGH_ON); - regAnsiMapping(UNDERLINE, Ansi.Attribute.UNDERLINE); - regAnsiMapping(ITALIC, Ansi.Attribute.ITALIC); - regAnsiMapping(RESET, Ansi.Attribute.RESET); + // Effects + regAnsiMapping(MAGIC, Ansi.Attribute.BLINK_SLOW); + regAnsiMapping(BOLD, Ansi.Attribute.UNDERLINE_DOUBLE); + regAnsiMapping(STRIKETHROUGH, Ansi.Attribute.STRIKETHROUGH_ON); + regAnsiMapping(UNDERLINE, Ansi.Attribute.UNDERLINE); + regAnsiMapping(ITALIC, Ansi.Attribute.ITALIC); + regAnsiMapping(RESET, Ansi.Attribute.RESET); } /* * Register a mapping from Bukkit color to Ansi */ private void regAnsiMapping(ChatColor bukkColor, Ansi.Color ansiColor) { - regAnsiMapping0(toPattern(bukkColor), toDesc(ansiColor)); + regAnsiMapping0(toPattern(bukkColor), toDesc(ansiColor)); } /* * Register a mapping from Bukkit color to Ansi */ private void regAnsiMapping(ChatColor bukkColor, Ansi.Attribute ansiAttribute) { - regAnsiMapping0(toPattern(bukkColor), toDesc(ansiAttribute)); + regAnsiMapping0(toPattern(bukkColor), toDesc(ansiAttribute)); } /* * Register a mapping from Bukkit color to Ansi, with color option */ private void regAnsiMapping(ChatColor bukkColor, Ansi.Color ansiColor, boolean intensity) { - regAnsiMapping0(toPattern(bukkColor), toDesc(ansiColor, intensity)); + regAnsiMapping0(toPattern(bukkColor), toDesc(ansiColor, intensity)); } /* @@ -230,52 +233,57 @@ public class QuickShopLogger extends PluginLogger { * and this is the genuine type for them to be registered. */ private void regAnsiMapping0(Pattern bukkitPattern, String ansiDesc) { - this.bukkitToAnsi.put(bukkitPattern, ansiDesc); + this.bukkitToAnsi.put(bukkitPattern, ansiDesc); } /** * Convert a Bukkit color to regex pattern + * * @param bukkitColor the bukkit color * @return the pattern */ private Pattern toPattern(ChatColor bukkitColor) { - return Pattern.compile(IGNORE_CASE.concat(bukkitColor.toString())); + return Pattern.compile(IGNORE_CASE.concat(bukkitColor.toString())); } /** * To populate a Ansi with a reset attribute ahead + * * @param ansiColor * @return Ansi with reset ahead */ private Ansi resetWith(Ansi.Color ansiColor) { - return Ansi.ansi().a(Ansi.Attribute.RESET).fg(ansiColor); + return Ansi.ansi().a(Ansi.Attribute.RESET).fg(ansiColor); } /** * Convert a Ansi to its description text + * * @param ansiColor Ansi * @param intensity Ansi color option * @return stringified Ansi */ private String toDesc(Ansi.Color ansiColor, boolean intensity) { - return intensity ? resetWith(ansiColor).bold().toString() : toDesc(ansiColor); + return intensity ? resetWith(ansiColor).bold().toString() : toDesc(ansiColor); } /** * Convert a Ansi to its description text + * * @param ansiColor Ansi * @return stringified Ansi */ private String toDesc(Ansi.Color ansiColor) { - return resetWith(ansiColor).boldOff().toString(); + return resetWith(ansiColor).boldOff().toString(); } /** * Convert a Ansi to its description text + * * @param ansiAttribute Ansi * @return stringified Ansi */ private String toDesc(Ansi.Attribute ansiAttribute) { - return Ansi.ansi().a(Ansi.Attribute.RESET).toString(); + return Ansi.ansi().a(Ansi.Attribute.RESET).toString(); } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/MojangAPI/AssetJson.java b/src/main/java/org/maxgamer/quickshop/Util/MojangAPI/AssetJson.java index e5084f4c3..6d4b3590f 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/MojangAPI/AssetJson.java +++ b/src/main/java/org/maxgamer/quickshop/Util/MojangAPI/AssetJson.java @@ -30,38 +30,40 @@ import org.maxgamer.quickshop.Util.MsgUtil; import org.maxgamer.quickshop.Util.Util; public class AssetJson { - @NotNull String gameAssets; final String pathTemplate = "minecraft/lang/{0}.json"; - public AssetJson(@NotNull String json){ + @NotNull String gameAssets; + + public AssetJson(@NotNull String json) { this.gameAssets = json; } + @Nullable - public String getLanguageHash(@NotNull String languageCode){ + public String getLanguageHash(@NotNull String languageCode) { JsonObject json = new JsonParser().parse(this.gameAssets).getAsJsonObject(); - if(json == null || json.isJsonNull()){ - Util.debugLog("Cannot parse the json: "+this.gameAssets); + if (json == null || json.isJsonNull()) { + Util.debugLog("Cannot parse the json: " + this.gameAssets); return null; } JsonElement obje = json.get("objects"); - if(obje == null){ - Util.debugLog("Json element is null for json "+this.gameAssets); - return null; + if (obje == null) { + Util.debugLog("Json element is null for json " + this.gameAssets); + return null; } JsonObject objs = obje.getAsJsonObject(); - if(objs == null || objs.isJsonNull()){ - Util.debugLog("Json object is null."); - return null; + if (objs == null || objs.isJsonNull()) { + Util.debugLog("Json object is null."); + return null; } - JsonObject langObj = objs.getAsJsonObject(MsgUtil.fillArgs(pathTemplate,languageCode)); - if(langObj == null || langObj.isJsonNull()){ - Util.debugLog("Cannot find request path."); - return null; + JsonObject langObj = objs.getAsJsonObject(MsgUtil.fillArgs(pathTemplate, languageCode)); + if (langObj == null || langObj.isJsonNull()) { + Util.debugLog("Cannot find request path."); + return null; } JsonPrimitive hashObj = langObj.getAsJsonPrimitive("hash"); - if(hashObj == null || hashObj.isJsonNull()){ + if (hashObj == null || hashObj.isJsonNull()) { Util.debugLog("Cannot get hash."); return null; } return hashObj.getAsString(); - } - } + } +} diff --git a/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java b/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java index 87b5d9b93..28f7a63cb 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java +++ b/src/main/java/org/maxgamer/quickshop/Util/MsgUtil.java @@ -60,9 +60,9 @@ import java.util.logging.Level; @SuppressWarnings("WeakerAccess") public class MsgUtil { + public static String invaildMsg = "Invaild message"; private static YamlConfiguration builtInDefaultLanguage = YamlConfiguration.loadConfiguration(new InputStreamReader(QuickShop.instance.getLanguage() .getFile("en", "messages"))); - public static String invaildMsg = "Invaild message"; private static YamlConfiguration enchi18n; private static boolean inited; private static YamlConfiguration itemi18n; @@ -129,7 +129,7 @@ public class MsgUtil { */ public static boolean flush(@NotNull OfflinePlayer p) { Player player = p.getPlayer(); - if (player!= null) { + if (player != null) { UUID pName = p.getUniqueId(); LinkedList msgs = player_messages.get(pName); if (msgs != null) { @@ -208,7 +208,7 @@ public class MsgUtil { public static String getMessage(@NotNull String loc, @Nullable CommandSender player, @NotNull String... args) { Optional raw = messagei18n.getString(loc); if (!raw.isPresent()) { - Util.debugLog("ERR: MsgUtil cannot find the the phrase at "+loc+", printing the all readed datas: "+messagei18n); + Util.debugLog("ERR: MsgUtil cannot find the the phrase at " + loc + ", printing the all readed datas: " + messagei18n); return invaildMsg + ": " + loc; } @@ -218,11 +218,12 @@ public class MsgUtil { try { filled = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, filled); Util.debugLog("Processed message " + filled + " by PlaceHolderAPI."); - }catch (Exception ignored){ - if(((OfflinePlayer) player).getPlayer() != null){ + } catch (Exception ignored) { + if (((OfflinePlayer) player).getPlayer() != null) { try { filled = PlaceholderAPI.setPlaceholders(((OfflinePlayer) player).getPlayer(), filled); - }catch (Exception ignore){} + } catch (Exception ignore) { + } } } } @@ -271,7 +272,7 @@ public class MsgUtil { return Util.prettifyText(potionString); } - public static void loadGameLanguage(@NotNull String languageCode){ + public static void loadGameLanguage(@NotNull String languageCode) { gameLanguage = new GameLanguage(languageCode); } @@ -282,40 +283,41 @@ public class MsgUtil { .getString("language", "en"); //noinspection ConstantConditions - loadGameLanguage(plugin.getConfig().getString("game-language","default")); + loadGameLanguage(plugin.getConfig().getString("game-language", "default")); //Init nJson IFile nJson; - if(plugin.getResource("messages/"+languageCode+".json") == null){ - nJson = new JSONFile(plugin, new File(plugin.getDataFolder(),"messages.json"),"messages/en.json",true); - }else{ - nJson = new JSONFile(plugin, new File(plugin.getDataFolder(),"messages.json"),"messages/"+languageCode+".json",true); + if (plugin.getResource("messages/" + languageCode + ".json") == null) { + nJson = new JSONFile(plugin, new File(plugin.getDataFolder(), "messages.json"), "messages/en.json", true); + } else { + nJson = new JSONFile(plugin, new File(plugin.getDataFolder(), "messages.json"), "messages/" + languageCode + ".json", true); } nJson.create(); File oldMsgFile = new File(plugin.getDataFolder(), "messages.yml"); - if(oldMsgFile.exists()){ //Old messages file convert. + if (oldMsgFile.exists()) { //Old messages file convert. plugin.getLogger().info("Converting the old format message.yml to message.json..."); - plugin.getLanguage().saveFile(languageCode,"messages","messages.json"); + plugin.getLanguage().saveFile(languageCode, "messages", "messages.json"); YamlConfiguration oldMsgI18n = YamlConfiguration.loadConfiguration(oldMsgFile); - for (String key:oldMsgI18n.getKeys(true)){ + for (String key : oldMsgI18n.getKeys(true)) { oldMsgI18n.get(key); } nJson.save(); try { Files.move(oldMsgFile.toPath(), new File(plugin.getDataFolder(), "messages.yml.bak").toPath()); - }catch (IOException ignore){} - if(oldMsgFile.exists()){ + } catch (IOException ignore) { + } + if (oldMsgFile.exists()) { oldMsgFile.delete(); } plugin.getLogger().info("Successfully converted, Continue loading..."); - }else{ + } else { Util.debugLog("Loading language file from exist file..."); - if(!new File(plugin.getDataFolder(),"messages.json").exists()){ - plugin.getLanguage().saveFile(languageCode,"messages","messages.json"); - nJson.loadFromString(Util.readToString(new File(plugin.getDataFolder(),"messages.json").getAbsolutePath())); - } + if (!new File(plugin.getDataFolder(), "messages.json").exists()) { + plugin.getLanguage().saveFile(languageCode, "messages", "messages.json"); + nJson.loadFromString(Util.readToString(new File(plugin.getDataFolder(), "messages.json").getAbsolutePath())); + } } messagei18n = nJson; /* Set default language vesion and update messages.yml */ @@ -425,7 +427,7 @@ public class MsgUtil { continue; } String potionName = gameLanguage.getPotion(potion); - plugin.getLogger().info("Found new potion [" +potionName + "] , adding it to the config..."); + plugin.getLogger().info("Found new potion [" + potionName + "] , adding it to the config..."); potioni18n.set("potioni18n." + potion.getName(), potionName); } try { @@ -839,7 +841,7 @@ public class MsgUtil { enchs = items.getItemMeta().getEnchants(); } if (!enchs.isEmpty()) { - chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants", p,"")); + chatSheetPrinter.printCenterLine(MsgUtil.getMessage("menu.enchants", p, "")); for (Entry entries : enchs.entrySet()) { chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getEnchi18n(entries.getKey()) + " " + entries.getValue()); } @@ -855,14 +857,14 @@ public class MsgUtil { } } } - if(items.getItemMeta() instanceof PotionMeta){ - PotionMeta potionMeta = (PotionMeta)items.getItemMeta(); + if (items.getItemMeta() instanceof PotionMeta) { + PotionMeta potionMeta = (PotionMeta) items.getItemMeta(); PotionEffectType potionEffectType = potionMeta.getBasePotionData().getType().getEffectType(); - if(potionEffectType != null){ + if (potionEffectType != null) { chatSheetPrinter.printLine(MsgUtil.getMessage("menu.effects", p)); - chatSheetPrinter.printLine(ChatColor.YELLOW+MsgUtil.getPotioni18n(potionEffectType)); + chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getPotioni18n(potionEffectType)); } - potionMeta.getCustomEffects().forEach((potionEffect -> chatSheetPrinter.printLine(ChatColor.YELLOW+MsgUtil.getPotioni18n(potionEffect.getType())))); + potionMeta.getCustomEffects().forEach((potionEffect -> chatSheetPrinter.printLine(ChatColor.YELLOW + MsgUtil.getPotioni18n(potionEffect.getType())))); } chatSheetPrinter.printFooter(); } @@ -1143,6 +1145,7 @@ public class MsgUtil { } messagei18n.set(path, objFromBuiltIn); } + public static IFile getI18nFile() { return messagei18n; } diff --git a/src/main/java/org/maxgamer/quickshop/Util/Paste/Paste.java b/src/main/java/org/maxgamer/quickshop/Util/Paste/Paste.java index 2e1348465..1ceb821b9 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Paste/Paste.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Paste/Paste.java @@ -82,7 +82,7 @@ public class Paste { finalReport.append("Unknown").append("%").append("Unknown error"); break; } - }catch(Exception e){ + } catch (Exception e) { finalReport.append("Unknown").append("%").append("Unknown error"); } @@ -106,17 +106,17 @@ public class Paste { List arguments = runtimeMxBean.getInputArguments(); finalReport.append("\tInput Args: ").append(Util.list2String(arguments)).append("\n"); finalReport.append("\tVM Name: ").append(runtimeMxBean.getVmName()).append("\n"); - Map sys = runtimeMxBean.getSystemProperties(); + Map sys = runtimeMxBean.getSystemProperties(); List sysData = new ArrayList<>(); - sys.keySet().forEach(key-> sysData.add(key+"="+sys.get(key))); + sys.keySet().forEach(key -> sysData.add(key + "=" + sys.get(key))); finalReport.append("\tSystem Properties: ").append(Util.list2String(sysData)).append("\n"); finalReport.append("\tPlayers: ").append(Bukkit.getOnlinePlayers().size()).append("/").append(Bukkit.getMaxPlayers()) .append("\n"); finalReport.append("\tOnlineMode: ").append(Bukkit.getOnlineMode()).append("\n"); finalReport.append("\tBukkitVersion: ").append(Bukkit.getVersion()).append("\n"); finalReport.append("\tWorldContainer: ").append(Bukkit.getWorldContainer()).append("\n"); - List modules = new ArrayList<>();; - plugin.getIntegrationHelper().getIntegrations().forEach(m->modules.add(m.getName())); + List modules = new ArrayList<>(); + plugin.getIntegrationHelper().getIntegrations().forEach(m -> modules.add(m.getName())); finalReport.append("\tLoaded Integrations: ").append(Util.list2String(modules)).append("\n"); finalReport.append("================================================\n"); finalReport.append("Worlds:\n"); @@ -243,23 +243,27 @@ public class Paste { } return report; } + @Nullable - public String paste(@NotNull String content){ + public String paste(@NotNull String content) { PasteInterface paster; - try{ + try { //EngineHub Pastebin paster = new EngineHubPaster(); return paster.pasteTheText(content); - }catch (Exception ignore){} - try{ + } catch (Exception ignore) { + } + try { //Ubuntu Pastebin paster = new UbuntuPaster(); return paster.pasteTheText(content); - }catch (Exception ignore){} + } catch (Exception ignore) { + } return null; } + @Nullable - public String paste(@NotNull String content,int type){ + public String paste(@NotNull String content, int type) { PasteInterface paster; if (type == 0) { try { diff --git a/src/main/java/org/maxgamer/quickshop/Util/Paste/UbuntuPaster.java b/src/main/java/org/maxgamer/quickshop/Util/Paste/UbuntuPaster.java index b17857376..e5dbfdd86 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Paste/UbuntuPaster.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Paste/UbuntuPaster.java @@ -29,7 +29,7 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; -public class UbuntuPaster implements PasteInterface{ +public class UbuntuPaster implements PasteInterface { /** * Paste a text to paste.ubuntu.com * diff --git a/src/main/java/org/maxgamer/quickshop/Util/ReflectFactory.java b/src/main/java/org/maxgamer/quickshop/Util/ReflectFactory.java index 39960324f..86384bc97 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ReflectFactory.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ReflectFactory.java @@ -24,13 +24,13 @@ import org.bukkit.Bukkit; import java.lang.reflect.Field; public class ReflectFactory { - public static String getServerVersion(){ + public static String getServerVersion() { try { Field consoleField = Bukkit.getServer().getClass().getDeclaredField("console"); consoleField.setAccessible(true); // protected Object console = consoleField.get(Bukkit.getServer()); // dedicated server return String.valueOf(console.getClass().getSuperclass().getMethod("getVersion").invoke(console)); - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); return "Unknown"; } diff --git a/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java b/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java index 1e55b8455..08f08d805 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java +++ b/src/main/java/org/maxgamer/quickshop/Util/SentryErrorReporter.java @@ -102,11 +102,11 @@ public class SentryErrorReporter { unit(); return; } - new BukkitRunnable(){ + new BukkitRunnable() { @Override public void run() { Paste paste = new Paste(plugin); - lastPaste = paste.paste(paste.genNewPaste(),1); + lastPaste = paste.paste(paste.genNewPaste(), 1); } }.runTaskAsynchronously(plugin); } @@ -121,10 +121,10 @@ public class SentryErrorReporter { if (!enabled) { return false; } - if(UpdateWatcher.hasNewUpdate){ //We only receive latest reports. + if (UpdateWatcher.hasNewUpdate) { //We only receive latest reports. return false; } - if(new IncompatibleChecker().isIncompatible(Util.getNMSVersion())){ //Ignore errors if user install quickshop on unsupported version. + if (new IncompatibleChecker().isIncompatible(Util.getNMSVersion())) { //Ignore errors if user install quickshop on unsupported version. return false; } StackTraceElement stackTraceElement; @@ -154,10 +154,10 @@ public class SentryErrorReporter { if (throwable == null) { return false; } - if(throwable.getMessage() == null){ + if (throwable.getMessage() == null) { return false; } - if(throwable.getMessage().contains("Could not pass event")){ + if (throwable.getMessage().contains("Could not pass event")) { return throwable.getMessage().contains("QuickShop"); } while (throwable.getCause() != null) { @@ -203,7 +203,7 @@ public class SentryErrorReporter { */ public @Nullable UUID sendError(@NotNull Throwable throwable, @NotNull String... context) { try { - if(QuickShop.instance.getBootError() != null){ + if (QuickShop.instance.getBootError() != null) { return null; //Don't report any errors if boot failed. } if (tempDisable) { @@ -242,7 +242,7 @@ public class SentryErrorReporter { try { Paste paste = new Paste(plugin); pasteURL = paste.paste(paste.genNewPaste()); - if(pasteURL != null && !pasteURL.isEmpty()){ + if (pasteURL != null && !pasteURL.isEmpty()) { lastPaste = pasteURL; } } catch (Throwable ex) { @@ -259,7 +259,7 @@ public class SentryErrorReporter { plugin.getLogger().warning("Event ID: " + this.context.getLastEventId()); plugin.getLogger().warning("Server ID: " + plugin.getServerUniqueID()); plugin.getLogger().warning("====QuickShop Error Report E N D==="); - if(Util.isDevMode()){ + if (Util.isDevMode()) { throwable.printStackTrace(); } return this.context.getLastEventId(); diff --git a/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/BukkitAPIWrapper.java b/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/BukkitAPIWrapper.java index a919e9374..c19d6933f 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/BukkitAPIWrapper.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/BukkitAPIWrapper.java @@ -32,7 +32,10 @@ import java.util.concurrent.CompletableFuture; public interface BukkitAPIWrapper { void teleportEntity(@NotNull Entity entity, @NotNull Location location, @Nullable PlayerTeleportEvent.TeleportCause cause); - void getChunkAt(@NotNull World world,@NotNull Location location, @NotNull CompletableFuture futureTask); - void getChunkAt(@NotNull World world,int x,int z, @NotNull CompletableFuture futureTask); + + void getChunkAt(@NotNull World world, @NotNull Location location, @NotNull CompletableFuture futureTask); + + void getChunkAt(@NotNull World world, int x, int z, @NotNull CompletableFuture futureTask); + void getChunkAt(@NotNull World world, @NotNull Block block, @NotNull CompletableFuture futureTask); } diff --git a/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/PaperWrapper.java b/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/PaperWrapper.java index fb02d377c..2b58b07b7 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/PaperWrapper.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/PaperWrapper.java @@ -31,13 +31,13 @@ import org.jetbrains.annotations.Nullable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -public class PaperWrapper implements BukkitAPIWrapper{ +public class PaperWrapper implements BukkitAPIWrapper { @Override public void teleportEntity(@NotNull Entity entity, @NotNull Location location, @Nullable PlayerTeleportEvent.TeleportCause cause) { - if(cause == null) { + if (cause == null) { entity.teleportAsync(location); - }else { - entity.teleportAsync(location,cause); + } else { + entity.teleportAsync(location, cause); } } @@ -53,9 +53,9 @@ public class PaperWrapper implements BukkitAPIWrapper{ @Override public void getChunkAt(@NotNull World world, int x, int z, @NotNull CompletableFuture futureTask) { try { - futureTask.complete(world.getChunkAtAsync(x,z).get()); + futureTask.complete(world.getChunkAtAsync(x, z).get()); } catch (InterruptedException | ExecutionException e) { - futureTask.complete(world.getChunkAt(x,z)); + futureTask.complete(world.getChunkAt(x, z)); } } diff --git a/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/SpigotWrapper.java b/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/SpigotWrapper.java index 9f96d642e..0c4011c7e 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/SpigotWrapper.java +++ b/src/main/java/org/maxgamer/quickshop/Util/ServerForkWrapper/SpigotWrapper.java @@ -33,10 +33,10 @@ import java.util.concurrent.CompletableFuture; public class SpigotWrapper implements BukkitAPIWrapper { @Override public void teleportEntity(@NotNull Entity entity, @NotNull Location location, @Nullable PlayerTeleportEvent.TeleportCause cause) { - if(cause == null){ + if (cause == null) { entity.teleport(location); - }else{ - entity.teleport(location,cause); + } else { + entity.teleport(location, cause); } } @@ -48,7 +48,7 @@ public class SpigotWrapper implements BukkitAPIWrapper { @Override public void getChunkAt(@NotNull World world, int x, int z, @NotNull CompletableFuture futureTask) { - futureTask.complete(world.getChunkAt(x,z)); + futureTask.complete(world.getChunkAt(x, z)); } @Override diff --git a/src/main/java/org/maxgamer/quickshop/Util/Updater.java b/src/main/java/org/maxgamer/quickshop/Util/Updater.java index c2b22bfae..ab96435fd 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Updater.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Updater.java @@ -63,6 +63,7 @@ public class Updater { return new UpdateInfomation(false, null); } } + public static byte[] downloadUpdatedJar() throws IOException { @Nullable String uurl; long uurlSize; @@ -70,7 +71,7 @@ public class Updater { ReleaseJsonContainer.AssetsBean bean = Objects.requireNonNull(new GithubAPI().getLatestRelease()); uurl = bean.getBrowser_download_url(); uurlSize = bean.getSize(); - }catch (Throwable ig){ + } catch (Throwable ig) { throw new IOException(ig.getMessage()); } @@ -78,12 +79,12 @@ public class Updater { throw new IOException("Failed read the URL, cause it is empty."); } Util.debugLog("Downloading from " + uurl); - InputStream is = HttpRequest.get(new URL(uurl)).header("User-Agent","QuickShop-Reremake " + QuickShop.getVersion()).execute().getInputStream(); + InputStream is = HttpRequest.get(new URL(uurl)).header("User-Agent", "QuickShop-Reremake " + QuickShop.getVersion()).execute().getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len; long downloaded = 0; - if(is == null){ + if (is == null) { throw new IOException("Failed downloading: Cannot open connection with remote server."); } while ((len = is.read(buff)) != -1) { diff --git a/src/main/java/org/maxgamer/quickshop/Util/Util.java b/src/main/java/org/maxgamer/quickshop/Util/Util.java index 8364415b6..f36379993 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Util.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Util.java @@ -64,6 +64,7 @@ import java.util.Map.Entry; */ @SuppressWarnings("WeakerAccess") public class Util { + static short tookLongTimeCostTimes; private static EnumSet blacklist = EnumSet.noneOf(Material.class); @Getter private static List debugLogs = new LinkedList<>(); @@ -192,8 +193,6 @@ public class Util { return space; } - static short tookLongTimeCostTimes; - /** * Print debug log when plugin running on dev mode. * @@ -221,7 +220,7 @@ public class Util { int codeLine = Thread.currentThread().getStackTrace()[2].getLineNumber(); for (String log : logs) { - String text = "["+ChatColor.DARK_GREEN + ChatColor.BOLD + "DEBUG" + ChatColor.RESET + "] [" + ChatColor.DARK_GREEN + className + ChatColor.RESET + "]" + " [" + ChatColor.DARK_GREEN + methodName + ChatColor.RESET + "] (" + ChatColor.DARK_GREEN + codeLine + ChatColor.RESET + ") " + log; + String text = "[" + ChatColor.DARK_GREEN + ChatColor.BOLD + "DEBUG" + ChatColor.RESET + "] [" + ChatColor.DARK_GREEN + className + ChatColor.RESET + "]" + " [" + ChatColor.DARK_GREEN + methodName + ChatColor.RESET + "] (" + ChatColor.DARK_GREEN + codeLine + ChatColor.RESET + ") " + log; debugLogs.add(Colorizer.stripColors(text)); if (debugLogs.size() > 500000) /* Keep debugLogs max can have 500k lines. */ { debugLogs.remove(0); @@ -243,6 +242,7 @@ public class Util { } } } + /** * Print debug log when plugin running on dev mode. * @@ -268,7 +268,7 @@ public class Util { int codeLine = Thread.currentThread().getStackTrace()[2].getLineNumber(); for (String log : logs) { - String text = "["+ChatColor.DARK_GREEN + ChatColor.BOLD + "DEBUG" + ChatColor.RESET + "] [" + ChatColor.DARK_GREEN + className + ChatColor.RESET + "]" + " [" + ChatColor.DARK_GREEN + methodName + ChatColor.RESET + "] (" + ChatColor.DARK_GREEN + codeLine + ChatColor.RESET + ") " + log; + String text = "[" + ChatColor.DARK_GREEN + ChatColor.BOLD + "DEBUG" + ChatColor.RESET + "] [" + ChatColor.DARK_GREEN + className + ChatColor.RESET + "]" + " [" + ChatColor.DARK_GREEN + methodName + ChatColor.RESET + "] (" + ChatColor.DARK_GREEN + codeLine + ChatColor.RESET + ") " + log; debugLogs.add(Colorizer.stripColors(text)); if (debugLogs.size() > 500000) /* Keep debugLogs max can have 500k lines. */ { debugLogs.remove(0); @@ -1323,7 +1323,7 @@ public class Util { final MessageDigest instance = MessageDigest.getInstance("MD5"); instance.update(s.getBytes(StandardCharsets.UTF_8)); final byte[] digest = instance.digest(); - final StringBuilder sb = new StringBuilder(""); + final StringBuilder sb = new StringBuilder(); for (int b : digest) { int n = b; if (n < 0) { diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/DisplayDupeRemoverWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/DisplayDupeRemoverWatcher.java index 96ce84616..9436a9016 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/DisplayDupeRemoverWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/DisplayDupeRemoverWatcher.java @@ -28,11 +28,13 @@ import java.util.Queue; public class DisplayDupeRemoverWatcher extends BukkitRunnable { private Queue checkQueue = new LinkedList<>(); + @Override public void run() { checkQueue.forEach(DisplayItem::removeDupe); } - public void add(@NotNull DisplayItem displayItem){ + + public void add(@NotNull DisplayItem displayItem) { checkQueue.offer(displayItem); } } diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/ShopContainerWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/ShopContainerWatcher.java index 48a968e25..f6f9c9af2 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/ShopContainerWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/ShopContainerWatcher.java @@ -39,7 +39,7 @@ public class ShopContainerWatcher extends BukkitRunnable { this.plugin = plugin; } - public void scheduleCheck(@NotNull Shop shop){ + public void scheduleCheck(@NotNull Shop shop) { checkQueue.add(shop); } @@ -48,10 +48,10 @@ public class ShopContainerWatcher extends BukkitRunnable { long beginTime = System.currentTimeMillis(); Shop shop = checkQueue.poll(); while (shop != null) { - if(shop instanceof ContainerShop){ + if (shop instanceof ContainerShop) { ((ContainerShop) shop).checkContainer(); } - if(System.currentTimeMillis() - beginTime > 45){ //Don't let quickshop eat more than 45 ms per tick. + if (System.currentTimeMillis() - beginTime > 45) { //Don't let quickshop eat more than 45 ms per tick. break; } shop = checkQueue.poll(); diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/SignUpdateWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/SignUpdateWatcher.java index b3d01a0b6..851bf80fe 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/SignUpdateWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/SignUpdateWatcher.java @@ -30,12 +30,13 @@ import java.util.Queue; public class SignUpdateWatcher extends BukkitRunnable { private QuickShop plugin; private Queue signUpdateQueue = new LinkedList<>(); - public SignUpdateWatcher(QuickShop plugin){ + + public SignUpdateWatcher(QuickShop plugin) { this.plugin = plugin; } - public void scheduleSignUpdate(@NotNull Shop shop){ - if(signUpdateQueue.contains(shop)){ + public void scheduleSignUpdate(@NotNull Shop shop) { + if (signUpdateQueue.contains(shop)) { return; //Ignore } signUpdateQueue.add(shop); @@ -44,7 +45,7 @@ public class SignUpdateWatcher extends BukkitRunnable { @Override public void run() { Shop shop = signUpdateQueue.poll(); - while (shop !=null){ + while (shop != null) { shop.setSignText(); shop = signUpdateQueue.poll(); } diff --git a/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java b/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java index 03689f58b..67ab548d7 100644 --- a/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java +++ b/src/main/java/org/maxgamer/quickshop/Watcher/UpdateWatcher.java @@ -38,8 +38,8 @@ import java.util.List; import java.util.Random; public class UpdateWatcher implements Listener { - private static BukkitTask cronTask = null; public static boolean hasNewUpdate = false; + private static BukkitTask cronTask = null; private static UpdateInfomation info = null; public static String fixVer(@NotNull String originalVer) { @@ -67,7 +67,7 @@ public class UpdateWatcher implements Listener { hasNewUpdate = true; if (!info.isBeta()) { - QuickShop.instance.getLogger().info("A new version of QuickShop has been released! ["+info.getVersion()+"]"); + QuickShop.instance.getLogger().info("A new version of QuickShop has been released! [" + info.getVersion() + "]"); QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/"); Bukkit.getOnlinePlayers().forEach(player -> {