Format code and Cleanup imports

Former-commit-id: 6d5b0d3c1dd1009e9df7b8e8faf27ea8b95e5f8d
This commit is contained in:
Ghost_chu committed 2020-01-18 22:05:53 +08:00
1 parent c35ea63384
commit 57b341a63f
93 files changed
+1163 -1121

No files matched your search

@@ -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;
}
}
@@ -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);
}
@@ -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;
}
@@ -79,15 +79,15 @@ public class SubCommand_Debug implements CommandProcesser {
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> 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<String,String> 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<String, String> sys = runtimeMxBean.getSystemProperties();
List<String> 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.");
@@ -72,13 +72,13 @@ public class SubCommand_Find implements CommandProcesser {
final int chunkRadius = (int) minDistance / 16 + 1;
Shop closest = null;
CompletableFuture<Chunk> 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))));
}
}
@@ -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));
}
}
}
@@ -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);
}
}
}
@@ -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!");
}
}
@@ -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<>();
}
}
@@ -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;
}
}
@@ -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));
@@ -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());
@@ -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())));
}
}
@@ -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));
@@ -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));
@@ -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;
}
@@ -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())));
}
@@ -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));
@@ -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;
@@ -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));
@@ -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) {
}
}
}
@@ -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.
*
@@ -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;
}
@@ -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();
}
}
@@ -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;
}
}
@@ -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,
@@ -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
@@ -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()
);
}
@@ -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 <T> object type
* @param <T> object type
* @return if path does not exist returns and set the path with fallback object
*/
@NotNull
<T> T getOrSet(@NotNull final String path, @NotNull T fallback);
@NotNull <T> 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:
*
* <p>
* 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);
@@ -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
)
)
)
);
}
}
@@ -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()
)
)
)
);
}
}
@@ -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).");
}
}
}
@@ -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;
}
@@ -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);
}
@@ -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;
}
@@ -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;
@@ -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();
}
@@ -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<CustomChart> 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.
*
@@ -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() {
@@ -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<Map <String, Object>>(){}.getType(),
new MapDeserializerDoubleAsIntFix())
.create();
input = gson.fromJson(contents, new TypeToken<Map<String, Object>>(){}.getType());
.registerTypeAdapter(new TypeToken<Map<String, Object>>() {
}.getType(),
new MapDeserializerDoubleAsIntFix())
.create();
input = gson.fromJson(contents, new TypeToken<Map<String, Object>>() {
}.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<Map<String, Object>> {
@Override @SuppressWarnings("unchecked")
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return (Map<String, Object>) read(json);
}
public Object read(JsonElement in) {
if(in.isJsonArray()){
if (in.isJsonArray()) {
List<Object> list = new ArrayList<Object>();
JsonArray arr = in.getAsJsonArray();
for (JsonElement anArr : arr) {
list.add(read(anArr));
}
return list;
}else if(in.isJsonObject()){
} else if (in.isJsonObject()) {
Map<String, Object> map = new LinkedTreeMap<String, Object>();
JsonObject obj = in.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
for(Map.Entry<String, JsonElement> entry: entitySet){
for (Map.Entry<String, JsonElement> 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();
}
}
@@ -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.
*
* <p>
* 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<String, Object> 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.
*
* <p>
* 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<Object> buildList(@NotNull final Collection<?> collection) {
final List<Object> result = new ArrayList<Object>(collection.size());
@@ -116,10 +116,11 @@ public class SerializationHelper {
/**
* Parses through the input map to deal with serialized objects a la {@link ConfigurationSerializable}.
*
* <p>
* 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}.
*
* <p>
* Functions similarly to {@link #deserialize(java.util.Map)} but only for detecting lists within
* lists and maps within lists.
*/
@@ -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.
*
* <p>
* 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);
@@ -29,6 +29,13 @@ public class Colorizer {
private static Map<String, String> 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()));
}
}
}
@@ -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) {
@@ -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 + "%";
@@ -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;
}
}
@@ -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;
}
@@ -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();
}
@@ -27,5 +27,6 @@ import java.lang.annotation.*;
@Inherited
public @interface IntegrationStage {
IntegrateStage loadStage() default IntegrateStage.onEnableAfter;
IntegrateStage unloadStage() default IntegrateStage.onUnloadBegin;
}
@@ -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
@@ -36,10 +36,11 @@ public class ResidenceIntegration implements IntegratedPlugin {
List<String> createLimits;
List<String> 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;
}
}
@@ -23,7 +23,7 @@ import java.util.ArrayList;
import java.util.List;
public enum TownyFlags {
OWN,MODIFY,SHOPTYPE;
OWN, MODIFY, SHOPTYPE;
public static List<TownyFlags> deserialize(List<String> list) {
List<TownyFlags> result = new ArrayList<>();
@@ -35,10 +35,12 @@ import java.util.List;
public class TownyIntegration implements IntegratedPlugin {
private List<TownyFlags> createFlags;
private List<TownyFlags> 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:
@@ -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<WorldGuardFlags> deserialize(List<String> list) {
List<WorldGuardFlags> result = new ArrayList<>();
@@ -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<String> 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<String> keysA = new HashSet<>(attached.getKeys(true));
// Set<String> keysB = new HashSet<>(getConfig().getKeys(true));
// Set<String> 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<String> tiers = new ArrayList<>(Arrays.asList(miss.split("\\.")));
// StringBuilder miss2Yaml = new StringBuilder();
// int spaces = 2;
// Iterator<String> 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<String> keysA = new HashSet<>(attached.getKeys(true));
// Set<String> keysB = new HashSet<>(getConfig().getKeys(true));
// Set<String> 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<String> tiers = new ArrayList<>(Arrays.asList(miss.split("\\.")));
// StringBuilder miss2Yaml = new StringBuilder();
// int spaces = 2;
// Iterator<String> 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");
@@ -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();
}
}
@@ -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())) {
@@ -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<String> 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
*
@@ -28,9 +28,8 @@ import org.jetbrains.annotations.NotNull;
import org.maxgamer.quickshop.Util.Util;
public class DisplayItemPersistentDataType implements PersistentDataType<String, ShopProtectionFlag> {
private static Gson gson = new Gson();
static final DisplayItemPersistentDataType INSTANCE = new DisplayItemPersistentDataType();
private static Gson gson = new Gson();
@Override
public @NotNull Class<String> getPrimitiveType() {
@@ -47,7 +46,7 @@ public class DisplayItemPersistentDataType implements PersistentDataType<String,
public String toPrimitive(@NotNull ShopProtectionFlag complex, @NotNull PersistentDataAdapterContext context) {
try {
return gson.toJson(complex);
}catch (Throwable th){
} catch (Throwable th) {
new RuntimeException("Cannot to toPrimitive the shop protection flag.").printStackTrace();
return "";
}
@@ -58,7 +57,7 @@ public class DisplayItemPersistentDataType implements PersistentDataType<String,
public ShopProtectionFlag fromPrimitive(@NotNull String primitive, @NotNull PersistentDataAdapterContext context) {
try {
return gson.fromJson(primitive, ShopProtectionFlag.class);
}catch (Throwable th){
} catch (Throwable th) {
new RuntimeException("Cannot to fromPrimitive the shop protection flag.").printStackTrace();
return new ShopProtectionFlag("", Util.serialize(new ItemStack(Material.STONE)));
}
@@ -31,6 +31,12 @@ public enum DisplayType {
* */
UNKNOWN(-1), REALITEM(0), ARMORSTAND(1), VIRTUALITEM(2);
private int id;
DisplayType(int id) {
this.id = id;
}
public static @NotNull DisplayType fromID(int id) {
for (DisplayType type : DisplayType.values()) {
if (type.id == id) {
@@ -54,12 +60,6 @@ public enum DisplayType {
return UNKNOWN;
}
private int id;
DisplayType(int id) {
this.id = id;
}
public int toID() {
return id;
}
@@ -45,27 +45,10 @@ import java.util.Objects;
@ToString
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<String> 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<String> 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;
@@ -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;
}
@@ -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) {
@@ -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
*
@@ -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<Shop> shopsInDatabase = new ArrayList<>();
@Getter private List<ShopDatabaseInfoOrigin> originShopsInDatabase = new ArrayList<>();
@Getter
private List<Shop> shopsInDatabase = new ArrayList<>();
@Getter
private List<ShopDatabaseInfoOrigin> 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
}
@@ -53,19 +53,16 @@ import java.util.stream.Collectors;
@SuppressWarnings("WeakerAccess")
public class ShopManager {
private HashMap<UUID, Info> actions = new HashMap<>();
private QuickShop plugin;
private final HashMap<String, HashMap<ShopChunk, HashMap<Location, Shop>>> shops = new HashMap<>();
private HashMap<UUID, Info> actions = new HashMap<>();
private QuickShop plugin;
private Set<Shop> 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<Shop> 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<Shop> 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<Shop> getShopsInWorld(@NotNull World world) {
return getAllShops().stream().filter(shop -> Objects.equals(shop.getLocation().getWorld(), world)).collect(Collectors.toList());
}
public class ShopIterator implements Iterator<Shop> {
private Iterator<HashMap<Location, Shop>> chunks;
private Iterator<Shop> shops;
@@ -1080,33 +1108,4 @@ public class ShopManager {
return shops.next();
}
}
/**
* Get all loaded shops.
*
* @return All loaded shops.
*/
public @Nullable Set<Shop> 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<Shop> 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<Shop> getShopsInWorld(@NotNull World world) {
return getAllShops().stream().filter(shop -> Objects.equals(shop.getLocation().getWorld(), world)).collect(Collectors.toList());
}
}
@@ -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<UUID> 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
*
@@ -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;
}
@@ -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);
});
@@ -38,11 +38,11 @@ public final class Copied implements Consumer<InputStream> {
@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);
}
@@ -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);
}
@@ -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.");
}
}
@@ -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;
}
@@ -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;
}
@@ -29,6 +29,7 @@ import org.maxgamer.quickshop.PluginsIntegration.IntegrationStage;
import java.util.HashSet;
import java.util.Set;
@Getter
public class IntegrationHelper {
private Set<IntegratedPlugin> 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;
}
}
@@ -11,7 +11,7 @@ public final class LocationOf {
@NotNull
private static final Pattern PATTERN =
Pattern.compile("((?<world>[^:/]+)[:/])?(?<x>[\\-0-9.]+),(?<y>[\\-0-9.]+),(?<z>[\\-0-9.]+)(:(?<yaw>[\\-0-9.]+):(?<pitch>[\\-0-9.]+))?");
Pattern.compile("((?<world>[^:/]+)[:/])?(?<x>[\\-0-9.]+),(?<y>[\\-0-9.]+),(?<z>[\\-0-9.]+)(:(?<yaw>[\\-0-9.]+):(?<pitch>[\\-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!");
@@ -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;
@@ -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<Pattern, String> entry : bukkitToAnsi.entrySet())
message = entry.getKey().matcher(message).replaceAll(entry.getValue());
for (Entry<Pattern, String> 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<Pattern, String>();
IGNORE_CASE = "(?i)";
// Initial here for secert optimization
bukkitToAnsi = new HashMap<Pattern, String>();
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();
}
}
@@ -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();
}
}
}
}
@@ -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<String> 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<String> 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<Enchantment, Integer> 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;
}
@@ -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<String> arguments = runtimeMxBean.getInputArguments();
finalReport.append("\tInput Args: ").append(Util.list2String(arguments)).append("\n");
finalReport.append("\tVM Name: ").append(runtimeMxBean.getVmName()).append("\n");
Map<String,String> sys = runtimeMxBean.getSystemProperties();
Map<String, String> sys = runtimeMxBean.getSystemProperties();
List<String> 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<String> modules = new ArrayList<>();;
plugin.getIntegrationHelper().getIntegrations().forEach(m->modules.add(m.getName()));
List<String> 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 {
@@ -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
*
@@ -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";
}
@@ -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();
@@ -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<Chunk> futureTask);
void getChunkAt(@NotNull World world,int x,int z, @NotNull CompletableFuture<Chunk> futureTask);
void getChunkAt(@NotNull World world, @NotNull Location location, @NotNull CompletableFuture<Chunk> futureTask);
void getChunkAt(@NotNull World world, int x, int z, @NotNull CompletableFuture<Chunk> futureTask);
void getChunkAt(@NotNull World world, @NotNull Block block, @NotNull CompletableFuture<Chunk> futureTask);
}
@@ -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<Chunk> 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));
}
}
@@ -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<Chunk> futureTask) {
futureTask.complete(world.getChunkAt(x,z));
futureTask.complete(world.getChunkAt(x, z));
}
@Override
@@ -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) {
@@ -64,6 +64,7 @@ import java.util.Map.Entry;
*/
@SuppressWarnings("WeakerAccess")
public class Util {
static short tookLongTimeCostTimes;
private static EnumSet<Material> blacklist = EnumSet.noneOf(Material.class);
@Getter
private static List<String> 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) {
@@ -28,11 +28,13 @@ import java.util.Queue;
public class DisplayDupeRemoverWatcher extends BukkitRunnable {
private Queue<DisplayItem> 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);
}
}
@@ -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();
@@ -30,12 +30,13 @@ import java.util.Queue;
public class SignUpdateWatcher extends BukkitRunnable {
private QuickShop plugin;
private Queue<Shop> 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();
}
@@ -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 -> {