diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java index 68e221333..3575b65a5 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java @@ -72,12 +72,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain pluginsField.setAccessible(true); lookupNamesField.setAccessible(true); List plugins = (List) pluginsField.get(manager); - Iterator iter = plugins.iterator(); - while (iter.hasNext()) { - if (iter.next().getName().startsWith("PlotMe")) { - iter.remove(); - } - } + plugins.removeIf(plugin -> plugin.getName().startsWith("PlotMe")); Map lookupNames = (Map) lookupNamesField.get(manager); lookupNames.remove("PlotMe"); @@ -201,8 +196,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain this.methodUnloadChunk0 = classCraftWorld.getRealClass() .getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); this.methodUnloadChunk0.setAccessible(true); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); } } final PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); @@ -226,7 +221,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain if (id != null) { final Plot plot = area.getOwnedPlot(id); if (plot != null) { - if (PlotPlayer.wrap(plot.owner) == null) { + if (PlotPlayer.wrap(plot.guessOwner()) == null) { if (world.getKeepSpawnInMemory()) { world.setKeepSpawnInMemory(false); return; @@ -651,10 +646,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain @Override public boolean initPlotMeConverter() { if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) { return true; - } else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) { - return true; - } - return false; + } else + return new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017()); } @Override @Nullable public GeneratorWrapper getGenerator(@NonNull final String world, diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java index 064d77d86..d4e0ff0b0 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java @@ -26,7 +26,7 @@ public final class ArrayWrapper { * * @param elements The elements of the array. */ - public ArrayWrapper(E... elements) { + @SafeVarargs public ArrayWrapper(E... elements) { setArray(elements); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java index 6c2e838d6..95ee205dc 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java @@ -56,7 +56,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa String clickActionData = null; String hoverActionName = null; JsonRepresentedObject hoverActionData = null; - TextualComponent text = null; + TextualComponent text; String insertionData = null; ArrayList translationReplacements = new ArrayList<>(); @@ -123,8 +123,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa if (insertionData != null) { json.name("insertion").value(insertionData); } - if (translationReplacements.size() > 0 && text != null && TextualComponent - .isTranslatableText(text)) { + if (translationReplacements.size() > 0 && TextualComponent.isTranslatableText(text)) { json.name("with").beginArray(); for (JsonRepresentedObject obj : translationReplacements) { obj.writeJson(json); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java index 79c445dcc..a92515221 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java @@ -181,13 +181,13 @@ public final class Reflection { */ public synchronized static Method getMethod(Class clazz, String name, Class... args) { if (!_loadedMethods.containsKey(clazz)) { - _loadedMethods.put(clazz, new HashMap>, Method>>()); + _loadedMethods.put(clazz, new HashMap<>()); } Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); if (!loadedMethodNames.containsKey(name)) { - loadedMethodNames.put(name, new HashMap>, Method>()); + loadedMethodNames.put(name, new HashMap<>()); } Map>, Method> loadedSignatures = loadedMethodNames.get(name); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java index 14e3d2305..73c2fa477 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java @@ -207,7 +207,7 @@ public abstract class TextualComponent implements Cloneable { this.value = value; } - @Override public TextualComponent clone() throws CloneNotSupportedException { + @Override public TextualComponent clone() { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone return new ArbitraryTextTypeComponent(getKey(), getValue()); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java index 0dfcf1a18..beb291715 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java @@ -171,126 +171,114 @@ import java.util.Map.Entry; } MainUtil.sendMessage(player, "&7 - Replacing cache"); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - for (Entry entry : uCMap.entrySet()) { - String name = UUIDHandler.getName(entry.getKey()); - if (name != null) { - UUIDHandler.add(new StringWrapper(name), entry.getValue()); - } + TaskManager.runTaskAsync(() -> { + for (Entry entry : uCMap.entrySet()) { + String name = UUIDHandler.getName(entry.getKey()); + if (name != null) { + UUIDHandler.add(new StringWrapper(name), entry.getValue()); } + } - MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); - - File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); - if (file.exists()) { - try { - List lines = - Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - for (String line : lines) { - try { - line = line.trim(); - if (line.isEmpty()) { - continue; - } - line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - String[] split = line.split("\\|"); - String name = split[0]; - if (name.isEmpty() || name.length() > 16 || !StringMan - .isAlphanumericUnd(name)) { - continue; - } - UUID old = currentUUIDWrapper.getUUID(name); - if (old == null) { - continue; - } - UUID now = newWrapper.getUUID(name); - UUIDHandler.add(new StringWrapper(name), now); - uCMap.put(old, now); - uCReverse.put(now, old); - } catch (Exception e2) { - e2.printStackTrace(); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - MainUtil.sendMessage(player, "&7 - Replacing wrapper"); - UUIDHandler.setUUIDWrapper(newWrapper); - - MainUtil.sendMessage(player, "&7 - Updating plot objects"); - - for (Plot plot : PlotSquared.get().getPlots()) { - UUID value = uCMap.get(plot.owner); - if (value != null) { - plot.owner = value; - } - plot.getTrusted().clear(); - plot.getMembers().clear(); - plot.getDenied().clear(); - } - - MainUtil.sendMessage(player, "&7 - Deleting database"); - boolean result = DBFunc.deleteTables(); - - MainUtil.sendMessage(player, "&7 - Creating tables"); + MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); + File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); + if (file.exists()) { try { - DBFunc.createTables(); - if (!result) { - MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); - for (Plot plot : PlotSquared.get().getPlots()) { - UUID value = uCReverse.get(plot.owner); - if (value != null) { - plot.owner = value; + List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + for (String line : lines) { + try { + line = line.trim(); + if (line.isEmpty()) { + continue; } + line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); + String[] split = line.split("\\|"); + String name = split[0]; + if (name.isEmpty() || name.length() > 16 || !StringMan + .isAlphanumericUnd(name)) { + continue; + } + UUID old = currentUUIDWrapper.getUUID(name); + if (old == null) { + continue; + } + UUID now = newWrapper.getUUID(name); + UUIDHandler.add(new StringWrapper(name), now); + uCMap.put(old, now); + uCReverse.put(now, old); + } catch (Exception e2) { + e2.printStackTrace(); } - DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()), - new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Recovery was successful!"); - } - }); - return; } - } catch (Exception e) { + } catch (IOException e) { e.printStackTrace(); + } + } + + MainUtil.sendMessage(player, "&7 - Replacing wrapper"); + UUIDHandler.setUUIDWrapper(newWrapper); + + MainUtil.sendMessage(player, "&7 - Updating plot objects"); + + for (Plot plot : PlotSquared.get().getPlots()) { + UUID value = uCMap.get(plot.guessOwner()); + if (value != null) { + plot.setOwner(value); + } + plot.getTrusted().clear(); + plot.getMembers().clear(); + plot.getDenied().clear(); + } + + MainUtil.sendMessage(player, "&7 - Deleting database"); + boolean result = DBFunc.deleteTables(); + + MainUtil.sendMessage(player, "&7 - Creating tables"); + + try { + DBFunc.createTables(); + if (!result) { + MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); + for (Plot plot : PlotSquared.get().getPlots()) { + UUID value = uCReverse.get(plot.guessOwner()); + if (value != null) { + plot.setOwner(value); + } + } + DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()), + () -> MainUtil.sendMessage(player, "&6Recovery was successful!")); return; } - - if (newWrapper instanceof OfflineUUIDWrapper) { - PlotSquared.get().worlds.set("UUID.force-lowercase", false); - PlotSquared.get().worlds.set("UUID.offline", true); - } else if (newWrapper instanceof DefaultUUIDWrapper) { - PlotSquared.get().worlds.set("UUID.force-lowercase", false); - PlotSquared.get().worlds.set("UUID.offline", false); - } - try { - PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); - } catch (IOException ignored) { - MainUtil.sendMessage(player, - "Could not save configuration. It will need to be manual set!"); - } - - MainUtil.sendMessage(player, "&7 - Populating tables"); - - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&aConversion complete!"); - } - }); - } - }); - - MainUtil.sendMessage(player, "&aIt is now safe for players to join"); - MainUtil.sendMessage(player, - "&cConversion is still in progress, you will be notified when it is complete"); + } catch (Exception e) { + e.printStackTrace(); + return; } + + if (newWrapper instanceof OfflineUUIDWrapper) { + PlotSquared.get().worlds.set("UUID.force-lowercase", false); + PlotSquared.get().worlds.set("UUID.offline", true); + } else if (newWrapper instanceof DefaultUUIDWrapper) { + PlotSquared.get().worlds.set("UUID.force-lowercase", false); + PlotSquared.get().worlds.set("UUID.offline", false); + } + try { + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); + } catch (IOException ignored) { + MainUtil.sendMessage(player, + "Could not save configuration. It will need to be manual set!"); + } + + MainUtil.sendMessage(player, "&7 - Populating tables"); + + TaskManager.runTaskAsync(() -> { + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&aConversion complete!")); + }); + + MainUtil.sendMessage(player, "&aIt is now safe for players to join"); + MainUtil.sendMessage(player, + "&cConversion is still in progress, you will be notified when it is complete"); }); return true; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java index 929360555..4f09da499 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java @@ -66,13 +66,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector { String name = resultSet.getString("owner"); String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); if (!plots.containsKey(world)) { - plots.put(world, new HashMap()); + plots.put(world, new HashMap<>()); if (merge) { int plot = PlotSquared.get().worlds.getInt("worlds." + world + ".plot.size"); int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width"); plotWidth.put(world, plot); roadWidth.put(world, path); - merges.put(world, new HashMap()); + merges.put(world, new HashMap<>()); } } if (merge) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java index b17583107..b8301dca1 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java @@ -48,7 +48,7 @@ public class LikePlotMeConverter { private void sendMessage(String message) { PlotSquared - .debug("&3PlotMe&8->&3" + PlotSquared.imp().getPluginName() + "&8: &7" + message); + .debug("&3PlotMe&8->&3" + PlotSquared.get().IMP.getPluginName() + "&8: &7" + message); } public String getPlotMePath() { @@ -97,7 +97,7 @@ public class LikePlotMeConverter { return; } String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); - String pluginName = PlotSquared.imp().getPluginName(); + String pluginName = PlotSquared.get().IMP.getPluginName(); content = content.replace("PlotMe-DefaultGenerator", pluginName); content = content.replace("PlotMe", pluginName); content = content.replace("AthionPlots", pluginName); @@ -220,8 +220,8 @@ public class LikePlotMeConverter { for (String world : allWorlds) { copyConfig(plotmeDgYml, world); } - } catch (IOException ignored) { - ignored.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); } } for (Entry> entry : plots.entrySet()) { @@ -266,23 +266,21 @@ public class LikePlotMeConverter { sendMessage("Creating plot DB"); Thread.sleep(1000); final AtomicBoolean done = new AtomicBoolean(false); - DBFunc.createPlotsAndData(createdPlots, new Runnable() { - @Override public void run() { - if (done.get()) { - done(); - sendMessage("&aDatabase conversion is now complete!"); - PlotSquared.debug("&c - Stop the server"); - PlotSquared.debug( - "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); - PlotSquared.debug( - "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); - PlotSquared.debug("&c - Start the server"); - PlotSquared.get().setPlots(DBFunc.getPlots()); - } else { - sendMessage( - "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); - done.set(true); - } + DBFunc.createPlotsAndData(createdPlots, () -> { + if (done.get()) { + done(); + sendMessage("&aDatabase conversion is now complete!"); + PlotSquared.debug("&c - Stop the server"); + PlotSquared.debug( + "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); + PlotSquared.debug( + "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PlotSquared.debug("&c - Start the server"); + PlotSquared.get().setPlots(DBFunc.getPlots()); + } else { + sendMessage( + "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + done.set(true); } }); sendMessage("Saving configuration..."); @@ -291,93 +289,88 @@ public class LikePlotMeConverter { } catch (IOException ignored) { sendMessage(" - &cFailed to save configuration."); } - TaskManager.runTask(new Runnable() { - @Override public void run() { - try { - boolean mv = false; - boolean mw = false; - if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) - && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { - mv = true; - } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) - && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - mw = true; + TaskManager.runTask(() -> { + try { + boolean mv = false; + boolean mw = false; + if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit + .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + mv = true; + } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit + .getPluginManager().getPlugin("MultiWorld").isEnabled()) { + mw = true; + } + for (String worldName : worlds) { + World world = Bukkit.getWorld(getWorld(worldName)); + if (world == null) { + sendMessage("&cInvalid world in PlotMe configuration: " + worldName); + continue; } - for (String worldName : worlds) { - World world = Bukkit.getWorld(getWorld(worldName)); - if (world == null) { - sendMessage( - "&cInvalid world in PlotMe configuration: " + worldName); - continue; - } - String actualWorldName = world.getName(); + String actualWorldName = world.getName(); + sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); + if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName() + .equals(worldName)) { sendMessage( - "Reloading generator for world: '" + actualWorldName + "'..."); - if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName() - .equals(worldName)) { - sendMessage( - "&cYou need to stop the server to reload this world properly"); - } else { - PlotSquared.get().removePlotAreas(actualWorldName); - if (mv) { - // unload world with MV - Bukkit.getServer() - .dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mv unload " + actualWorldName); - try { - Thread.sleep(1000); - } catch (InterruptedException ignored) { - Thread.currentThread().interrupt(); - } - // load world with MV - Bukkit.getServer() - .dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mv import " + actualWorldName + " normal -g " - + PlotSquared.imp().getPluginName()); - } else if (mw) { - // unload world with MW - Bukkit.getServer() - .dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mw unload " + actualWorldName); - try { - Thread.sleep(1000); - } catch (InterruptedException ignored) { - Thread.currentThread().interrupt(); - } - // load world with MW - Bukkit.getServer() - .dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mw create " + actualWorldName + " plugin:" - + PlotSquared.imp().getPluginName()); - } else { - // Load using Bukkit API - // - User must set generator manually - Bukkit.getServer().unloadWorld(world, true); - World myWorld = WorldCreator.name(actualWorldName).generator( - new BukkitPlotGenerator( - PlotSquared.get().IMP.getDefaultGenerator())) - .createWorld(); - myWorld.save(); + "&cYou need to stop the server to reload this world properly"); + } else { + PlotSquared.get().removePlotAreas(actualWorldName); + if (mv) { + // unload world with MV + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv unload " + actualWorldName); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); } + // load world with MV + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv import " + actualWorldName + " normal -g " + PlotSquared + .get().IMP.getPluginName()); + } else if (mw) { + // unload world with MW + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw unload " + actualWorldName); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + // load world with MW + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw create " + actualWorldName + " plugin:" + PlotSquared + .get().IMP.getPluginName()); + } else { + // Load using Bukkit API + // - User must set generator manually + Bukkit.getServer().unloadWorld(world, true); + World myWorld = WorldCreator.name(actualWorldName).generator( + new BukkitPlotGenerator( + PlotSquared.get().IMP.getDefaultGenerator())).createWorld(); + myWorld.save(); } } - } catch (CommandException e) { - e.printStackTrace(); - } - if (done.get()) { - done(); - sendMessage("&aDatabase conversion is now complete!"); - PlotSquared.debug("&c - Stop the server"); - PlotSquared.debug( - "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); - PlotSquared.debug( - "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); - PlotSquared.debug("&c - Start the server"); - } else { - sendMessage( - "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); - done.set(true); } + } catch (CommandException e) { + e.printStackTrace(); + } + if (done.get()) { + done(); + sendMessage("&aDatabase conversion is now complete!"); + PlotSquared.debug("&c - Stop the server"); + PlotSquared.debug( + "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); + PlotSquared.debug( + "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PlotSquared.debug("&c - Start the server"); + } else { + sendMessage( + "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + done.set(true); } }); } catch (InterruptedException | SQLException e) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java index 0aa5afcd5..494161816 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java @@ -75,7 +75,7 @@ public class PlotMeConnector_017 extends APlotMeConnector { int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width"); plotWidth.put(world, plot); roadWidth.put(world, path); - merges.put(world, new HashMap()); + merges.put(world, new HashMap<>()); } if (merge) { int tx = resultSet.getInt("topX"); @@ -178,11 +178,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { HashMap> processed = new HashMap<>(); for (Plot plot : plots.values()) { - HashMap map = processed.get(plot.getWorldName()); - if (map == null) { - map = new HashMap<>(); - processed.put(plot.getWorldName(), map); - } + HashMap map = + processed.computeIfAbsent(plot.getWorldName(), k -> new HashMap<>()); map.put(plot.getId(), plot); } return processed; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 58a9e4692..6fc46c8b5 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -19,7 +19,10 @@ import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.Set; public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper { @@ -28,7 +31,6 @@ public class BukkitPlotGenerator extends ChunkGenerator private final IndependentPlotGenerator plotGenerator; private final ChunkGenerator platformGenerator; private final boolean full; - private final HashMap dataMap = new HashMap<>(); private List populators; private boolean loaded = false; @@ -199,9 +201,11 @@ public class BukkitPlotGenerator extends ChunkGenerator if (populators == null && platformGenerator != null) { populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world)); } - for (BlockPopulator populator : this.populators) { - if (!existing.contains(populator)) { - toAdd.add(populator); + if (this.populators != null) { + for (BlockPopulator populator : this.populators) { + if (!existing.contains(populator)) { + toAdd.add(populator); + } } } return toAdd; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java index 4fdfd28ed..37de68982 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java @@ -47,7 +47,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils this.mustSave = classChunk.getField("mustSave"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); } catch (Throwable ignored) { - PlotSquared.debug(PlotSquared.imp().getPluginName() + PlotSquared.debug(PlotSquared.get().IMP.getPluginName() + "/Server not compatible for chunk processor trim/gc"); Settings.Chunk_Processor.AUTO_TRIM = false; } @@ -58,48 +58,45 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils for (World world : Bukkit.getWorlds()) { world.setAutoSave(false); } - TaskManager.runTaskRepeat(new Runnable() { - @Override public void run() { - try { - HashSet toUnload = new HashSet<>(); - for (World world : Bukkit.getWorlds()) { - String worldName = world.getName(); - if (!PlotSquared.get().hasPlotArea(worldName)) { + TaskManager.runTaskRepeat(() -> { + try { + HashSet toUnload = new HashSet<>(); + for (World world : Bukkit.getWorlds()) { + String worldName = world.getName(); + if (!PlotSquared.get().hasPlotArea(worldName)) { + continue; + } + Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world); + Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); + Method methodIsChunkInUse = + chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class); + Chunk[] chunks = world.getLoadedChunks(); + for (Chunk chunk : chunks) { + if ((boolean) methodIsChunkInUse + .invoke(chunkMap, chunk.getX(), chunk.getZ())) { continue; } - Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world); - Object chunkMap = - w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); - Method methodIsChunkInUse = chunkMap.getClass() - .getDeclaredMethod("isChunkInUse", int.class, int.class); - Chunk[] chunks = world.getLoadedChunks(); - for (Chunk chunk : chunks) { - if ((boolean) methodIsChunkInUse - .invoke(chunkMap, chunk.getX(), chunk.getZ())) { - continue; - } - int x = chunk.getX(); - int z = chunk.getZ(); - if (!shouldSave(worldName, x, z)) { - unloadChunk(worldName, chunk, false); - continue; - } - toUnload.add(chunk); + int x = chunk.getX(); + int z = chunk.getZ(); + if (!shouldSave(worldName, x, z)) { + unloadChunk(worldName, chunk, false); + continue; } + toUnload.add(chunk); } - if (toUnload.isEmpty()) { + } + if (toUnload.isEmpty()) { + return; + } + long start = System.currentTimeMillis(); + for (Chunk chunk : toUnload) { + if (System.currentTimeMillis() - start > 5) { return; } - long start = System.currentTimeMillis(); - for (Chunk chunk : toUnload) { - if (System.currentTimeMillis() - start > 5) { - return; - } - chunk.unload(true, false); - } - } catch (Throwable e) { - e.printStackTrace(); + chunk.unload(true, false); } + } catch (Throwable e) { + e.printStackTrace(); } }, 1); } @@ -110,7 +107,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils } Object c = this.methodGetHandleChunk.of(chunk).call(); RefField.RefExecutor field = this.mustSave.of(c); - if ((Boolean) field.get() == true) { + if ((Boolean) field.get()) { field.set(false); if (chunk.isLoaded()) { ignoreUnload = true; @@ -221,9 +218,26 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils private void cleanChunk(final Chunk chunk) { TaskManager.index.incrementAndGet(); final Integer currentIndex = TaskManager.index.get(); - Integer task = TaskManager.runTaskRepeat(new Runnable() { - @Override public void run() { - if (!chunk.isLoaded()) { + Integer task = TaskManager.runTaskRepeat(() -> { + if (!chunk.isLoaded()) { + Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); + TaskManager.tasks.remove(currentIndex); + PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + chunk.unload(true, true); + return; + } + BlockState[] tiles = chunk.getTileEntities(); + if (tiles.length == 0) { + Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); + TaskManager.tasks.remove(currentIndex); + PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + chunk.unload(true, true); + return; + } + long start = System.currentTimeMillis(); + int i = 0; + while (System.currentTimeMillis() - start < 250) { + if (i >= tiles.length) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); PlotSquared @@ -231,29 +245,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils chunk.unload(true, true); return; } - BlockState[] tiles = chunk.getTileEntities(); - if (tiles.length == 0) { - Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); - TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); - chunk.unload(true, true); - return; - } - long start = System.currentTimeMillis(); - int i = 0; - while (System.currentTimeMillis() - start < 250) { - if (i >= tiles.length) { - Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); - TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); - chunk.unload(true, true); - return; - } - tiles[i].getBlock().setType(Material.AIR, false); - i++; - } + tiles[i].getBlock().setType(Material.AIR, false); + i++; } }, 5); TaskManager.tasks.put(currentIndex, task); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java index 9f787297d..3c6ee668f 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java @@ -129,7 +129,7 @@ import java.util.List; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { + public void vehicleMove(VehicleMoveEvent event) { test(event.getVehicle()); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java index bb001769c..be9d1215c 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java @@ -590,13 +590,11 @@ import java.util.regex.Pattern; // Delayed // Async - TaskManager.runTaskLaterAsync(new Runnable() { - @Override public void run() { - if (!player.hasPlayedBefore() && player.isOnline()) { - player.saveData(); - } - EventUtil.manager.doJoinTask(pp); + TaskManager.runTaskLaterAsync(() -> { + if (!player.hasPlayedBefore() && player.isOnline()) { + player.saveData(); } + EventUtil.manager.doJoinTask(pp); }, 20); } @@ -2194,7 +2192,7 @@ import java.util.regex.Pattern; MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(pp.getUUID())) { - if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket().getId(), 0))) { + if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket()))) { return; } if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { @@ -2216,9 +2214,7 @@ import java.util.regex.Pattern; } @EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { - if (TaskManager.TELEPORT_QUEUE.contains(event.getPlayer().getName())) { - TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); - } + TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); pp.unregister(); } @@ -2507,7 +2503,7 @@ import java.util.regex.Pattern; @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { - EntityDamageByEntityEvent eventChange = null; + EntityDamageByEntityEvent eventChange; eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); onEntityDamageByEntityEvent(eventChange); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java index afabd8250..f5257ca86 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -36,45 +36,43 @@ import java.util.UUID; private static final HashMap healRunnable = new HashMap<>(); public static void startRunnable(JavaPlugin plugin) { - plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override public void run() { - if (!healRunnable.isEmpty()) { - for (Iterator> iterator = - healRunnable.entrySet().iterator(); iterator.hasNext(); ) { - Entry entry = iterator.next(); - Interval value = entry.getValue(); - ++value.count; - if (value.count == value.interval) { - value.count = 0; - Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) { - iterator.remove(); - continue; - } - double level = player.getHealth(); - if (level != value.max) { - player.setHealth(Math.min(level + value.amount, value.max)); - } + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> { + if (!healRunnable.isEmpty()) { + for (Iterator> iterator = + healRunnable.entrySet().iterator(); iterator.hasNext(); ) { + Entry entry = iterator.next(); + Interval value = entry.getValue(); + ++value.count; + if (value.count == value.interval) { + value.count = 0; + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + iterator.remove(); + continue; + } + double level = player.getHealth(); + if (level != value.max) { + player.setHealth(Math.min(level + value.amount, value.max)); } } } - if (!feedRunnable.isEmpty()) { - for (Iterator> iterator = - feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { - Entry entry = iterator.next(); - Interval value = entry.getValue(); - ++value.count; - if (value.count == value.interval) { - value.count = 0; - Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) { - iterator.remove(); - continue; - } - int level = player.getFoodLevel(); - if (level != value.max) { - player.setFoodLevel(Math.min(level + value.amount, value.max)); - } + } + if (!feedRunnable.isEmpty()) { + for (Iterator> iterator = + feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { + Entry entry = iterator.next(); + Interval value = entry.getValue(); + ++value.count; + if (value.count == value.interval) { + value.count = 0; + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + iterator.remove(); + continue; + } + int level = player.getFoodLevel(); + if (level != value.max) { + player.setFoodLevel(Math.min(level + value.amount, value.max)); } } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java index 6a3e26d59..df434b237 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java @@ -33,8 +33,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils this.done = classChunk.getField("done").getRealField(); this.lit = classChunk.getField("lit").getRealField(); this.s = classChunk.getField("s").getRealField(); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); } Bukkit.getPluginManager().registerEvents(this, plugin); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java index 0903e78d9..8890dc5a0 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java @@ -10,7 +10,7 @@ public class BukkitLazyBlock extends LazyBlock { private StringPlotBlock pb; public BukkitLazyBlock(Block block) { - this.pb = (StringPlotBlock) PlotBlock.get(block.getType().toString()); + this.pb = PlotBlock.get(block.getType().toString()); } public BukkitLazyBlock(StringPlotBlock pb) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java index a97993cfc..80dd4be91 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java @@ -76,7 +76,7 @@ public class BukkitPlayer extends PlotPlayer { private void callEvent(final Event event) { RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners(); for (RegisteredListener listener : listeners) { - if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) { + if (listener.getPlugin().getName().equals(PlotSquared.get().IMP.getPluginName())) { continue; } try { @@ -143,7 +143,7 @@ public class BukkitPlayer extends PlotPlayer { } @Override public void sendMessage(String message) { - if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( + if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { setMeta("lastMessage", message); setMeta("lastMessageTime", System.currentTimeMillis()); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java index e71373771..58622c2d0 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java @@ -38,7 +38,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { if (depth == 0) { return; } - Entity passenger = entity.getPassenger(); + Entity passenger = entity.getPassengers().get(0); if (passenger != null) { this.base.passenger = new ReplicatingEntityWrapper(passenger, depth); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java index 28a6c4e29..408345fb7 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java @@ -101,9 +101,7 @@ public class BukkitChunkManager extends ChunkManager { Set chunks = super.getChunkChunks(world); for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); - if (!chunks.contains(loc)) { - chunks.add(loc); - } + chunks.add(loc); } return chunks; } @@ -115,10 +113,6 @@ public class BukkitChunkManager extends ChunkManager { final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - com.github.intellectualsites.plotsquared.plot.object.Location pos4 = - new com.github.intellectualsites.plotsquared.plot.object.Location(newPos.getWorld(), - newPos.getX() + relX, 256, newPos.getZ() + relZ); - final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); final World oldWorld = Bukkit.getWorld(pos1.getWorld()); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java index 6beebcd95..5d9e1d9c6 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -85,7 +85,6 @@ public class BukkitInventoryUtil extends InventoryUtil { } // int id = item.getTypeId(); Material id = item.getType(); - short data = item.getDurability(); int amount = item.getAmount(); String name = null; String[] lore = null; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java index efdb034cd..c1449709a 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -208,8 +208,6 @@ public class BukkitSetupUtils extends SetupUtils { return world; } } - World bw = - Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL)); } return object.world; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java index dcee95c67..1d3aee600 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java @@ -215,7 +215,7 @@ import java.util.*; public static List getEntities(@NonNull final String worldName) { World world = getWorld(worldName); - return world != null ? world.getEntities() : new ArrayList(); + return world != null ? world.getEntities() : new ArrayList<>(); } public static Location getLocation(@NonNull final Entity entity) { @@ -233,7 +233,7 @@ import java.util.*; } public static BukkitLegacyMappings getBukkitLegacyMappings() { - return (BukkitLegacyMappings) PlotSquared.imp().getLegacyMappings(); + return (BukkitLegacyMappings) PlotSquared.get().IMP.getLegacyMappings(); } public static Material getMaterial(@NonNull final PlotBlock plotBlock) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java index ffc69edfc..f2b481e4c 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java @@ -117,7 +117,7 @@ public class NbtFactory { * * @return The NBT list. */ - public static NbtList createList(Iterable iterable) { + public static NbtList createList(Iterable iterable) { NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); // Add the content as well @@ -951,8 +951,7 @@ public class NbtFactory { @Override public Entry next() { Entry entry = proxy.next(); - return new SimpleEntry(entry.getKey(), - wrapOutgoing(entry.getValue())); + return new SimpleEntry<>(entry.getKey(), wrapOutgoing(entry.getValue())); } @Override public void remove() { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java index f0987b219..cecea15ff 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java @@ -65,11 +65,7 @@ public class SendChunk { int view = Bukkit.getServer().getViewDistance(); for (Chunk chunk : chunks) { String world = chunk.getWorld().getName(); - ArrayList list = map.get(world); - if (list == null) { - list = new ArrayList<>(); - map.put(world, list); - } + ArrayList list = map.computeIfAbsent(world, k -> new ArrayList<>()); list.add(chunk); Object c = this.methodGetHandleChunk.of(chunk).call(); this.methodInitLighting.of(c).call(); @@ -118,20 +114,17 @@ public class SendChunk { } } for (final Chunk chunk : chunks) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - try { - chunk.unload(true, false); - } catch (Throwable ignored) { - String worldName = chunk.getWorld().getName(); - PlotSquared.debug( - "$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" - + chunk.getZ()); - PlotSquared - .debug("$3 - $4File may be open in another process (e.g. MCEdit)"); - PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName - + "/level_old.dat may be corrupt (try repairing or removing these)"); - } + TaskManager.runTask(() -> { + try { + chunk.unload(true, false); + } catch (Throwable ignored) { + String worldName = chunk.getWorld().getName(); + PlotSquared.debug( + "$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk + .getZ()); + PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); + PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName + + "/level_old.dat may be corrupt (try repairing or removing these)"); } }); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java index 110635f2d..45814d639 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java @@ -5,12 +5,10 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import org.bukkit.World; -import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Iterator; public class SetGenCB { @@ -45,12 +43,8 @@ public class SetGenCB { } } if (!set) { - Iterator iterator = world.getPopulators().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof BukkitAugmentedGenerator) { - iterator.remove(); - } - } + world.getPopulators() + .removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator); } PlotSquared.get() .loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null)); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java index 32f0c09b3..2dc2daa6a 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java @@ -189,11 +189,11 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { for (int x = 0; x < lc.biomes.length; x++) { String[] biomes2 = lc.biomes[x]; if (biomes2 != null) { - for (int y = 0; y < biomes2.length; y++) { - String biomeStr = biomes2[y]; + for (String biomeStr : biomes2) { if (biomeStr != null) { if (last == null || !StringMan.isEqual(last, biomeStr)) { biome = Biome.valueOf(biomeStr.toUpperCase()); + last = biomeStr; } worldObj.setBiome(bx, bz, biome); } @@ -244,8 +244,8 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { if (disableResult != null) { try { fieldNeighbors.set(disableResult[0], disableResult[1]); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); } } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java index 2223feceb..42a83f466 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -47,204 +47,196 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } else { world = worlds.get(0).getName(); } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world); - File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); - if (uuidFile.exists()) { - try { - List lines = - Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8); - for (String line : lines) { - try { - line = line.trim(); - if (line.isEmpty()) { - continue; - } - line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - String[] split = line.split("\\|"); - String name = split[0]; - if (name.isEmpty() || (name.length() > 16) || !StringMan - .isAlphanumericUnd(name)) { - continue; - } - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); - if (uuid == null) { - continue; - } - UUIDHandler.add(new StringWrapper(name), uuid); - } catch (Exception e2) { - e2.printStackTrace(); + TaskManager.runTaskAsync(() -> { + PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world); + File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); + if (uuidFile.exists()) { + try { + List lines = + Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8); + for (String line : lines) { + try { + line = line.trim(); + if (line.isEmpty()) { + continue; } + line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); + String[] split = line.split("\\|"); + String name = split[0]; + if (name.isEmpty() || (name.length() > 16) || !StringMan + .isAlphanumericUnd(name)) { + continue; + } + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + if (uuid == null) { + continue; + } + UUIDHandler.add(new StringWrapper(name), uuid); + } catch (Exception e2) { + e2.printStackTrace(); } - } catch (IOException e) { - e.printStackTrace(); } + } catch (IOException e) { + e.printStackTrace(); } - HashBiMap toAdd = - HashBiMap.create(new HashMap()); - if (Settings.UUID.NATIVE_UUID_PROVIDER) { - HashSet all = UUIDHandler.getAllUUIDS(); - PlotSquared.debug("&aFast mode UUID caching enabled!"); - File playerDataFolder = - new File(container, world + File.separator + "playerdata"); - String[] dat = playerDataFolder.list(new DatFileFilter()); - boolean check = all.isEmpty(); - if (dat != null) { - for (String current : dat) { - String s = current.replaceAll(".dat$", ""); - try { - UUID uuid = UUID.fromString(s); - if (check || all.remove(uuid)) { - File file = new File(playerDataFolder, current); - NbtFactory.NbtCompound compound = NbtFactory - .fromStream(new FileInputStream(file), - NbtFactory.StreamOptions.GZIP_COMPRESSION); - if (!compound.containsKey("bukkit")) { - PlotSquared.debug("ERROR: Player data (" + uuid.toString() - + ".dat) does not contain the the key \"bukkit\""); - } else { - NbtFactory.NbtCompound bukkit = - (NbtFactory.NbtCompound) compound.get("bukkit"); - String name = (String) bukkit.get("lastKnownName"); - long last = (long) bukkit.get("lastPlayed"); - long first = (long) bukkit.get("firstPlayed"); - if (ExpireManager.IMP != null) { - ExpireManager.IMP.storeDate(uuid, last); - ExpireManager.IMP.storeAccountAge(uuid, last - first); - } - toAdd.put(new StringWrapper(name), uuid); + } + HashBiMap toAdd = HashBiMap.create(new HashMap<>()); + if (Settings.UUID.NATIVE_UUID_PROVIDER) { + HashSet all = UUIDHandler.getAllUUIDS(); + PlotSquared.debug("&aFast mode UUID caching enabled!"); + File playerDataFolder = new File(container, world + File.separator + "playerdata"); + String[] dat = playerDataFolder.list(new DatFileFilter()); + boolean check = all.isEmpty(); + if (dat != null) { + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); + try { + UUID uuid = UUID.fromString(s); + if (check || all.remove(uuid)) { + File file = new File(playerDataFolder, current); + NbtFactory.NbtCompound compound = NbtFactory + .fromStream(new FileInputStream(file), + NbtFactory.StreamOptions.GZIP_COMPRESSION); + if (!compound.containsKey("bukkit")) { + PlotSquared.debug("ERROR: Player data (" + uuid.toString() + + ".dat) does not contain the the key \"bukkit\""); + } else { + NbtFactory.NbtCompound bukkit = + (NbtFactory.NbtCompound) compound.get("bukkit"); + String name = (String) bukkit.get("lastKnownName"); + long last = (long) bukkit.get("lastPlayed"); + long first = (long) bukkit.get("firstPlayed"); + if (ExpireManager.IMP != null) { + ExpireManager.IMP.storeDate(uuid, last); + ExpireManager.IMP.storeAccountAge(uuid, last - first); } - } - } catch (Exception e) { - e.printStackTrace(); - PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current); - } - } - } - add(toAdd); - if (all.isEmpty()) { - if (whenDone != null) { - whenDone.run(); - } - return; - } else { - PlotSquared.debug("Failed to cache: " + all.size() - + " uuids - slowly processing all files"); - } - } - HashSet worlds = Sets.newHashSet(world, "world"); - HashSet uuids = new HashSet<>(); - HashSet names = new HashSet<>(); - File playerDataFolder = null; - for (String worldName : worlds) { - // Getting UUIDs - playerDataFolder = - new File(container, worldName + File.separator + "playerdata"); - String[] dat = playerDataFolder.list(new DatFileFilter()); - if ((dat != null) && (dat.length != 0)) { - for (String current : dat) { - String s = current.replaceAll(".dat$", ""); - try { - UUID uuid = UUID.fromString(s); - uuids.add(uuid); - } catch (Exception ignored) { - PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current); - } - } - break; - } - // Getting names - File playersFolder = new File(worldName + File.separator + "players"); - dat = playersFolder.list(new DatFileFilter()); - if ((dat != null) && (dat.length != 0)) { - for (String current : dat) { - names.add(current.replaceAll(".dat$", "")); - } - break; - } - } - for (UUID uuid : uuids) { - try { - File file = - new File(playerDataFolder + File.separator + uuid.toString() + ".dat"); - if (!file.exists()) { - continue; - } - NbtFactory.NbtCompound compound = NbtFactory - .fromStream(new FileInputStream(file), - NbtFactory.StreamOptions.GZIP_COMPRESSION); - if (!compound.containsKey("bukkit")) { - PlotSquared.debug("ERROR: Player data (" + uuid.toString() - + ".dat) does not contain the the key \"bukkit\""); - } else { - NbtFactory.NbtCompound bukkit = - (NbtFactory.NbtCompound) compound.get("bukkit"); - String name = (String) bukkit.get("lastKnownName"); - StringWrapper wrap = new StringWrapper(name); - if (!toAdd.containsKey(wrap)) { - long last = (long) bukkit.get("lastPlayed"); - long first = (long) bukkit.get("firstPlayed"); - if (Settings.UUID.OFFLINE) { - if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase() - .equals(name)) { - uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); - } else { - long most = (long) compound.get("UUIDMost"); - long least = (long) compound.get("UUIDLeast"); - uuid = new UUID(most, least); - } - } - if (ExpireManager.IMP != null) { - ExpireManager.IMP.storeDate(uuid, last); - ExpireManager.IMP.storeAccountAge(uuid, last - first); - } - toAdd.put(wrap, uuid); - } - } - } catch (Exception ignored) { - PlotSquared - .debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat"); - } - } - for (String name : names) { - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); - StringWrapper nameWrap = new StringWrapper(name); - toAdd.put(nameWrap, uuid); - } - - if (getUUIDMap().isEmpty()) { - for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper - .getOfflinePlayers()) { - long last = op.getLastPlayed(); - if (last != 0) { - String name = op.getName(); - StringWrapper wrap = new StringWrapper(name); - if (!toAdd.containsKey(wrap)) { - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op); - toAdd.put(wrap, uuid); - if (ExpireManager.IMP != null) { - ExpireManager.IMP.storeDate(uuid, last); + toAdd.put(new StringWrapper(name), uuid); } } + } catch (Exception e) { + e.printStackTrace(); + PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current); } } } add(toAdd); - if (whenDone != null) { - whenDone.run(); + if (all.isEmpty()) { + if (whenDone != null) { + whenDone.run(); + } + return; + } else { + PlotSquared.debug( + "Failed to cache: " + all.size() + " uuids - slowly processing all files"); } } + HashSet worlds1 = Sets.newHashSet(world, "world"); + HashSet uuids = new HashSet<>(); + HashSet names = new HashSet<>(); + File playerDataFolder = null; + for (String worldName : worlds1) { + // Getting UUIDs + playerDataFolder = new File(container, worldName + File.separator + "playerdata"); + String[] dat = playerDataFolder.list(new DatFileFilter()); + if ((dat != null) && (dat.length != 0)) { + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); + try { + UUID uuid = UUID.fromString(s); + uuids.add(uuid); + } catch (Exception ignored) { + PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current); + } + } + break; + } + // Getting names + File playersFolder = new File(worldName + File.separator + "players"); + dat = playersFolder.list(new DatFileFilter()); + if ((dat != null) && (dat.length != 0)) { + for (String current : dat) { + names.add(current.replaceAll(".dat$", "")); + } + break; + } + } + for (UUID uuid : uuids) { + try { + File file = + new File(playerDataFolder + File.separator + uuid.toString() + ".dat"); + if (!file.exists()) { + continue; + } + NbtFactory.NbtCompound compound = NbtFactory + .fromStream(new FileInputStream(file), + NbtFactory.StreamOptions.GZIP_COMPRESSION); + if (!compound.containsKey("bukkit")) { + PlotSquared.debug("ERROR: Player data (" + uuid.toString() + + ".dat) does not contain the the key \"bukkit\""); + } else { + NbtFactory.NbtCompound bukkit = + (NbtFactory.NbtCompound) compound.get("bukkit"); + String name = (String) bukkit.get("lastKnownName"); + StringWrapper wrap = new StringWrapper(name); + if (!toAdd.containsKey(wrap)) { + long last = (long) bukkit.get("lastPlayed"); + long first = (long) bukkit.get("firstPlayed"); + if (Settings.UUID.OFFLINE) { + if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase() + .equals(name)) { + uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + } else { + long most = (long) compound.get("UUIDMost"); + long least = (long) compound.get("UUIDLeast"); + uuid = new UUID(most, least); + } + } + if (ExpireManager.IMP != null) { + ExpireManager.IMP.storeDate(uuid, last); + ExpireManager.IMP.storeAccountAge(uuid, last - first); + } + toAdd.put(wrap, uuid); + } + } + } catch (Exception ignored) { + PlotSquared + .debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat"); + } + } + for (String name : names) { + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + StringWrapper nameWrap = new StringWrapper(name); + toAdd.put(nameWrap, uuid); + } + + if (getUUIDMap().isEmpty()) { + for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { + long last = op.getLastPlayed(); + if (last != 0) { + String name = op.getName(); + StringWrapper wrap = new StringWrapper(name); + if (!toAdd.containsKey(wrap)) { + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op); + toAdd.put(wrap, uuid); + if (ExpireManager.IMP != null) { + ExpireManager.IMP.storeDate(uuid, last); + } + } + } + } + } + add(toAdd); + if (whenDone != null) { + whenDone.run(); + } }); return true; } @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); - TaskManager.runTask(ifFetch); - } + TaskManager.runTaskAsync(() -> { + ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); + TaskManager.runTask(ifFetch); }); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java index 1c9a30bba..e0bcaf0a9 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -34,7 +34,6 @@ import java.util.UUID; public class SQLUUIDHandler extends UUIDHandlerImplementation { - final int MAX_REQUESTS = 500; private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; private final int INTERVAL = 12000; @@ -71,96 +70,81 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { if (!super.startCaching(whenDone)) { return false; } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try { - HashBiMap toAdd = - HashBiMap.create(new HashMap()); - try (PreparedStatement statement = getConnection() - .prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); - ResultSet resultSet = statement.executeQuery()) { - while (resultSet.next()) { - StringWrapper username = - new StringWrapper(resultSet.getString("username")); - UUID uuid = UUID.fromString(resultSet.getString("uuid")); - toAdd.put(new StringWrapper(username.value), uuid); - } + TaskManager.runTaskAsync(() -> { + try { + HashBiMap toAdd = HashBiMap.create(new HashMap<>()); + try (PreparedStatement statement = getConnection() + .prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); + ResultSet resultSet = statement.executeQuery()) { + while (resultSet.next()) { + StringWrapper username = new StringWrapper(resultSet.getString("username")); + UUID uuid = UUID.fromString(resultSet.getString("uuid")); + toAdd.put(new StringWrapper(username.value), uuid); } - add(toAdd); - // This should be called as long as there are some unknown plots - final ArrayDeque toFetch = new ArrayDeque<>(); - for (UUID u : UUIDHandler.getAllUUIDS()) { - if (!uuidExists(u)) { - toFetch.add(u); - } + } + add(toAdd); + // This should be called as long as there are some unknown plots + final ArrayDeque toFetch = new ArrayDeque<>(); + for (UUID u : UUIDHandler.getAllUUIDS()) { + if (!uuidExists(u)) { + toFetch.add(u); } - if (toFetch.isEmpty()) { + } + if (toFetch.isEmpty()) { + if (whenDone != null) { + whenDone.run(); + } + return; + } + FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); + fileHandler.startCaching(() -> { + // If the file based UUID handler didn't cache it, then we can't cache offline mode + // Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does + if (Settings.UUID.OFFLINE) { if (whenDone != null) { whenDone.run(); } return; } - FileUUIDHandler fileHandler = - new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); - fileHandler.startCaching(new Runnable() { - @Override public void run() { - // If the file based UUID handler didn't cache it, then we can't cache offline mode - // Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does - if (Settings.UUID.OFFLINE) { - if (whenDone != null) { - whenDone.run(); - } - return; - } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - while (!toFetch.isEmpty()) { - try { - for (int i = 0; - i < Math.min(500, toFetch.size()); i++) { - UUID uuid = toFetch.pop(); - HttpURLConnection connection = - (HttpURLConnection) new URL( - SQLUUIDHandler.this.PROFILE_URL + uuid - .toString().replace("-", "")) - .openConnection(); - try (InputStream con = connection - .getInputStream()) { - InputStreamReader reader = - new InputStreamReader(con); - JSONObject response = - (JSONObject) SQLUUIDHandler.this.jsonParser - .parse(reader); - String name = (String) response.get("name"); - if (name != null) { - add(new StringWrapper(name), uuid); - } - } - connection.disconnect(); - } - } catch (IOException | ParseException e) { - PlotSquared.debug( - "Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); - } - try { - Thread.sleep(INTERVAL * 50); - } catch (InterruptedException e) { - e.printStackTrace(); - break; + TaskManager.runTaskAsync(() -> { + while (!toFetch.isEmpty()) { + try { + for (int i = 0; i < Math.min(500, toFetch.size()); i++) { + UUID uuid = toFetch.pop(); + HttpURLConnection connection = (HttpURLConnection) new URL( + SQLUUIDHandler.this.PROFILE_URL + uuid.toString() + .replace("-", "")).openConnection(); + try (InputStream con = connection.getInputStream()) { + InputStreamReader reader = new InputStreamReader(con); + JSONObject response = + (JSONObject) SQLUUIDHandler.this.jsonParser + .parse(reader); + String name = (String) response.get("name"); + if (name != null) { + add(new StringWrapper(name), uuid); } } - if (whenDone != null) { - whenDone.run(); - } - return; + connection.disconnect(); } - }); + } catch (IOException | ParseException e) { + PlotSquared.debug( + "Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); + } + try { + Thread.sleep(INTERVAL * 50); + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } + } + if (whenDone != null) { + whenDone.run(); } }); - } catch (SQLException e) { - throw new SQLUUIDHandlerException("Couldn't select :s", e); - } + }); + } catch (SQLException e) { + throw new SQLUUIDHandlerException("Couldn't select :s", e); } }); return true; @@ -172,34 +156,32 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { if (ifFetch == null) { return; } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try { - URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - String body = JSONArray.toJSONString(Collections.singletonList(name)); - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser - .parse(new InputStreamReader(connection.getInputStream())); - JSONObject jsonProfile = (JSONObject) array.get(0); - String id = (String) jsonProfile.get("id"); - String name = (String) jsonProfile.get("name"); - ifFetch.value = UUID.fromString( - id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) - + '-' + id.substring(16, 20) + '-' + id.substring(20, 32)); - } catch (IOException | ParseException e) { - e.printStackTrace(); - } - TaskManager.runTask(ifFetch); + TaskManager.runTaskAsync(() -> { + try { + URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + String body = JSONArray.toJSONString(Collections.singletonList(name)); + OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser + .parse(new InputStreamReader(connection.getInputStream())); + JSONObject jsonProfile = (JSONObject) array.get(0); + String id = (String) jsonProfile.get("id"); + String name1 = (String) jsonProfile.get("name"); + ifFetch.value = UUID.fromString( + id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + + '-' + id.substring(16, 20) + '-' + id.substring(20, 32)); + } catch (IOException | ParseException e) { + e.printStackTrace(); } + TaskManager.runTask(ifFetch); }); } @@ -215,18 +197,15 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { @Override public boolean add(final StringWrapper name, final UUID uuid) { // Ignoring duplicates if (super.add(name, uuid)) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try (PreparedStatement statement = getConnection().prepareStatement( - "REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { - statement.setString(1, uuid.toString()); - statement.setString(2, name.toString()); - statement.execute(); - PlotSquared - .debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); - } catch (SQLException e) { - e.printStackTrace(); - } + TaskManager.runTaskAsync(() -> { + try (PreparedStatement statement = getConnection() + .prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { + statement.setString(1, uuid.toString()); + statement.setString(2, name.toString()); + statement.execute(); + PlotSquared.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); + } catch (SQLException e) { + e.printStackTrace(); } }); return true; @@ -239,18 +218,16 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { */ @Override public void rename(final UUID uuid, final StringWrapper name) { super.rename(uuid, name); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try (PreparedStatement statement = getConnection() - .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { - statement.setString(1, name.value); - statement.setString(2, uuid.toString()); - statement.execute(); - PlotSquared.debug( - C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); - } catch (SQLException e) { - e.printStackTrace(); - } + TaskManager.runTaskAsync(() -> { + try (PreparedStatement statement = getConnection() + .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { + statement.setString(1, name.value); + statement.setString(2, uuid.toString()); + statement.execute(); + PlotSquared + .debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); + } catch (SQLException e) { + e.printStackTrace(); } }); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java index 6bac09a26..730ecba5b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java @@ -10,7 +10,10 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.io.IOException; import java.lang.annotation.Annotation; @@ -47,7 +50,7 @@ public abstract class Command { this.perm = perm; this.required = required; this.category = cat; - this.aliases = Arrays.asList(id); + this.aliases = Collections.singletonList(id); if (this.parent != null) { this.parent.register(this); } @@ -114,12 +117,7 @@ public abstract class Command { public List getCommands(CommandCategory cat, PlotPlayer player) { List commands = getCommands(player); if (cat != null) { - Iterator iterator = commands.iterator(); - while (iterator.hasNext()) { - if (iterator.next().category != cat) { - iterator.remove(); - } - } + commands.removeIf(command -> command.category != cat); } return commands; } @@ -249,8 +247,7 @@ public abstract class Command { } if (page == 0 && totalPages != 0) { // Next new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1") - .command(baseCommand + " " + (0 + 2)).text(C.CLICKABLE.s()).color("$2") - .send(player); + .command(baseCommand + " " + 2).text(C.CLICKABLE.s()).color("$2").send(player); return; } if (page == totalPages && totalPages != 0) { // Back @@ -276,7 +273,7 @@ public abstract class Command { } return; } - if (this.allCommands == null || this.allCommands.isEmpty()) { + if (this.allCommands.isEmpty()) { player.sendMessage( "Not Implemented: https://github.com/IntellectualSites/PlotSquared/issues/new"); return; @@ -289,13 +286,10 @@ public abstract class Command { } // Help command try { - if (args.length == 0 || MathMan.isInteger(args[0]) - || CommandCategory.valueOf(args[0].toUpperCase()) != null) { - // This will default certain syntax to the help command - // e.g. /plot, /plot 1, /plot claiming - MainCommand.getInstance().help.execute(player, args, null, null); - return; - } + // This will default certain syntax to the help command + // e.g. /plot, /plot 1, /plot claiming + MainCommand.getInstance().help.execute(player, args, null, null); + return; } catch (IllegalArgumentException ignored) { } // Command recommendation @@ -341,7 +335,6 @@ public abstract class Command { boolean failed = args.length < reqArgs.length; String[] baseSplit = getCommandString().split(" "); String[] fullSplit = getUsage().split(" "); - String base = getCommandString(); if (fullSplit.length - baseSplit.length < reqArgs.length) { String[] tmp = new String[baseSplit.length + reqArgs.length]; System.arraycopy(fullSplit, 0, tmp, 0, fullSplit.length); @@ -457,7 +450,6 @@ public abstract class Command { } public String getCommandString() { - String base; if (this.parent == null) { return "/" + toString(); } else { @@ -490,7 +482,7 @@ public abstract class Command { return null; } List result = new ArrayList<>(); - int index = input.length - (space ? 0 : 1); + int index = input.length; for (String arg : args) { arg = arg.replace(getCommandString() + " ", ""); String[] split = arg.split(" "); @@ -519,7 +511,7 @@ public abstract class Command { return null; } } else { - Set commands = new HashSet(); + Set commands = new HashSet<>(); for (Map.Entry entry : this.staticCommands.entrySet()) { if (entry.getKey().startsWith(arg) && entry.getValue() .canExecute(player, false)) { @@ -566,7 +558,7 @@ public abstract class Command { } } - public T check(T object, C message, Object... args) { + public T check(T object, C message, Object... args) { if (object == null) { throw new CommandException(message, args); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java index d8c41c3da..1e694f05a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java @@ -83,7 +83,7 @@ public class YamlConfiguration extends FileConfiguration { Map input; try { - input = (Map) yaml.load(contents); + input = yaml.load(contents); } catch (YAMLException e) { throw new InvalidConfigurationException(e); } catch (ClassCastException ignored) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java index 62ecfad3f..dccf3d755 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java @@ -48,8 +48,7 @@ import java.util.zip.ZipInputStream; * An implementation of the core, with a static getter for easy access. */ @SuppressWarnings({"unused", "WeakerAccess"}) public class PlotSquared { - private static final Set EMPTY_SET = - Collections.unmodifiableSet(Collections.emptySet()); + private static final Set EMPTY_SET = Collections.unmodifiableSet(Collections.emptySet()); private static PlotSquared instance; // Implementation public final IPlotMain IMP; @@ -216,26 +215,16 @@ import java.util.zip.ZipInputStream; } // Economy if (Settings.Enabled_Components.ECONOMY) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler(); - } - }); + TaskManager + .runTask(() -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler()); } // Check for updates if (Settings.Enabled_Components.UPDATER) { updater = new Updater(); - TaskManager.IMP.taskAsync(new Runnable() { - @Override public void run() { - updater.update(getPlatform(), getVersion()); - } - }); - TaskManager.IMP.taskRepeatAsync(new Runnable() { - @Override public void run() { - updater.update(getPlatform(), getVersion()); - } - }, 36000); + TaskManager.IMP.taskAsync(() -> updater.update(getPlatform(), getVersion())); + TaskManager.IMP + .taskRepeatAsync(() -> updater.update(getPlatform(), getVersion()), 36000); } // World generators: @@ -249,21 +238,20 @@ import java.util.zip.ZipInputStream; this.IMP.setGenerator(world); } } - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - for (String world : section.getKeys(false)) { - if (world.equals("CheckingPlotSquaredGenerator")) { - continue; - } - if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { - debug("&c`" + world + "` was not properly loaded - " + IMP - .getPluginName() + " will now try to load it properly: "); - debug( - "&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); - debug( - "&8 - &7Your world management plugin may be faulty (or non existent)"); - PlotSquared.this.IMP.setGenerator(world); - } + TaskManager.runTaskLater(() -> { + for (String world : section.getKeys(false)) { + if (world.equals("CheckingPlotSquaredGenerator")) { + continue; + } + if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { + debug( + "&c`" + world + "` was not properly loaded - " + IMP.getPluginName() + + " will now try to load it properly: "); + debug( + "&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); + debug( + "&8 - &7Your world management plugin may be faulty (or non existent)"); + PlotSquared.this.IMP.setGenerator(world); } } }, 1); @@ -338,26 +326,22 @@ import java.util.zip.ZipInputStream; } private void startUuidCatching() { - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - debug("Starting UUID caching"); - UUIDHandler.startCaching(new Runnable() { - @Override public void run() { - UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); - foreachPlotRaw(new RunnableVal() { - @Override public void run(Plot plot) { - if (plot.hasOwner() && plot.temp != -1) { - if (UUIDHandler.getName(plot.owner) == null) { - UUIDHandler.implementation.unknown.add(plot.owner); - } - } + TaskManager.runTaskLater(() -> { + debug("Starting UUID caching"); + UUIDHandler.startCaching(() -> { + UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); + foreachPlotRaw(new RunnableVal() { + @Override public void run(Plot plot) { + if (plot.hasOwner() && plot.temp != -1) { + if (UUIDHandler.getName(plot.guessOwner()) == null) { + UUIDHandler.implementation.unknown.add(plot.guessOwner()); } - }); - startExpiryTasks(); - startPlotMeConversion(); + } } }); - } + startExpiryTasks(); + startPlotMeConversion(); + }); }, 20); } @@ -374,22 +358,19 @@ import java.util.zip.ZipInputStream; private void startPlotMeConversion() { if (Settings.Enabled_Components.PLOTME_CONVERTER || Settings.PlotMe.CACHE_UUDS) { - TaskManager.IMP.taskAsync(new Runnable() { - @Override public void run() { - if (PlotSquared.this.IMP.initPlotMeConverter()) { - PlotSquared.log("&c=== IMPORTANT ==="); - PlotSquared.log( - "&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); - PlotSquared - .log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); - PlotSquared.log( - "&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); - PlotSquared.log( - "&c - After the conversion is finished, please set 'plotme-converter' to false in the " - + "'settings.yml'"); - } - Settings.Enabled_Components.PLOTME_CONVERTER = false; + TaskManager.IMP.taskAsync(() -> { + if (PlotSquared.this.IMP.initPlotMeConverter()) { + PlotSquared.log("&c=== IMPORTANT ==="); + PlotSquared.log( + "&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); + PlotSquared.log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); + PlotSquared.log( + "&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); + PlotSquared.log( + "&c - After the conversion is finished, please set 'plotme-converter' to false in the " + + "'settings.yml'"); } + Settings.Enabled_Components.PLOTME_CONVERTER = false; }); } } @@ -514,11 +495,8 @@ import java.util.zip.ZipInputStream; if (this.plots_tmp == null) { this.plots_tmp = new HashMap<>(); } - HashMap map = this.plots_tmp.get(area.toString()); - if (map == null) { - map = new HashMap<>(); - this.plots_tmp.put(area.toString(), map); - } + HashMap map = + this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>()); for (Plot plot : area.getPlots()) { map.put(plot.getId(), plot); } @@ -586,11 +564,7 @@ import java.util.zip.ZipInputStream; result.add(plot); } } - Collections.sort(overflow, new Comparator() { - @Override public int compare(Plot a, Plot b) { - return a.hashCode() - b.hashCode(); - } - }); + overflow.sort(Comparator.comparingInt(Plot::hashCode)); result.addAll(overflow); return result; } @@ -646,9 +620,7 @@ import java.util.zip.ZipInputStream; } } Collections.addAll(result, overflowArray); - for (Plot plot : extra) { - result.add(plot); - } + result.addAll(extra); return result; } @@ -727,9 +699,7 @@ import java.util.zip.ZipInputStream; } } Collections.addAll(result, overflowArray); - for (Plot plot : extra) { - result.add(plot); - } + result.addAll(extra); return result; } @@ -748,12 +718,7 @@ import java.util.zip.ZipInputStream; } else { list = new ArrayList<>(input); } - Collections.sort(list, new Comparator() { - @Override public int compare(Plot a, Plot b) { - return Long.compare(ExpireManager.IMP.getTimestamp(a.owner), - ExpireManager.IMP.getTimestamp(b.owner)); - } - }); + list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.guessOwner()))); return list; } @@ -779,7 +744,7 @@ import java.util.zip.ZipInputStream; } } else { for (PlotArea area : plotAreaManager.getAllPlotAreas()) { - map.put(area, new ArrayList(0)); + map.put(area, new ArrayList<>(0)); } Collection lastList = null; PlotArea lastWorld = null; @@ -794,17 +759,15 @@ import java.util.zip.ZipInputStream; } } List areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); - Collections.sort(areas, new Comparator() { - @Override public int compare(PlotArea a, PlotArea b) { - if (priorityArea != null) { - if (a.equals(priorityArea)) { - return -1; - } else if (b.equals(priorityArea)) { - return 1; - } + areas.sort((a, b) -> { + if (priorityArea != null) { + if (a.equals(priorityArea)) { + return -1; + } else if (b.equals(priorityArea)) { + return 1; } - return a.hashCode() - b.hashCode(); } + return a.hashCode() - b.hashCode(); }); ArrayList toReturn = new ArrayList<>(plots.size()); for (PlotArea area : areas) { @@ -883,11 +846,8 @@ import java.util.zip.ZipInputStream; String world = entry.getKey(); PlotArea area = getPlotArea(world, null); if (area == null) { - HashMap map = this.plots_tmp.get(world); - if (map == null) { - map = new HashMap<>(); - this.plots_tmp.put(world, map); - } + HashMap map = + this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>()); map.putAll(entry.getValue()); } else { for (Plot plot : entry.getValue().values()) { @@ -1202,9 +1162,8 @@ import java.util.zip.ZipInputStream; PlotSquared.log(C.PREFIX + "&aDetected world load for '" + world + "'"); String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName()); if (type == 2) { - Set clusters = this.clusters_tmp != null ? - this.clusters_tmp.get(world) : - new HashSet(); + Set clusters = + this.clusters_tmp != null ? this.clusters_tmp.get(world) : new HashSet<>(); if (clusters == null) { throw new IllegalArgumentException("No cluster exists for world: " + world); } @@ -1613,8 +1572,8 @@ import java.util.zip.ZipInputStream; // Close the connection DBFunc.close(); UUIDHandler.handleShutdown(); - } catch (NullPointerException ignored) { - ignored.printStackTrace(); + } catch (NullPointerException e) { + e.printStackTrace(); PlotSquared.log("&cCould not close database connection!"); } } @@ -1672,10 +1631,8 @@ import java.util.zip.ZipInputStream; /** * Setup the default configuration. - * - * @throws IOException if the config failed to save */ - public void setupConfig() throws IOException { + public void setupConfig() { String lastVersionString = this.config.getString("version"); if (lastVersionString != null) { String[] split = lastVersionString.split("\\."); @@ -1708,8 +1665,8 @@ import java.util.zip.ZipInputStream; Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer .toHexString(version.hash); System.out.println("Version is " + this.version); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); } Settings.save(configFile); config = YamlConfiguration.loadConfiguration(configFile); @@ -2027,7 +1984,7 @@ import java.util.zip.ZipInputStream; * * @param alias to search plots * @param worldname to filter alias to a specific world [optional] null means all worlds - * @return Set<{ @ link Plot }> empty if nothing found + * @return Set<{ @ link Plot }> empty if nothing found */ public Set getPlotsByAlias(@Nullable final String alias, @NonNull final String worldname) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java index 3abf51fde..d32def9b6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java @@ -33,8 +33,8 @@ public class PlotVersion { public static PlotVersion tryParse(String version) { try { return new PlotVersion(version); - } catch (Exception ignore) { - ignore.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); return new PlotVersion(0, 0, 0, 0, 0); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java index 03d27555a..9aeed3057 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java @@ -61,21 +61,19 @@ import java.util.UUID; checkTrue(!uuids.isEmpty(), null); checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS); - confirm.run(this, new Runnable() { - @Override // Success - public void run() { - for (UUID uuid : uuids) { - if (uuid != DBFunc.EVERYONE) { - if (!plot.removeTrusted(uuid)) { - if (plot.getDenied().contains(uuid)) { - plot.removeDenied(uuid); - } + // Success + confirm.run(this, () -> { + for (UUID uuid : uuids) { + if (uuid != DBFunc.EVERYONE) { + if (!plot.removeTrusted(uuid)) { + if (plot.getDenied().contains(uuid)) { + plot.removeDenied(uuid); } } - plot.addMember(uuid); - EventUtil.manager.callMember(player, plot, uuid, true); - MainUtil.sendMessage(player, C.MEMBER_ADDED); } + plot.addMember(uuid); + EventUtil.manager.callMember(player, plot, uuid, true); + MainUtil.sendMessage(player, C.MEMBER_ADDED); } }, null); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java index 9dc5ce20e..84837e9d3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java @@ -98,42 +98,40 @@ import java.util.Set; object.type = area.TYPE; object.min = new PlotId(1, 1); object.max = new PlotId(numX, numZ); - object.plotManager = PlotSquared.imp().getPluginName(); - object.setupGenerator = PlotSquared.imp().getPluginName(); + object.plotManager = PlotSquared.get().IMP.getPluginName(); + object.setupGenerator = PlotSquared.get().IMP.getPluginName(); object.step = area.getSettingNodes(); final String path = "worlds." + area.worldname + ".areas." + area.id + '-' + object.min + '-' + object.max; - Runnable run = new Runnable() { - @Override public void run() { - if (offsetX != 0) { - PlotSquared.get().worlds - .set(path + ".road.offset.x", offsetX); - } - if (offsetZ != 0) { - PlotSquared.get().worlds - .set(path + ".road.offset.z", offsetZ); - } - final String world = SetupUtils.manager.setupWorld(object); - if (WorldUtil.IMP.isWorld(world)) { - PlotSquared.get().loadWorld(world, null); - C.SETUP_FINISHED.send(player); - player.teleport(WorldUtil.IMP.getSpawn(world)); - if (area.TERRAIN != 3) { - ChunkManager.largeRegionTask(world, region, - new RunnableVal() { - @Override public void run(ChunkLoc value) { - AugmentedUtils - .generate(world, value.x, value.z, - null); - } - }, null); - } - } else { - MainUtil.sendMessage(player, - "An error occurred while creating the world: " - + area.worldname); + Runnable run = () -> { + if (offsetX != 0) { + PlotSquared.get().worlds + .set(path + ".road.offset.x", offsetX); + } + if (offsetZ != 0) { + PlotSquared.get().worlds + .set(path + ".road.offset.z", offsetZ); + } + final String world = SetupUtils.manager.setupWorld(object); + if (WorldUtil.IMP.isWorld(world)) { + PlotSquared.get().loadWorld(world, null); + C.SETUP_FINISHED.send(player); + player.teleport(WorldUtil.IMP.getSpawn(world)); + if (area.TERRAIN != 3) { + ChunkManager.largeRegionTask(world, region, + new RunnableVal() { + @Override public void run(ChunkLoc value) { + AugmentedUtils + .generate(world, value.x, value.z, + null); + } + }, null); } + } else { + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + area.worldname); } }; if (hasConfirmation(player)) { @@ -228,32 +226,30 @@ import java.util.Set; C.SETUP_WORLD_TAKEN.send(player, pa.worldname); return false; } - Runnable run = new Runnable() { - @Override public void run() { - String path = "worlds." + pa.worldname; - if (!PlotSquared.get().worlds.contains(path)) { - PlotSquared.get().worlds.createSection(path); - } - ConfigurationSection section = - PlotSquared.get().worlds.getConfigurationSection(path); - pa.saveConfiguration(section); - pa.loadConfiguration(section); - object.plotManager = PlotSquared.imp().getPluginName(); - object.setupGenerator = PlotSquared.imp().getPluginName(); - String world = SetupUtils.manager.setupWorld(object); - if (WorldUtil.IMP.isWorld(world)) { - C.SETUP_FINISHED.send(player); - player.teleport(WorldUtil.IMP.getSpawn(world)); - } else { - MainUtil.sendMessage(player, - "An error occurred while creating the world: " - + pa.worldname); - } - try { - PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); - } catch (IOException e) { - e.printStackTrace(); - } + Runnable run = () -> { + String path = "worlds." + pa.worldname; + if (!PlotSquared.get().worlds.contains(path)) { + PlotSquared.get().worlds.createSection(path); + } + ConfigurationSection section = + PlotSquared.get().worlds.getConfigurationSection(path); + pa.saveConfiguration(section); + pa.loadConfiguration(section); + object.plotManager = PlotSquared.get().IMP.getPluginName(); + object.setupGenerator = PlotSquared.get().IMP.getPluginName(); + String world = SetupUtils.manager.setupWorld(object); + if (WorldUtil.IMP.isWorld(world)) { + C.SETUP_FINISHED.send(player); + player.teleport(WorldUtil.IMP.getSpawn(world)); + } else { + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + pa.worldname); + } + try { + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); + } catch (IOException e) { + e.printStackTrace(); } }; if (hasConfirmation(player)) { @@ -422,11 +418,7 @@ import java.util.Set; @Override public void run(ChunkLoc value) { AugmentedUtils.generate(area.worldname, value.x, value.z, null); } - }, new Runnable() { - @Override public void run() { - player.sendMessage("Regen complete"); - } - }); + }, () -> player.sendMessage("Regen complete")); return true; } case "goto": @@ -464,7 +456,7 @@ import java.util.Set; case "remove": MainUtil.sendMessage(player, "$1World creation settings may be stored in multiple locations:" - + "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.imp() + + "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.get().IMP .getPluginName() + " settings.yml" + "\n$3 - $2Multiverse worlds.yml (or any world management plugin)" + "\n$1Stop the server and delete it from these locations."); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java index a8636d1e1..0c1fb9225 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java @@ -16,10 +16,6 @@ import java.util.Set; description = "Claim the nearest plot", aliases = "a", usage = "/plot auto [length,width]") public class Auto extends SubCommand { - @Deprecated public static PlotId getNextPlotId(PlotId id, int step) { - return id.getNextId(step); - } - private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, @Nullable Integer allowed_plots, int size_x, int size_z) { if (allowed_plots == null) @@ -128,12 +124,9 @@ public class Auto extends SubCommand { return; } whenDone.value = plot; - plot.owner = player.getUUID(); - DBFunc.createPlotSafe(plot, whenDone, new Runnable() { - @Override public void run() { - autoClaimFromDatabase(player, area, plot.getId(), whenDone); - } - }); + plot.setOwner(player.getUUID()); + DBFunc.createPlotSafe(plot, whenDone, + () -> autoClaimFromDatabase(player, area, plot.getId(), whenDone)); } @Override public boolean onCommand(final PlotPlayer player, String[] args) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java index 82a573949..84d57b192 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java @@ -27,11 +27,9 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; return false; } plot.addRunning(); - plot.setBiome(value.toUpperCase(), new Runnable() { - @Override public void run() { - plot.removeRunning(); - MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase()); - } + plot.setBiome(value.toUpperCase(), () -> { + plot.removeRunning(); + MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase()); }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java index af552ec67..f258650f0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java @@ -46,27 +46,24 @@ import java.util.Set; final double price = flag.get(); checkTrue(player.getMoney() >= price, C.CANNOT_AFFORD_PLOT); player.withdraw(price); - confirm.run(this, new Runnable() { - @Override // Success - public void run() { - C.REMOVED_BALANCE.send(player, price); - EconHandler.manager - .depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price); - PlotPlayer owner = UUIDHandler.getPlayer(plot.owner); - if (owner != null) { - C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); - } - plot.removeFlag(Flags.PRICE); - plot.setOwner(player.getUUID()); - C.CLAIMED.send(player); - whenDone.run(Buy.this, CommandResult.SUCCESS); - } - }, new Runnable() { - @Override // Failure - public void run() { - player.deposit(price); - whenDone.run(Buy.this, CommandResult.FAILURE); + // Failure + // Success + confirm.run(this, () -> { + C.REMOVED_BALANCE.send(player, price); + EconHandler.manager + .depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.guessOwner()), + price); + PlotPlayer owner = UUIDHandler.getPlayer(plot.guessOwner()); + if (owner != null) { + C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); } + plot.removeFlag(Flags.PRICE); + plot.setOwner(player.getUUID()); + C.CLAIMED.send(player); + whenDone.run(Buy.this, CommandResult.SUCCESS); + }, () -> { + player.deposit(price); + whenDone.run(Buy.this, CommandResult.FAILURE); }); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java index 88f102967..6677eeb51 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java @@ -80,24 +80,16 @@ public class Claim extends SubCommand { sendMessage(player, C.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1)); } if (plot.canClaim(player)) { - plot.owner = player.getUUID(); + plot.setOwner(player.getUUID()); final String finalSchematic = schematic; - DBFunc.createPlotSafe(plot, new Runnable() { - @Override public void run() { - TaskManager.IMP.sync(new RunnableVal() { - @Override public void run(Object value) { - plot.claim(player, true, finalSchematic, false); - if (area.AUTO_MERGE) { - plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); - } - } - }); + DBFunc.createPlotSafe(plot, () -> TaskManager.IMP.sync(new RunnableVal() { + @Override public void run(Object value) { + plot.claim(player, true, finalSchematic, false); + if (area.AUTO_MERGE) { + plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); + } } - }, new Runnable() { - @Override public void run() { - sendMessage(player, C.PLOT_NOT_CLAIMED); - } - }); + }), () -> sendMessage(player, C.PLOT_NOT_CLAIMED)); return true; } else { sendMessage(player, C.PLOT_NOT_CLAIMED); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java index efd6b1525..98c1eb597 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java @@ -35,33 +35,27 @@ import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER); checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions .hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE); - confirm.run(this, new Runnable() { - @Override public void run() { - final long start = System.currentTimeMillis(); - boolean result = plot.clear(true, false, new Runnable() { - @Override public void run() { - plot.unlink(); - GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override public void run() { - plot.removeRunning(); - // If the state changes, then mark it as no longer done - if (plot.getFlag(Flags.DONE).isPresent()) { - FlagManager.removePlotFlag(plot, Flags.DONE); - } - if (plot.getFlag(Flags.ANALYSIS).isPresent()) { - FlagManager.removePlotFlag(plot, Flags.ANALYSIS); - } - MainUtil.sendMessage(player, C.CLEARING_DONE, - "" + (System.currentTimeMillis() - start)); - } - }); + confirm.run(this, () -> { + final long start = System.currentTimeMillis(); + boolean result = plot.clear(true, false, () -> { + plot.unlink(); + GlobalBlockQueue.IMP.addTask(() -> { + plot.removeRunning(); + // If the state changes, then mark it as no longer done + if (plot.getFlag(Flags.DONE).isPresent()) { + FlagManager.removePlotFlag(plot, Flags.DONE); } + if (plot.getFlag(Flags.ANALYSIS).isPresent()) { + FlagManager.removePlotFlag(plot, Flags.ANALYSIS); + } + MainUtil.sendMessage(player, C.CLEARING_DONE, + "" + (System.currentTimeMillis() - start)); }); - if (!result) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); - } else { - plot.addRunning(); - } + }); + if (!result) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + } else { + plot.addRunning(); } }, null); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java index 154a8f914..6eacb6c15 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java @@ -148,9 +148,9 @@ import java.util.UUID; // Add any existing plots to the current cluster for (Plot plot : plots) { if (plot.hasOwner()) { - if (!cluster.isAdded(plot.owner)) { - cluster.invited.add(plot.owner); - DBFunc.setInvited(cluster, plot.owner); + if (!cluster.isAdded(plot.guessOwner())) { + cluster.invited.add(plot.guessOwner()); + DBFunc.setInvited(cluster, plot.guessOwner()); } } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java index 040fd97b8..97dfe7d3d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java @@ -97,7 +97,7 @@ import java.util.concurrent.atomic.AtomicBoolean; if (plot != null && !plot.hasOwner()) { free.add(plot.getId()); } - start = Auto.getNextPlotId(start, 1); + start = start.getNextId(1); } if (free.isEmpty() || toMove.isEmpty()) { MainUtil.sendMessage(player, "NO FREE PLOTS FOUND"); @@ -126,13 +126,11 @@ import java.util.concurrent.atomic.AtomicBoolean; } i++; final AtomicBoolean result = new AtomicBoolean(false); - result.set(origin.move(possible, new Runnable() { - @Override public void run() { - if (result.get()) { - MainUtil.sendMessage(player, - "Moving: " + origin + " -> " + possible); - TaskManager.runTaskLater(task, 1); - } + result.set(origin.move(possible, () -> { + if (result.get()) { + MainUtil.sendMessage(player, + "Moving: " + origin + " -> " + possible); + TaskManager.runTaskLater(task, 1); } }, false)); if (result.get()) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java index 8303ef042..80c1aa28a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java @@ -40,11 +40,7 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; C.PLOTWORLD_INCOMPATIBLE.send(player); return false; } - if (plot1.copy(plot2, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, C.COPY_SUCCESS); - } - })) { + if (plot1.copy(plot2, () -> MainUtil.sendMessage(player, C.COPY_SUCCESS))) { return true; } else { MainUtil.sendMessage(player, C.REQUIRES_UNOWNED); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java index b760bc282..26951f136 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java @@ -30,25 +30,18 @@ import java.util.Map.Entry; public static void insertPlots(final SQLManager manager, final List plots, final PlotPlayer player) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try { - ArrayList ps = new ArrayList<>(); - for (Plot p : plots) { - ps.add(p); - } - MainUtil.sendMessage(player, "&6Starting..."); - manager.createPlotsAndData(ps, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database conversion finished!"); - manager.close(); - } - }); - } catch (Exception e) { - MainUtil.sendMessage(player, - "Failed to insert plot objects, see stacktrace for info"); - e.printStackTrace(); - } + TaskManager.runTaskAsync(() -> { + try { + ArrayList ps = new ArrayList<>(plots); + MainUtil.sendMessage(player, "&6Starting..."); + manager.createPlotsAndData(ps, () -> { + MainUtil.sendMessage(player, "&6Database conversion finished!"); + manager.close(); + }); + } catch (Exception e) { + MainUtil + .sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); + e.printStackTrace(); } }); } @@ -106,12 +99,12 @@ import java.util.Map.Entry; PlotId newId = newPlot.getId(); PlotId id = plot.getId(); File worldFile = - new File(PlotSquared.imp().getWorldContainer(), + new File(PlotSquared.get().IMP.getWorldContainer(), id.toCommaSeparatedString()); if (worldFile.exists()) { - File newFile = - new File(PlotSquared.imp().getWorldContainer(), - newId.toCommaSeparatedString()); + File newFile = new File( + PlotSquared.get().IMP.getWorldContainer(), + newId.toCommaSeparatedString()); worldFile.renameTo(newFile); } id.x = newId.x; @@ -130,20 +123,13 @@ import java.util.Map.Entry; plots.add(plot); } } else { - HashMap plotmap = - PlotSquared.get().plots_tmp.get(areaname); - if (plotmap == null) { - plotmap = new HashMap<>(); - PlotSquared.get().plots_tmp.put(areaname, plotmap); - } + HashMap plotmap = PlotSquared.get().plots_tmp + .computeIfAbsent(areaname, k -> new HashMap<>()); plotmap.putAll(entry.getValue()); } } - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database conversion finished!"); - } - }); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&6Database conversion finished!")); return true; case "mysql": if (args.length < 6) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java index 01a344369..1d06cabd3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java @@ -34,8 +34,6 @@ public class DebugClaimTest extends SubCommand { } PlotId min, max; try { - args[1].split(";"); - args[2].split(";"); min = PlotId.fromString(args[1]); max = PlotId.fromString(args[2]); } catch (Exception ignored) { @@ -96,11 +94,8 @@ public class DebugClaimTest extends SubCommand { if (!plots.isEmpty()) { MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database update finished!"); - } - }); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&6Database update finished!")); for (Plot plot : plots) { plot.create(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java index d68220814..a2995308a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java @@ -46,8 +46,8 @@ import java.util.*; this.engine.eval(script, this.scope); } } - } catch (IOException | ScriptException ignored) { - ignored.printStackTrace(); + } catch (IOException | ScriptException e) { + e.printStackTrace(); } } @@ -164,11 +164,8 @@ import java.util.*; "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); return false; } - PlotAnalysis.calcOptimalModifiers(new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry"); - } - }, threshold); + PlotAnalysis.calcOptimalModifiers(() -> MainUtil + .sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold); return true; case "stop-expire": if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) { @@ -404,18 +401,16 @@ import java.util.*; try { if (async) { final String toExec = script; - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - long start = System.currentTimeMillis(); - Object result = null; - try { - result = DebugExec.this.engine.eval(toExec, DebugExec.this.scope); - } catch (ScriptException e) { - e.printStackTrace(); - } - PlotSquared.log( - "> " + (System.currentTimeMillis() - start) + "ms -> " + result); + TaskManager.runTaskAsync(() -> { + long start = System.currentTimeMillis(); + Object result = null; + try { + result = DebugExec.this.engine.eval(toExec, DebugExec.this.scope); + } catch (ScriptException e) { + e.printStackTrace(); } + PlotSquared + .log("> " + (System.currentTimeMillis() - start) + "ms -> " + result); }); } else { long start = System.currentTimeMillis(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java index ddffaf744..4c3bb8c8f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java @@ -35,7 +35,7 @@ import java.util.UUID; } SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea(); PlotId id = new PlotId(0, 0); - File container = PlotSquared.imp().getWorldContainer(); + File container = PlotSquared.get().IMP.getWorldContainer(); for (File folder : container.listFiles()) { String name = folder.getName(); if (!WorldUtil.IMP.isWorld(name) && PlotId.fromString(name) == null) { @@ -45,7 +45,7 @@ import java.util.UUID; UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); } while (new File(container, id.toCommaSeparatedString()).exists()) { - id = Auto.getNextPlotId(id, 1); + id = id.getNextId(1); } File newDir = new File(container, id.toCommaSeparatedString()); if (folder.renameTo(newDir)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java index bb06abe8a..ee75f0435 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java @@ -19,69 +19,64 @@ import java.io.IOException; extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { + TaskManager.runTaskAsync(() -> { + try { + String settingsYML = HastebinUtility.upload(PlotSquared.get().configFile); + String worldsYML = HastebinUtility.upload(PlotSquared.get().worldsFile); + String commandsYML = HastebinUtility.upload(PlotSquared.get().commandsFile); + String latestLOG; try { - String settingsYML = HastebinUtility.upload(PlotSquared.get().configFile); - String worldsYML = HastebinUtility.upload(PlotSquared.get().worldsFile); - String commandsYML = HastebinUtility.upload(PlotSquared.get().commandsFile); - String latestLOG; - try { - latestLOG = HastebinUtility.upload( - new File(PlotSquared.get().IMP.getDirectory(), - "../../logs/latest.log")); - } catch (IOException ignored) { - MainUtil.sendMessage(player, - "&clatest.log is too big to be pasted, will ignore"); - latestLOG = "too big :("; - } - StringBuilder b = new StringBuilder(); - b.append( - "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " - + "problem\n\n# We will start with some informational files\n"); - b.append("links.settings_yml: ").append(settingsYML).append('\n'); - b.append("links.worlds_yml: ").append(worldsYML).append('\n'); - b.append("links.commands_yml: ").append(commandsYML).append('\n'); - b.append("links.latest_log: ").append(latestLOG).append('\n'); - b.append("\n# Server Information\n"); - int[] sVersion = PlotSquared.get().IMP.getServerVersion(); - b.append("version.server: ").append(sVersion[0]).append('.').append(sVersion[1]) - .append('.').append(sVersion[2]).append('\n'); - b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';') - .append(!Settings.UUID.OFFLINE).append('\n'); - b.append("plugins:"); - for (String id : PlotSquared.get().IMP.getPluginIds()) { - String[] split = id.split(":"); - String[] split2 = split[0].split(";"); - String enabled = split.length == 2 ? split[1] : "unknown"; - String name = split2[0]; - String version = split2.length == 2 ? split2[1] : "unknown"; - b.append("\n ").append(name).append(":\n ").append("version: '") - .append(version).append('\'').append("\n enabled: ").append(enabled); - } - b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); - Runtime runtime = Runtime.getRuntime(); - b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); - b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); - b.append("java.specification.version: '") - .append(System.getProperty("java.specification.version")).append("'\n"); - b.append("java.vendor: '").append(System.getProperty("java.vendor")) - .append("'\n"); - b.append("java.version: '").append(System.getProperty("java.version")) - .append("'\n"); - b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); - b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); - b.append("os.version: '").append(System.getProperty("os.version")) - .append("'\n\n"); - b.append("# Okay :D Great. You are now ready to create your bug report!"); - b.append( - "\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); - - String link = HastebinUtility.upload(b.toString()); - player.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); - } catch (IOException e) { - e.printStackTrace(); + latestLOG = HastebinUtility.upload( + new File(PlotSquared.get().IMP.getDirectory(), "../../logs/latest.log")); + } catch (IOException ignored) { + MainUtil + .sendMessage(player, "&clatest.log is too big to be pasted, will ignore"); + latestLOG = "too big :("; } + StringBuilder b = new StringBuilder(); + b.append( + "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " + + "problem\n\n# We will start with some informational files\n"); + b.append("links.settings_yml: ").append(settingsYML).append('\n'); + b.append("links.worlds_yml: ").append(worldsYML).append('\n'); + b.append("links.commands_yml: ").append(commandsYML).append('\n'); + b.append("links.latest_log: ").append(latestLOG).append('\n'); + b.append("\n# Server Information\n"); + int[] sVersion = PlotSquared.get().IMP.getServerVersion(); + b.append("version.server: ").append(sVersion[0]).append('.').append(sVersion[1]) + .append('.').append(sVersion[2]).append('\n'); + b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';') + .append(!Settings.UUID.OFFLINE).append('\n'); + b.append("plugins:"); + for (String id : PlotSquared.get().IMP.getPluginIds()) { + String[] split = id.split(":"); + String[] split2 = split[0].split(";"); + String enabled = split.length == 2 ? split[1] : "unknown"; + String name = split2[0]; + String version = split2.length == 2 ? split2[1] : "unknown"; + b.append("\n ").append(name).append(":\n ").append("version: '") + .append(version).append('\'').append("\n enabled: ").append(enabled); + } + b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); + Runtime runtime = Runtime.getRuntime(); + b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); + b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); + b.append("java.specification.version: '") + .append(System.getProperty("java.specification.version")).append("'\n"); + b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n"); + b.append("java.version: '").append(System.getProperty("java.version")) + .append("'\n"); + b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); + b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); + b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); + b.append("# Okay :D Great. You are now ready to create your bug report!"); + b.append( + "\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); + + String link = HastebinUtility.upload(b.toString()); + player.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); + } catch (IOException e) { + e.printStackTrace(); } }); return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java index fbbc3267c..0c544d096 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java @@ -16,14 +16,10 @@ import java.util.ArrayList; public class DebugSaveTest extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - ArrayList plots = new ArrayList(); - plots.addAll(PlotSquared.get().getPlots()); + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`"); - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database sync finished!"); - } - }); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&6Database sync finished!")); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java index ede1f14cd..82d644292 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java @@ -33,33 +33,28 @@ import com.github.intellectualsites.plotsquared.plot.util.*; final java.util.Set plots = plot.getConnectedPlots(); final int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); - Runnable run = new Runnable() { - @Override public void run() { - if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); - return; - } - final long start = System.currentTimeMillis(); - boolean result = plot.deletePlot(new Runnable() { - @Override public void run() { - plot.removeRunning(); - if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) { - Expression valueExr = plotArea.PRICES.get("sell"); - double value = plots.size() * valueExr.evaluate((double) currentPlots); - if (value > 0d) { - EconHandler.manager.depositMoney(player, value); - sendMessage(player, C.ADDED_BALANCE, String.valueOf(value)); - } - } - MainUtil.sendMessage(player, C.DELETING_DONE, - System.currentTimeMillis() - start); + Runnable run = () -> { + if (plot.getRunning() > 0) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + return; + } + final long start = System.currentTimeMillis(); + boolean result = plot.deletePlot(() -> { + plot.removeRunning(); + if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) { + Expression valueExr = plotArea.PRICES.get("sell"); + double value = plots.size() * valueExr.evaluate((double) currentPlots); + if (value > 0d) { + EconHandler.manager.depositMoney(player, value); + sendMessage(player, C.ADDED_BALANCE, String.valueOf(value)); } - }); - if (result) { - plot.addRunning(); - } else { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); } + MainUtil.sendMessage(player, C.DELETING_DONE, System.currentTimeMillis() - start); + }); + if (result) { + plot.addRunning(); + } else { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); } }; if (hasConfirmation(player)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java index e586f0656..e36f09c04 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java @@ -10,7 +10,6 @@ import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.*; -import java.util.Iterator; import java.util.Set; import java.util.UUID; @@ -44,9 +43,7 @@ import java.util.UUID; MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); return false; } - Iterator iter = uuids.iterator(); - while (iter.hasNext()) { - UUID uuid = iter.next(); + for (UUID uuid : uuids) { if (uuid == DBFunc.EVERYONE && !( Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java index d7ab4e9cd..3deb9b3ba 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java @@ -247,20 +247,21 @@ import java.util.*; for (Flag flag1 : Flags.getFlags()) { String type = flag1.getClass().getSimpleName(); if (!flags.containsKey(type)) { - flags.put(type, new ArrayList()); + flags.put(type, new ArrayList<>()); } flags.get(type).add(flag1.getName()); } - String message = ""; + StringBuilder message = new StringBuilder(); String prefix = ""; for (Map.Entry> entry : flags.entrySet()) { String category = entry.getKey(); List flagNames = entry.getValue(); Collections.sort(flagNames); - message += prefix + "&6" + category + ": &7" + StringMan.join(flagNames, ", "); + message.append(prefix).append("&6").append(category).append(": &7") + .append(StringMan.join(flagNames, ", ")); prefix = "\n"; } - MainUtil.sendMessage(player, message); + MainUtil.sendMessage(player, message.toString()); return true; } MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag "); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java index 5a69479b5..199396d43 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java @@ -209,7 +209,7 @@ public class GenerateDocs { line = line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "") .trim(); - result.append(line + '\n'); + result.append(line).append('\n'); } } return result.toString().trim(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java index f0ff64af1..0ef4248cc 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java @@ -57,9 +57,7 @@ public class Help extends Command { public void displayHelp(PlotPlayer player, String cat, int page) { CommandCategory catEnum = null; if (cat != null) { - if (StringMan.isEqualIgnoreCase(cat, "all")) { - catEnum = null; - } else { + if (!StringMan.isEqualIgnoreCase(cat, "all")) { for (CommandCategory c : CommandCategory.values()) { if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { catEnum = c; @@ -76,13 +74,13 @@ public class Help extends Command { StringBuilder builder = new StringBuilder(); builder.append(C.HELP_HEADER.s()); for (CommandCategory c : CommandCategory.values()) { - builder.append("\n" + StringMan + builder.append("\n").append(StringMan .replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); } builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all") .replaceAll("%category_desc%", "Display all commands")); - builder.append("\n" + C.HELP_FOOTER.s()); + builder.append("\n").append(C.HELP_FOOTER.s()); MainUtil.sendMessage(player, builder.toString(), false); return; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java index bf1bb74be..b2d434dec 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java @@ -43,7 +43,7 @@ import java.util.List; StringBuilder string = new StringBuilder(); string.append(StringMan .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", - page + 1, "%max", totalPages + 1, "%word", "all") + '\n'); + page + 1, "%max", totalPages + 1, "%word", "all")).append('\n'); // This might work xD for (int x = page * 12; x < max; x++) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java index 6241e1d51..5144ebcad 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java @@ -69,24 +69,24 @@ import java.util.UUID; } }; UUID uuid = player.getUUID(); - String name = MainUtil.getName(plot.owner); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", - "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, - "&cAlias: &6" + plot.getAlias(), - "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), - "&cCan Build: &6" + plot.isAdded(uuid), - "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), - "&cIs Denied: &6" + plot.isDenied(uuid))); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", + String name = MainUtil.getName(plot.guessOwner()); + inv.setItem(1, + new PlotItemStack("emerald", 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(), + "&cOwner: &6" + name, "&cAlias: &6" + plot.getAlias(), + "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), + "&cCan Build: &6" + plot.isAdded(uuid), "&cSeen: &6" + MainUtil + .secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), + "&cIs Denied: &6" + plot.isDenied(uuid))); + inv.setItem(1, new PlotItemStack("emerald", 1, "&cTrusted", "&cAmount: &6" + plot.getTrusted().size(), "&8Click to view a list of the trusted users")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", + inv.setItem(1, new PlotItemStack("emerald", 1, "&cMembers", "&cAmount: &6" + plot.getMembers().size(), "&8Click to view a list of plot members")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied", + inv.setItem(1, new PlotItemStack("emerald", 1, "&cDenied", "&cDenied", "&cAmount: &6" + plot.getDenied().size(), "&8Click to view a list of denied players")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags", + inv.setItem(1, new PlotItemStack("emerald", 1, "&cFlags", "&cFlags", "&cAmount: &6" + plot.getFlags().size(), "&8Click to view a list of plot flags")); inv.openInventory(); return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java index 472103853..526f05969 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java @@ -10,8 +10,11 @@ import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.google.common.base.Optional; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Map.Entry; +import java.util.UUID; @CommandDeclaration(command = "list", aliases = {"l", "find", "search"}, description = "List plots", permission = "plots.list", category = CommandCategory.INFO, @@ -132,7 +135,7 @@ public class ListCmd extends SubCommand { return false; } plots = ExpireManager.IMP == null ? - new ArrayList() : + new ArrayList<>() : new ArrayList<>(ExpireManager.IMP.getPendingExpired()); break; case "area": @@ -145,7 +148,7 @@ public class ListCmd extends SubCommand { C.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } - plots = area == null ? new ArrayList() : new ArrayList<>(area.getPlots()); + plots = area == null ? new ArrayList<>() : new ArrayList<>(area.getPlots()); break; case "all": if (!Permissions.hasPermission(player, C.PERMISSION_LIST_ALL)) { @@ -167,18 +170,16 @@ public class ListCmd extends SubCommand { } plots.add(plot); } - Collections.sort(plots, new Comparator() { - @Override public int compare(Plot a, Plot b) { - String va = "" + a.getFlags().get(Flags.DONE); - String vb = "" + b.getFlags().get(Flags.DONE); - if (MathMan.isInteger(va)) { - if (MathMan.isInteger(vb)) { - return Integer.parseInt(vb) - Integer.parseInt(va); - } - return -1; + plots.sort((a, b) -> { + String va = "" + a.getFlags().get(Flags.DONE); + String vb = "" + b.getFlags().get(Flags.DONE); + if (MathMan.isInteger(va)) { + if (MathMan.isInteger(vb)) { + return Integer.parseInt(vb) - Integer.parseInt(va); } - return 1; + return -1; } + return 1; }); sort = false; break; @@ -188,33 +189,31 @@ public class ListCmd extends SubCommand { return false; } plots = new ArrayList<>(PlotSquared.get().getPlots()); - Collections.sort(plots, new Comparator() { - @Override public int compare(Plot p1, Plot p2) { - double v1 = 0; - int p1s = p1.getSettings().getRatings().size(); - int p2s = p2.getRatings().size(); - if (!p1.getSettings().getRatings().isEmpty()) { - for (Entry entry : p1.getRatings().entrySet()) { - double av = entry.getValue().getAverageRating(); - v1 += av * av; - } - v1 /= p1s; - v1 += p1s; + plots.sort((p1, p2) -> { + double v1 = 0; + int p1s = p1.getSettings().getRatings().size(); + int p2s = p2.getRatings().size(); + if (!p1.getSettings().getRatings().isEmpty()) { + for (Entry entry : p1.getRatings().entrySet()) { + double av = entry.getValue().getAverageRating(); + v1 += av * av; } - double v2 = 0; - if (!p2.getSettings().getRatings().isEmpty()) { - for (Entry entry : p2.getRatings().entrySet()) { - double av = entry.getValue().getAverageRating(); - v2 += av * av; - } - v2 /= p2s; - v2 += p2s; - } - if (v2 == v1 && v2 != 0) { - return p2s - p1s; - } - return (int) Math.signum(v2 - v1); + v1 /= p1s; + v1 += p1s; } + double v2 = 0; + if (!p2.getSettings().getRatings().isEmpty()) { + for (Entry entry : p2.getRatings().entrySet()) { + double av = entry.getValue().getAverageRating(); + v2 += av * av; + } + v2 /= p2s; + v2 += p2s; + } + if (v2 == v1 && v2 != 0) { + return p2s - p1s; + } + return (int) Math.signum(v2 - v1); }); sort = false; break; @@ -241,7 +240,7 @@ public class ListCmd extends SubCommand { } plots = new ArrayList<>(); for (Plot plot : PlotSquared.get().getPlots()) { - if (plot.owner == null) { + if (plot.guessOwner() == null) { plots.add(plot); } } @@ -253,10 +252,10 @@ public class ListCmd extends SubCommand { } plots = new ArrayList<>(); for (Plot plot : PlotSquared.get().getPlots()) { - if (plot.owner == null) { + if (plot.guessOwner() == null) { continue; } - if (UUIDHandler.getName(plot.owner) == null) { + if (UUIDHandler.getName(plot.guessOwner()) == null) { plots.add(plot); } } @@ -330,12 +329,7 @@ public class ListCmd extends SubCommand { public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, PlotArea area, String[] args, boolean sort) { // Header - Iterator iterator = plots.iterator(); - while (iterator.hasNext()) { - if (!iterator.next().isBasePlot()) { - iterator.remove(); - } - } + plots.removeIf(plot -> !plot.isBasePlot()); if (sort) { plots = PlotSquared.get().sortPlots(plots, SortType.CREATION_DATE, area); } @@ -343,7 +337,7 @@ public class ListCmd extends SubCommand { new RunnableVal3() { @Override public void run(Integer i, Plot plot, PlotMessage message) { String color; - if (plot.owner == null) { + if (plot.guessOwner() == null) { color = "$3"; } else if (plot.isOwner(player.getUUID())) { color = "$1"; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java index 42736f9dc..36ee0a1a6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java @@ -103,17 +103,15 @@ import java.util.List; List schematics = player.getMeta("plot_schematics"); if (schematics == null) { plot.addRunning(); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - List schematics = SchematicHandler.manager.getSaves(player.getUUID()); - plot.removeRunning(); - if ((schematics == null) || schematics.isEmpty()) { - MainUtil.sendMessage(player, C.LOAD_FAILED); - return; - } - player.setMeta("plot_schematics", schematics); - displaySaves(player); + TaskManager.runTaskAsync(() -> { + List schematics1 = SchematicHandler.manager.getSaves(player.getUUID()); + plot.removeRunning(); + if ((schematics1 == null) || schematics1.isEmpty()) { + MainUtil.sendMessage(player, C.LOAD_FAILED); + return; } + player.setMeta("plot_schematics", schematics1); + displaySaves(player); }); } else { displaySaves(player); @@ -151,30 +149,30 @@ import java.util.List; if (time >= 33868800) { int years = (int) (time / 33868800); time -= years * 33868800; - toreturn.append(years + "y "); + toreturn.append(years).append("y "); } if (time >= 604800) { int weeks = (int) (time / 604800); time -= weeks * 604800; - toreturn.append(weeks + "w "); + toreturn.append(weeks).append("w "); } if (time >= 86400) { int days = (int) (time / 86400); time -= days * 86400; - toreturn.append(days + "d "); + toreturn.append(days).append("d "); } if (time >= 3600) { int hours = (int) (time / 3600); time -= hours * 3600; - toreturn.append(hours + "h "); + toreturn.append(hours).append("h "); } if (time >= 60) { int minutes = (int) (time / 60); time -= minutes * 60; - toreturn.append(minutes + "m "); + toreturn.append(minutes).append("m "); } if (toreturn.length() == 0 || (time > 0)) { - toreturn.append(time + "s "); + toreturn.append(time).append("s "); } return toreturn.toString().trim(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java index a68681d7a..70e0007df 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java @@ -127,27 +127,23 @@ public class MainCommand extends Command { @Override public void run(final Command cmd, final Runnable success, final Runnable failure) { if (cmd.hasConfirmation(player)) { - CmdConfirm.addPending(player, cmd.getUsage(), new Runnable() { - @Override public void run() { - if (EconHandler.manager != null) { - PlotArea area = player.getApplicablePlotArea(); - if (area != null) { - Expression priceEval = - area.PRICES.get(cmd.getFullId()); - Double price = - priceEval != null ? priceEval.evaluate(0d) : 0d; - if (price != null - && EconHandler.manager.getMoney(player) < price) { - if (failure != null) { - failure.run(); - } - return; + CmdConfirm.addPending(player, cmd.getUsage(), () -> { + if (EconHandler.manager != null) { + PlotArea area = player.getApplicablePlotArea(); + if (area != null) { + Expression priceEval = area.PRICES.get(cmd.getFullId()); + Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; + if (price != null + && EconHandler.manager.getMoney(player) < price) { + if (failure != null) { + failure.run(); } + return; } } - if (success != null) { - success.run(); - } + } + if (success != null) { + success.run(); } }); return; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java index 532fa2ce0..05e090c70 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java @@ -55,12 +55,11 @@ public class Merge extends SubCommand { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } else { - uuid = plot.owner; + uuid = plot.guessOwner(); } } final PlotArea plotArea = plot.getArea(); - Expression priceExr = - plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; + Expression priceExr = plotArea.PRICES.getOrDefault("merge", null); final int size = plot.getConnectedPlots().size(); final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d @@ -155,25 +154,23 @@ public class Merge extends SubCommand { } isOnline = true; final int dir = direction; - Runnable run = new Runnable() { - @Override public void run() { - MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); - plot.autoMerge(dir, maxSize - size, owner, terrain); - PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID()); - if (plotPlayer == null) { - sendMessage(accepter, C.MERGE_NOT_VALID); + Runnable run = () -> { + MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); + plot.autoMerge(dir, maxSize - size, owner, terrain); + PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID()); + if (plotPlayer == null) { + sendMessage(accepter, C.MERGE_NOT_VALID); + return; + } + if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d) { + if (EconHandler.manager.getMoney(player) < price) { + sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); return; } - if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d) { - if (EconHandler.manager.getMoney(player) < price) { - sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); - return; - } - EconHandler.manager.withdrawMoney(player, price); - sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price)); - } - MainUtil.sendMessage(player, C.SUCCESS_MERGE); + EconHandler.manager.withdrawMoney(player, price); + sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price)); } + MainUtil.sendMessage(player, C.SUCCESS_MERGE); }; if (hasConfirmation(player)) { CmdConfirm.addPending(accepter, diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java index 346dea7b9..289a3c4a6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java @@ -54,11 +54,7 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; C.PLOTWORLD_INCOMPATIBLE.send(player); return false; } - if (plot1.move(plot2, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, C.MOVE_SUCCESS); - } - }, false)) { + if (plot1.move(plot2, () -> MainUtil.sendMessage(player, C.MOVE_SUCCESS), false)) { return true; } else { MainUtil.sendMessage(player, C.REQUIRES_UNOWNED); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java index 4095c15c9..943195a75 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java @@ -71,20 +71,17 @@ import java.util.UUID; final String finalName = name; final UUID finalUUID = uuid; final boolean removeDenied = plot.isDenied(finalUUID); - Runnable run = new Runnable() { - @Override public void run() { - if (plot.setOwner(finalUUID, player)) { - if (removeDenied) - plot.removeDenied(finalUUID); - plot.setSign(finalName); - MainUtil.sendMessage(player, C.SET_OWNER); - if (other != null) { - MainUtil - .sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId()); - } - } else - MainUtil.sendMessage(player, C.SET_OWNER_CANCELLED); - } + Runnable run = () -> { + if (plot.setOwner(finalUUID, player)) { + if (removeDenied) + plot.removeDenied(finalUUID); + plot.setSign(finalName); + MainUtil.sendMessage(player, C.SET_OWNER); + if (other != null) { + MainUtil.sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId()); + } + } else + MainUtil.sendMessage(player, C.SET_OWNER_CANCELLED); }; if (hasConfirmation(player)) { CmdConfirm.addPending(player, "/plot set owner " + value, run); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java index 81047ec9b..23b76964d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java @@ -13,18 +13,16 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager; category = CommandCategory.INFO) public class PluginCmd extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - TaskManager.IMP.taskAsync(new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, String.format( - "$2>> $1&l" + PlotSquared.imp().getPluginName() + " $2($1Version$2: $1%s$2)", - PlotSquared.get().getVersion())); - MainUtil.sendMessage(player, - "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev $2& $1dordsor21"); - MainUtil.sendMessage(player, - "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); - MainUtil.sendMessage(player, - "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); - } + TaskManager.IMP.taskAsync(() -> { + MainUtil.sendMessage(player, String.format( + "$2>> $1&l" + PlotSquared.get().IMP.getPluginName() + " $2($1Version$2: $1%s$2)", + PlotSquared.get().getVersion())); + MainUtil.sendMessage(player, + "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev $2& $1dordsor21"); + MainUtil.sendMessage(player, + "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); + MainUtil + .sendMessage(player, "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java index b8b38e298..4ccaeec1c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java @@ -105,12 +105,10 @@ import java.util.UUID; if (added != null && !plot.isAdded(added)) { continue; } - if (unknown && UUIDHandler.getName(plot.owner) != null) { + if (unknown && UUIDHandler.getName(plot.guessOwner()) != null) { continue; } - for (Plot current : plot.getConnectedPlots()) { - toDelete.add(current); - } + toDelete.addAll(plot.getConnectedPlots()); } if (PlotSquared.get().plots_tmp != null) { for (Entry> entry : PlotSquared.get().plots_tmp @@ -130,7 +128,7 @@ import java.util.UUID; if (added != null && !plot.isAdded(added)) { continue; } - if (unknown && UUIDHandler.getName(plot.owner) != null) { + if (unknown && UUIDHandler.getName(plot.guessOwner()) != null) { continue; } toDelete.add(plot); @@ -143,23 +141,21 @@ import java.util.UUID; } String cmd = "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; - Runnable run = new Runnable() { - @Override public void run() { - PlotSquared.debug("Calculating plots to purge, please wait..."); - HashSet ids = new HashSet<>(); - for (Plot plot : toDelete) { - if (plot.temp != Integer.MAX_VALUE) { - ids.add(plot.temp); - plot.getArea().removePlot(plot.getId()); - for (PlotPlayer pp : plot.getPlayersInPlot()) { - PlotListener.plotEntry(pp, plot); - } - plot.removeSign(); + Runnable run = () -> { + PlotSquared.debug("Calculating plots to purge, please wait..."); + HashSet ids = new HashSet<>(); + for (Plot plot : toDelete) { + if (plot.temp != Integer.MAX_VALUE) { + ids.add(plot.temp); + plot.getArea().removePlot(plot.getId()); + for (PlotPlayer pp : plot.getPlayersInPlot()) { + PlotListener.plotEntry(pp, plot); } + plot.removeSign(); } - DBFunc.purgeIds(ids); - C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size()); } + DBFunc.purgeIds(ids); + C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size()); }; if (hasConfirmation(player)) { CmdConfirm.addPending(player, cmd, run); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java index 7141df96e..3a5f01081 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java @@ -10,8 +10,11 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.Map.Entry; +import java.util.UUID; @CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot", usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO, @@ -22,25 +25,23 @@ import java.util.Map.Entry; switch (args[0].toLowerCase()) { case "next": { ArrayList plots = new ArrayList<>(PlotSquared.get().getBasePlots()); - Collections.sort(plots, new Comparator() { - @Override public int compare(Plot p1, Plot p2) { - double v1 = 0; - if (!p1.getRatings().isEmpty()) { - for (Entry entry : p1.getRatings().entrySet()) { - v1 -= 11 - entry.getValue().getAverageRating(); - } + Collections.sort(plots, (p1, p2) -> { + double v1 = 0; + if (!p1.getRatings().isEmpty()) { + for (Entry entry : p1.getRatings().entrySet()) { + v1 -= 11 - entry.getValue().getAverageRating(); } - double v2 = 0; - if (!p2.getRatings().isEmpty()) { - for (Entry entry : p2.getRatings().entrySet()) { - v2 -= 11 - entry.getValue().getAverageRating(); - } - } - if (v1 == v2) { - return -0; - } - return v2 > v1 ? 1 : -1; } + double v2 = 0; + if (!p2.getRatings().isEmpty()) { + for (Entry entry : p2.getRatings().entrySet()) { + v2 -= 11 - entry.getValue().getAverageRating(); + } + } + if (v1 == v2) { + return -0; + } + return v2 > v1 ? 1 : -1; }); UUID uuid = player.getUUID(); for (Plot p : plots) { @@ -123,25 +124,23 @@ import java.util.Map.Entry; return true; } }; - inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8")); - inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8")); - inventory.setItem(2, new PlotItemStack(35, (short) 1, 2, "2/8")); - inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8")); - inventory.setItem(4, new PlotItemStack(35, (short) 5, 4, "4/8")); - inventory.setItem(5, new PlotItemStack(35, (short) 9, 5, "5/8")); - inventory.setItem(6, new PlotItemStack(35, (short) 11, 6, "6/8")); - inventory.setItem(7, new PlotItemStack(35, (short) 10, 7, "7/8")); - inventory.setItem(8, new PlotItemStack(35, (short) 2, 8, "8/8")); + inventory.setItem(0, new PlotItemStack("brown_wool", 0, "0/8")); + inventory.setItem(1, new PlotItemStack("red_wool", 1, "1/8")); + inventory.setItem(2, new PlotItemStack("orange_wool", 2, "2/8")); + inventory.setItem(3, new PlotItemStack("yellow_wool", 3, "3/8")); + inventory.setItem(4, new PlotItemStack("lime_wool", 4, "4/8")); + inventory.setItem(5, new PlotItemStack("cyan_wool", 5, "5/8")); + inventory.setItem(6, new PlotItemStack("blue_wool", 6, "6/8")); + inventory.setItem(7, new PlotItemStack("purple_wool", 7, "7/8")); + inventory.setItem(8, new PlotItemStack("magenta_wool", 8, "8/8")); inventory.openInventory(); } }; if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - plot.getSettings().ratings = DBFunc.getRatings(plot); - run.run(); - } + TaskManager.runTaskAsync(() -> { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); }); return true; } @@ -167,26 +166,22 @@ import java.util.Map.Entry; return false; } final UUID uuid = player.getUUID(); - final Runnable run = new Runnable() { - @Override public void run() { - if (plot.getRatings().containsKey(uuid)) { - sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); - return; - } - Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); - if (result != null) { - plot.addRating(uuid, result); - sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); - } + final Runnable run = () -> { + if (plot.getRatings().containsKey(uuid)) { + sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); + return; + } + Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); + if (result != null) { + plot.addRating(uuid, result); + sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); } }; if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - plot.getSettings().ratings = DBFunc.getRatings(plot); - run.run(); - } + TaskManager.runTaskAsync(() -> { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java index 79a87b887..f5e21f34c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java @@ -7,8 +7,6 @@ import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; -import java.util.HashSet; - @CommandDeclaration(command = "relight", description = "Relight your plot", usage = "/plot relight", category = CommandCategory.DEBUG) public class Relight extends Command { public Relight() { @@ -23,17 +21,14 @@ import java.util.HashSet; C.NOT_IN_PLOT.send(player); return; } - HashSet regions = plot.getRegions(); final LocalBlockQueue queue = plot.getArea().getQueue(false); ChunkManager.chunkTask(plot, new RunnableVal() { @Override public void run(int[] value) { queue.fixChunkLighting(value[0], value[1]); } - }, new Runnable() { - @Override public void run() { - plot.refreshChunks(); - C.SET_BLOCK_ACTION_FINISHED.send(player); - } + }, () -> { + plot.refreshChunks(); + C.SET_BLOCK_ACTION_FINISHED.send(player); }, 5); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java index 110992543..7787518bb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java @@ -189,7 +189,6 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } - location.getWorld(); Collection plots = new ArrayList<>(); plots.add(plot); boolean result = SchematicHandler.manager.exportAll(plots, null, null, () -> { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java index 95166aa4a..0b9c47605 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java @@ -58,8 +58,6 @@ import java.util.HashSet; MainUtil.sendMessage(player, C.NEED_BLOCK); return true; } - String[] split = material.split(","); - // blocks = Configuration.BLOCKLIST.parseString(material); try { bucket = Configuration.BLOCK_BUCKET.parseString(material); @@ -100,11 +98,7 @@ import java.util.HashSet; current.setComponent(component, bucket); } MainUtil.sendMessage(player, C.GENERATING_COMPONENT); - GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override public void run() { - plot.removeRunning(); - } - }); + GlobalBlockQueue.IMP.addTask(() -> plot.removeRunning()); return true; } } @@ -114,8 +108,8 @@ import java.util.HashSet; } public boolean noArgs(PlotPlayer player) { - ArrayList newValues = new ArrayList<>(); - newValues.addAll(Arrays.asList("biome", "alias", "home", "flag")); + ArrayList newValues = + new ArrayList<>(Arrays.asList("biome", "alias", "home", "flag")); Plot plot = player.getCurrentPlot(); if (plot != null) { newValues.addAll( diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java index facea4952..98431a203 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java @@ -25,7 +25,7 @@ import java.util.Map.Entry; StringBuilder message = new StringBuilder(); message.append("&6What generator do you want?"); for (Entry> entry : SetupUtils.generators.entrySet()) { - if (entry.getKey().equals(PlotSquared.imp().getPluginName())) { + if (entry.getKey().equals(PlotSquared.get().IMP.getPluginName())) { message.append("\n&8 - &2").append(entry.getKey()).append(" (Default Generator)"); } else if (entry.getValue().isFull()) { message.append("\n&8 - &7").append(entry.getKey()).append(" (Plot Generator)"); @@ -73,8 +73,8 @@ import java.util.Map.Entry; MainUtil.sendMessage(player, "&cYou must choose a generator!" + prefix + StringMan .join(SetupUtils.generators.keySet(), prefix) - .replaceAll(PlotSquared.imp().getPluginName(), - "&2" + PlotSquared.imp().getPluginName())); + .replaceAll(PlotSquared.get().IMP.getPluginName(), + "&2" + PlotSquared.get().IMP.getPluginName())); sendMessage(player, C.SETUP_INIT); return false; } @@ -142,7 +142,7 @@ import java.util.Map.Entry; SetupUtils.generators.get(object.plotManager).getPlotGenerator() .processSetup(object); } else { - object.plotManager = PlotSquared.imp().getPluginName(); + object.plotManager = PlotSquared.get().IMP.getPluginName(); MainUtil.sendMessage(player, "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); MainUtil.sendMessage(player, @@ -282,7 +282,7 @@ import java.util.Map.Entry; } MainUtil.sendMessage(player, "&cThe world you specified already exists. After restarting, new terrain will use " - + PlotSquared.imp().getPluginName() + ", however you may need to " + + PlotSquared.get().IMP.getPluginName() + ", however you may need to " + "reset the world for it to generate correctly!"); } object.world = args[0]; @@ -318,7 +318,7 @@ import java.util.Map.Entry; messages.add(new PlotMessage("What generator do you want?").color("$6")); for (Entry> entry : SetupUtils.generators.entrySet()) { final PlotMessage plotMessage = new PlotMessage(" - ").color("$8"); - if (entry.getKey().equals(PlotSquared.imp().getPluginName())) { + if (entry.getKey().equals(PlotSquared.get().IMP.getPluginName())) { plotMessage.text(entry.getKey()).color("$8").tooltip("Select this generator") .color("$2").command("/plot setup generator " + entry.getKey()) .text(" (Default Generator)").color("$7"); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java index 80a96dfb6..f47e39a83 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java @@ -40,11 +40,7 @@ public class Swap extends SubCommand { C.PLOTWORLD_INCOMPATIBLE.send(player); return false; } - if (plot1.move(plot2, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, C.SWAP_SUCCESS); - } - }, true)) { + if (plot1.move(plot2, () -> MainUtil.sendMessage(player, C.SWAP_SUCCESS), true)) { return true; } else { MainUtil.sendMessage(player, C.SWAP_OVERLAP); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java index aed9c5ca6..b22dabc49 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java @@ -15,7 +15,10 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -63,9 +66,6 @@ import java.util.zip.ZipOutputStream; zis.closeEntry(); } return true; - } catch (FileNotFoundException e) { - e.printStackTrace(); - return false; } catch (IOException e) { e.printStackTrace(); return false; @@ -147,8 +147,8 @@ import java.util.zip.ZipOutputStream; } catch (InvalidConfigurationException | IOException e) { e.printStackTrace(); } - String manager = - worldConfig.getString("generator.plugin", PlotSquared.imp().getPluginName()); + String manager = worldConfig + .getString("generator.plugin", PlotSquared.get().IMP.getPluginName()); String generator = worldConfig.getString("generator.init", manager); int type = worldConfig.getInt("generator.type"); int terrain = worldConfig.getInt("generator.terrain"); @@ -161,11 +161,9 @@ import java.util.zip.ZipOutputStream; setup.step = new ConfigurationNode[0]; setup.world = world; SetupUtils.manager.setupWorld(setup); - GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "Done!"); - player.teleport(WorldUtil.IMP.getSpawn(world)); - } + GlobalBlockQueue.IMP.addTask(() -> { + MainUtil.sendMessage(player, "Done!"); + player.teleport(WorldUtil.IMP.getSpawn(world)); }); return true; } @@ -180,17 +178,15 @@ import java.util.zip.ZipOutputStream; return false; } final PlotManager manager = area.getPlotManager(); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try { - manager.exportTemplate(area); - } catch (Exception e) { // Must recover from any exception thrown a third party template manager - e.printStackTrace(); - MainUtil.sendMessage(player, "Failed: " + e.getMessage()); - return; - } - MainUtil.sendMessage(player, "Done!"); + TaskManager.runTaskAsync(() -> { + try { + manager.exportTemplate(area); + } catch (Exception e) { // Must recover from any exception thrown a third party template manager + e.printStackTrace(); + MainUtil.sendMessage(player, "Failed: " + e.getMessage()); + return; } + MainUtil.sendMessage(player, "Done!"); }); return true; default: diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java index 4a324e879..cf2f99bc9 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java @@ -70,7 +70,7 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; RunnableVal3 confirm, RunnableVal2 whenDone) { PlotArea area = player.getApplicablePlotArea(); - boolean chat = area == null ? false : area.PLOT_CHAT; + boolean chat = area != null && area.PLOT_CHAT; if (toggle(player, "disabletitles") != chat) { MainUtil.sendMessage(player, C.TOGGLE_ENABLED, command.toString()); } else { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java index f1a063dcb..bed09cdf8 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java @@ -95,8 +95,7 @@ import java.util.Set; return false; } MainUtil.sendMessage(null, "Collecting region data..."); - ArrayList plots = new ArrayList<>(); - plots.addAll(PlotSquared.get().getPlots(world)); + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots(world)); if (ExpireManager.IMP != null) { plots.removeAll(ExpireManager.IMP.getPendingExpired()); } @@ -198,11 +197,9 @@ import java.util.Set; } }; } else { - regenTask = new Runnable() { - @Override public void run() { - Trim.TASK = false; - player.sendMessage("Trim done!"); - } + regenTask = () -> { + Trim.TASK = false; + player.sendMessage("Trim done!"); }; } ChunkManager.manager.deleteRegionFiles(world, viable, regenTask); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java index ea87f1c8c..e9f5609ac 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java @@ -39,14 +39,12 @@ import com.github.intellectualsites.plotsquared.plot.util.*; } else { createRoad = true; } - Runnable runnable = new Runnable() { - @Override public void run() { - if (!plot.unlinkPlot(createRoad, createRoad)) { - MainUtil.sendMessage(player, "&cUnlink has been cancelled"); - return; - } - MainUtil.sendMessage(player, C.UNLINK_SUCCESS); + Runnable runnable = () -> { + if (!plot.unlinkPlot(createRoad, createRoad)) { + MainUtil.sendMessage(player, "&cUnlink has been cancelled"); + return; } + MainUtil.sendMessage(player, C.UNLINK_SUCCESS); }; if (hasConfirmation(player)) { CmdConfirm.addPending(player, "/plot unlink " + plot.getId(), runnable); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/C.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/C.java index d2b611b39..893c8e57e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/C.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/C.java @@ -915,18 +915,16 @@ public enum C { return m; } Map map = new LinkedHashMap<>(); - if (args.length > 0) { - for (int i = args.length - 1; i >= 0; i--) { - String arg = "" + args[i]; - if (arg == null || arg.isEmpty()) { - map.put("%s" + i, ""); - } else { - arg = C.color(arg); - map.put("%s" + i, arg); - } - if (i == 0) { - map.put("%s", arg); - } + for (int i = args.length - 1; i >= 0; i--) { + String arg = "" + args[i]; + if (arg.isEmpty()) { + map.put("%s" + i, ""); + } else { + arg = C.color(arg); + map.put("%s" + i, arg); + } + if (i == 0) { + map.put("%s", arg); } } m = StringMan.replaceFromMap(m, map); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java index 82992e265..7cf161be2 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java @@ -120,7 +120,8 @@ public class Config { * @param clazz * @return */ - public static Map getFields(Class clazz) { + public static Map getFields( + Class clazz) { HashMap map = new HashMap<>(); for (Field field : clazz.getFields()) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { @@ -142,7 +143,8 @@ public class Config { } StringBuilder m = new StringBuilder(); for (Object obj : listValue) { - m.append(System.lineSeparator() + spacing + "- " + toYamlString(obj, spacing)); + m.append(System.lineSeparator()).append(spacing).append("- ") + .append(toYamlString(obj, spacing)); } return m.toString(); } @@ -176,7 +178,7 @@ public class Config { if (value == null && field.getType() != ConfigBlock.class) { setAccessible(field); Class[] classes = clazz.getDeclaredClasses(); - for (Class current : classes) { + for (Class current : classes) { if (StringMan.isEqual(current.getSimpleName(), field.getName())) { field.set(instance, current.newInstance()); break; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java index 7e7df9124..d5943d1ac 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java @@ -45,7 +45,7 @@ public class MySQL extends Database { return this.connection; } - @Override public Connection openConnection() throws SQLException, ClassNotFoundException { + @Override public Connection openConnection() throws SQLException { if (checkConnection()) { return this.connection; } @@ -69,7 +69,7 @@ public class MySQL extends Database { return true; } - @Override public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { + @Override public ResultSet querySQL(String query) throws SQLException { if (checkConnection()) { openConnection(); } @@ -78,7 +78,7 @@ public class MySQL extends Database { } } - @Override public int updateSQL(String query) throws SQLException, ClassNotFoundException { + @Override public int updateSQL(String query) throws SQLException { if (checkConnection()) { openConnection(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java index 66a21174d..e91fd3816 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java @@ -121,42 +121,40 @@ import java.util.concurrent.atomic.AtomicInteger; } catch (SQLException e) { e.printStackTrace(); } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - long last = System.currentTimeMillis(); - while (true) { - if (SQLManager.this.closed) { - break; + TaskManager.runTaskAsync(() -> { + long last = System.currentTimeMillis(); + while (true) { + if (SQLManager.this.closed) { + break; + } + boolean hasTask = + !globalTasks.isEmpty() || !playerTasks.isEmpty() || !plotTasks.isEmpty() + || !clusterTasks.isEmpty(); + if (hasTask) { + if (SQLManager.this.mySQL && System.currentTimeMillis() - last > 550000 + || !isValid()) { + last = System.currentTimeMillis(); + reconnect(); } - boolean hasTask = - !globalTasks.isEmpty() || !playerTasks.isEmpty() || !plotTasks.isEmpty() - || !clusterTasks.isEmpty(); - if (hasTask) { - if (SQLManager.this.mySQL && System.currentTimeMillis() - last > 550000 - || !isValid()) { - last = System.currentTimeMillis(); - reconnect(); - } - if (!sendBatch()) { - try { - if (!getNotifyTasks().isEmpty()) { - for (Runnable task : getNotifyTasks()) { - TaskManager.runTask(task); - } - getNotifyTasks().clear(); - } - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else { + if (!sendBatch()) { try { - Thread.sleep(1000); + if (!getNotifyTasks().isEmpty()) { + for (Runnable task : getNotifyTasks()) { + TaskManager.runTask(task); + } + getNotifyTasks().clear(); + } + Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } + } else { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } } } }); @@ -515,92 +513,74 @@ import java.util.concurrent.atomic.AtomicInteger; } @Override public void createPlotsAndData(final List myList, final Runnable whenDone) { - addGlobalTask(new Runnable() { - @Override public void run() { - try { - // Create the plots - createPlots(myList, new Runnable() { - @Override public void run() { - try { - // Creating datastructures - HashMap plotMap = new HashMap<>(); - for (Plot plot : myList) { - plotMap.put(plot.getId(), plot); - } - ArrayList settings = new ArrayList<>(); - final ArrayList helpers = new ArrayList<>(); - final ArrayList trusted = new ArrayList<>(); - final ArrayList denied = new ArrayList<>(); + addGlobalTask(() -> { + try { + // Create the plots + createPlots(myList, () -> { + try { + // Creating datastructures + HashMap plotMap = new HashMap<>(); + for (Plot plot : myList) { + plotMap.put(plot.getId(), plot); + } + ArrayList settings = new ArrayList<>(); + final ArrayList helpers = new ArrayList<>(); + final ArrayList trusted = new ArrayList<>(); + final ArrayList denied = new ArrayList<>(); - // Populating structures - try (PreparedStatement stmt = SQLManager.this.connection - .prepareStatement(SQLManager.this.GET_ALL_PLOTS); - ResultSet result = stmt.executeQuery()) { - while (result.next()) { - int id = result.getInt("id"); - int x = result.getInt("plot_id_x"); - int y = result.getInt("plot_id_z"); - PlotId plotId = new PlotId(x, y); - Plot plot = plotMap.get(plotId); - if (plot != null) { - settings.add(new SettingsPair(id, plot.getSettings())); - for (UUID uuid : plot.getDenied()) { - denied.add(new UUIDPair(id, uuid)); - } - for (UUID uuid : plot.getMembers()) { - trusted.add(new UUIDPair(id, uuid)); - } - for (UUID uuid : plot.getTrusted()) { - helpers.add(new UUIDPair(id, uuid)); - } - } + // Populating structures + try (PreparedStatement stmt = SQLManager.this.connection + .prepareStatement(SQLManager.this.GET_ALL_PLOTS); + ResultSet result = stmt.executeQuery()) { + while (result.next()) { + int id = result.getInt("id"); + int x = result.getInt("plot_id_x"); + int y = result.getInt("plot_id_z"); + PlotId plotId = new PlotId(x, y); + Plot plot = plotMap.get(plotId); + if (plot != null) { + settings.add(new SettingsPair(id, plot.getSettings())); + for (UUID uuid : plot.getDenied()) { + denied.add(new UUIDPair(id, uuid)); } - } - createSettings(settings, new Runnable() { - @Override public void run() { - createTiers(helpers, "helpers", new Runnable() { - @Override public void run() { - createTiers(trusted, "trusted", new Runnable() { - @Override public void run() { - createTiers(denied, "denied", - new Runnable() { - @Override public void run() { - try { - SQLManager.this.connection - .commit(); - } catch (SQLException e) { - e.printStackTrace(); - } - if (whenDone != null) { - whenDone.run(); - } - } - }); - } - }); - } - }); + for (UUID uuid : plot.getMembers()) { + trusted.add(new UUIDPair(id, uuid)); + } + for (UUID uuid : plot.getTrusted()) { + helpers.add(new UUIDPair(id, uuid)); } - }); - } catch (SQLException e) { - e.printStackTrace(); - PlotSquared.debug("&7[WARN] Failed to set all helpers for plots"); - try { - SQLManager.this.connection.commit(); - } catch (SQLException e1) { - e1.printStackTrace(); } } } - }); - } catch (Exception e) { - e.printStackTrace(); - PlotSquared.debug("&7[WARN] Failed to set all helpers for plots"); - try { - SQLManager.this.connection.commit(); - } catch (SQLException e1) { - e1.printStackTrace(); + createSettings(settings, () -> createTiers(helpers, "helpers", + () -> createTiers(trusted, "trusted", + () -> createTiers(denied, "denied", () -> { + try { + SQLManager.this.connection.commit(); + } catch (SQLException e) { + e.printStackTrace(); + } + if (whenDone != null) { + whenDone.run(); + } + })))); + } catch (SQLException e) { + e.printStackTrace(); + PlotSquared.debug("&7[WARN] Failed to set all helpers for plots"); + try { + SQLManager.this.connection.commit(); + } catch (SQLException e1) { + e1.printStackTrace(); + } } + }); + } catch (Exception e) { + e.printStackTrace(); + PlotSquared.debug("&7[WARN] Failed to set all helpers for plots"); + try { + SQLManager.this.connection.commit(); + } catch (SQLException e1) { + e1.printStackTrace(); } } }); @@ -676,7 +656,7 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(i * 5 + 1, plot.getId().x); stmt.setInt(i * 5 + 2, plot.getId().y); try { - stmt.setString(i * 5 + 3, plot.owner.toString()); + stmt.setString(i * 5 + 3, plot.guessOwner().toString()); } catch (SQLException ignored) { stmt.setString(i * 5 + 3, everyone.toString()); } @@ -690,7 +670,7 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(i * 6 + 2, plot.getId().x); stmt.setInt(i * 6 + 3, plot.getId().y); try { - stmt.setString(i * 6 + 4, plot.owner.toString()); + stmt.setString(i * 6 + 4, plot.guessOwner().toString()); } catch (SQLException ignored) { stmt.setString(i * 6 + 4, everyone.toString()); } @@ -701,7 +681,7 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public void setSQL(PreparedStatement stmt, Plot plot) throws SQLException { stmt.setInt(1, plot.getId().x); stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.owner.toString()); + stmt.setString(3, plot.guessOwner().toString()); stmt.setString(4, plot.getArea().toString()); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); @@ -929,11 +909,7 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(1, pair.id); } }; - addGlobalTask(new Runnable() { - @Override public void run() { - setBulk(myList, mod, whenDone); - } - }); + addGlobalTask(() -> setBulk(myList, mod, whenDone)); } public void createEmptySettings(final ArrayList myList, final Runnable whenDone) { @@ -977,20 +953,15 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(1, id); } }; - addGlobalTask(new Runnable() { - @Override public void run() { - setBulk(myList, mod, whenDone); - } - }); + addGlobalTask(() -> setBulk(myList, mod, whenDone)); } public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) { - final long timestamp = plot.getTimestamp(); addPlotTask(plot, new UniqueStatement("createPlotSafe_" + plot.hashCode()) { @Override public void set(PreparedStatement stmt) throws SQLException { stmt.setInt(1, plot.getId().x); stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.owner.toString()); + stmt.setString(3, plot.guessOwner().toString()); stmt.setString(4, plot.getArea().toString()); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); stmt.setString(6, plot.getArea().toString()); @@ -1057,7 +1028,7 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public void set(PreparedStatement stmt) throws SQLException { stmt.setInt(1, plot.getId().x); stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.owner.toString()); + stmt.setString(3, plot.guessOwner().toString()); stmt.setString(4, plot.getArea().toString()); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); } @@ -1351,7 +1322,7 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public void delete(final Plot plot) { PlotSquared.debug( "Deleting plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: " - + plot.owner + " Index: " + plot.temp); + + plot.guessOwner() + " Index: " + plot.temp); deleteSettings(plot); deleteDenied(plot); deleteHelpers(plot); @@ -1379,7 +1350,7 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public void createPlotSettings(final int id, Plot plot) { PlotSquared.debug( "Creating plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: " - + plot.owner + " Index: " + id); + + plot.guessOwner() + " Index: " + id); addPlotTask(plot, new UniqueStatement("createPlotSettings") { @Override public void set(PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); @@ -1685,8 +1656,8 @@ import java.util.concurrent.atomic.AtomicInteger; time = System.currentTimeMillis() + id; } } - Plot p = new Plot(plot_id, user, new HashSet(), new HashSet(), - new HashSet(), "", null, null, null, + Plot p = new Plot(plot_id, user, new HashSet<>(), new HashSet<>(), + new HashSet<>(), "", null, null, null, new boolean[] {false, false, false, false}, time, id); HashMap map = newPlots.get(areaid); if (map != null) { @@ -2036,103 +2007,96 @@ import java.util.concurrent.atomic.AtomicInteger; * Purge all plots with the following database IDs */ @Override public void purgeIds(final Set uniqueIds) { - addGlobalTask(new Runnable() { - @Override public void run() { - if (!uniqueIds.isEmpty()) { - try { - ArrayList uniqueIdsList = new ArrayList(uniqueIds); - String stmt_prefix = ""; - int size = uniqueIdsList.size(); - int packet = 990; - int amount = size / packet; - int count = 0; - int last = -1; - for (int j = 0; j <= amount; j++) { - PlotSquared.debug("Purging " + (j * packet) + " / " + size); - List subList = - uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet)); - if (subList.isEmpty()) { - break; - } - StringBuilder idstr2 = new StringBuilder(""); - stmt_prefix = ""; - for (Integer id : subList) { - idstr2.append(stmt_prefix).append(id); - stmt_prefix = " OR `id` = "; - } - stmt_prefix = ""; - StringBuilder idstr = new StringBuilder(); - for (Integer id : subList) { - idstr.append(stmt_prefix).append(id); - stmt_prefix = " OR `plot_plot_id` = "; - } - PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_helpers` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_denied` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_settings` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_trusted` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix + "plot` WHERE `id` = " - + idstr2); - stmt.executeUpdate(); - stmt.close(); - commit(); + addGlobalTask(() -> { + if (!uniqueIds.isEmpty()) { + try { + ArrayList uniqueIdsList = new ArrayList<>(uniqueIds); + String stmt_prefix = ""; + int size = uniqueIdsList.size(); + int packet = 990; + int amount = size / packet; + for (int j = 0; j <= amount; j++) { + PlotSquared.debug("Purging " + (j * packet) + " / " + size); + List subList = + uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet)); + if (subList.isEmpty()) { + break; } - } catch (SQLException e) { - e.printStackTrace(); - PlotSquared.debug("&c[ERROR] FAILED TO PURGE PLOTS!"); - return; + StringBuilder idstr2 = new StringBuilder(""); + stmt_prefix = ""; + for (Integer id : subList) { + idstr2.append(stmt_prefix).append(id); + stmt_prefix = " OR `id` = "; + } + stmt_prefix = ""; + StringBuilder idstr = new StringBuilder(); + for (Integer id : subList) { + idstr.append(stmt_prefix).append(id); + stmt_prefix = " OR `plot_plot_id` = "; + } + PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_helpers` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_denied` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_settings` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_trusted` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + "plot` WHERE `id` = " + + idstr2); + stmt.executeUpdate(); + stmt.close(); + commit(); } + } catch (SQLException e) { + e.printStackTrace(); + PlotSquared.debug("&c[ERROR] FAILED TO PURGE PLOTS!"); + return; } - PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); } + PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); }); } @Override public void purge(final PlotArea area, final Set plots) { - addGlobalTask(new Runnable() { - @Override public void run() { - try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix - + "plot` WHERE `world` = ?")) { - stmt.setString(1, area.toString()); - Set ids; - try (ResultSet r = stmt.executeQuery()) { - ids = new HashSet<>(); - while (r.next()) { - PlotId plot_id = - new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); - if (plots.contains(plot_id)) { - ids.add(r.getInt("id")); - } + addGlobalTask(() -> { + try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix + + "plot` WHERE `world` = ?")) { + stmt.setString(1, area.toString()); + Set ids; + try (ResultSet r = stmt.executeQuery()) { + ids = new HashSet<>(); + while (r.next()) { + PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); + if (plots.contains(plot_id)) { + ids.add(r.getInt("id")); } } - purgeIds(ids); - } catch (SQLException e) { - e.printStackTrace(); - PlotSquared.debug("&c[ERROR] FAILED TO PURGE AREA '" + area + "'!"); - } - for (Iterator iterator = plots.iterator(); iterator.hasNext(); ) { - PlotId plotId = iterator.next(); - iterator.remove(); - PlotId id = new PlotId(plotId.x, plotId.y); - area.removePlot(id); } + purgeIds(ids); + } catch (SQLException e) { + e.printStackTrace(); + PlotSquared.debug("&c[ERROR] FAILED TO PURGE AREA '" + area + "'!"); + } + for (Iterator iterator = plots.iterator(); iterator.hasNext(); ) { + PlotId plotId = iterator.next(); + iterator.remove(); + PlotId id = new PlotId(plotId.x, plotId.y); + area.removePlot(id); } }); } @@ -2523,11 +2487,7 @@ import java.util.concurrent.atomic.AtomicInteger; } resultSet.close(); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - result.run(metaMap); - } - }); + TaskManager.runTaskAsync(() -> result.run(metaMap)); } }); @@ -2591,11 +2551,8 @@ import java.util.concurrent.atomic.AtomicInteger; } cluster = new PlotCluster(null, pos1, pos2, user, id); clusters.put(id, cluster); - Set set = newClusters.get(areaid); - if (set == null) { - set = new HashSet<>(); - newClusters.put(areaid, set); - } + Set set = + newClusters.computeIfAbsent(areaid, k -> new HashSet<>()); set.add(cluster); } //Getting helpers @@ -2973,10 +2930,10 @@ import java.util.concurrent.atomic.AtomicInteger; continue; } // owner - if (!plot.owner.equals(dataPlot.owner)) { - PlotSquared - .debug("&8 - &7Setting owner: " + plot + " -> " + MainUtil.getName(plot.owner)); - setOwner(plot, plot.owner); + if (!plot.guessOwner().equals(dataPlot.guessOwner())) { + PlotSquared.debug( + "&8 - &7Setting owner: " + plot + " -> " + MainUtil.getName(plot.guessOwner())); + setOwner(plot, plot.guessOwner()); } // trusted if (!plot.getTrusted().equals(dataPlot.getTrusted())) { @@ -3069,87 +3026,83 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min, final PlotId max) { - addGlobalTask(new Runnable() { - @Override public void run() { - if (min == null) { - try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "UPDATE `" + SQLManager.this.prefix - + "plot` SET `world` = ? WHERE `world` = ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "UPDATE `" + SQLManager.this.prefix - + "cluster` SET `world` = ? WHERE `world` = ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } else { - try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "UPDATE `" + SQLManager.this.prefix - + "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.setInt(3, min.x); - stmt.setInt(4, max.x); - stmt.setInt(5, min.y); - stmt.setInt(6, max.y); - stmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "UPDATE `" + SQLManager.this.prefix - + "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.setInt(3, max.x); - stmt.setInt(4, max.y); - stmt.setInt(5, min.x); - stmt.setInt(6, min.y); - stmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } + addGlobalTask(() -> { + if (min == null) { + try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "UPDATE `" + SQLManager.this.prefix + + "plot` SET `world` = ? WHERE `world` = ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "UPDATE `" + SQLManager.this.prefix + + "cluster` SET `world` = ? WHERE `world` = ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } else { + try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "UPDATE `" + SQLManager.this.prefix + + "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.setInt(3, min.x); + stmt.setInt(4, max.x); + stmt.setInt(5, min.y); + stmt.setInt(6, max.y); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "UPDATE `" + SQLManager.this.prefix + + "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.setInt(3, max.x); + stmt.setInt(4, max.y); + stmt.setInt(5, min.x); + stmt.setInt(6, min.y); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); } } }); } @Override public void replaceUUID(final UUID old, final UUID now) { - addGlobalTask(new Runnable() { - @Override public void run() { - try (Statement stmt = SQLManager.this.connection.createStatement()) { - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now - .toString() + "' WHERE `owner` = '" + old.toString() + '\''); - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "cluster_helpers` SET `user_uuid` = '" - + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '" - + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now - .toString() + "' WHERE `owner` = '" + old.toString() + '\''); - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '" - + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '" - + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); - stmt.executeUpdate( - "UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '" - + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); - } catch (SQLException e) { - e.printStackTrace(); - } + addGlobalTask(() -> { + try (Statement stmt = SQLManager.this.connection.createStatement()) { + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now + .toString() + "' WHERE `owner` = '" + old.toString() + '\''); + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "cluster_helpers` SET `user_uuid` = '" + + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '" + + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now.toString() + + "' WHERE `owner` = '" + old.toString() + '\''); + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '" + now + .toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '" + now + .toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + stmt.executeUpdate( + "UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '" + now + .toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + } catch (SQLException e) { + e.printStackTrace(); } }); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java index c52b77f44..d9f321738 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java @@ -146,7 +146,7 @@ public class FlagManager { * @return */ public static V getPlotFlagRaw(Plot plot, Flag flag) { - if (plot.owner == null) { + if (plot.guessOwner() == null) { return null; } return getSettingFlag(plot.getArea(), plot.getSettings(), flag); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java index f69ea6785..848d12f55 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java @@ -244,7 +244,6 @@ public class ClassicPlotManager extends SquarePlotManager { Location bot = plot.getExtendedBottomAbs() .subtract(plot.getMerged(3) ? 0 : 1, 0, plot.getMerged(0) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - PseudoRandom random = new PseudoRandom(); LocalBlockQueue queue = plotArea.getQueue(false); int y = dpw.WALL_HEIGHT + 1; if (!plot.getMerged(0)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java index bccb61d32..c6c509bac 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java @@ -6,12 +6,10 @@ import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; import com.sk89q.worldedit.world.block.BaseBlock; -import java.util.HashMap; - public class HybridGen extends IndependentPlotGenerator { @Override public String getName() { - return PlotSquared.imp().getPluginName(); + return PlotSquared.get().IMP.getPluginName(); } private void placeSchem(HybridPlotWorld world, ScopedLocalBlockQueue result, short relativeX, @@ -41,8 +39,6 @@ public class HybridGen extends IndependentPlotGenerator { } // Coords Location min = result.getMin(); - int cx = min.getX() >> 4; - int cz = min.getZ() >> 4; int bx = (min.getX()) - hpw.ROAD_OFFSET_X; int bz = (min.getZ()) - hpw.ROAD_OFFSET_Z; short rbx; @@ -86,7 +82,6 @@ public class HybridGen extends IndependentPlotGenerator { } } // generation - HashMap sch = hpw.G_SCH; for (short x = 0; x < 16; x++) { if (gx[x]) { for (short z = 0; z < 16; z++) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java index 1f6429dbd..bae538497 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java @@ -197,12 +197,10 @@ public class HybridPlotManager extends ClassicPlotManager { // And finally set the schematic, the y value is unimportant for this function pastePlotSchematic(dpw, queue, bot, top); } - }, new Runnable() { - @Override public void run() { - queue.enqueue(); - // And notify whatever called this when plot clearing is done - GlobalBlockQueue.IMP.addTask(whenDone); - } + }, () -> { + queue.enqueue(); + // And notify whatever called this when plot clearing is done + GlobalBlockQueue.IMP.addTask(whenDone); }, 10); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java index 30d7ea22f..2648ba863 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java @@ -212,11 +212,7 @@ public abstract class HybridUtils { PlotSquared.debug("&d - Potentially skipping 1024 chunks"); PlotSquared.debug("&d - TODO: recommend chunkster if corrupt"); } - GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override public void run() { - TaskManager.runTaskLater(task, 20); - } - }); + GlobalBlockQueue.IMP.addTask(() -> TaskManager.runTaskLater(task, 20)); } }); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java index d47d7a94f..4a398cabc 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java @@ -158,23 +158,21 @@ public class PlotListener { if (titles) { if (!C.TITLE_ENTERED_PLOT.s().isEmpty() || !C.TITLE_ENTERED_PLOT_SUB.s() .isEmpty()) { - TaskManager.runTaskLaterAsync(new Runnable() { - @Override public void run() { - Plot lastPlot = player.getMeta(PlotPlayer.META_LAST_PLOT); - if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { - Map replacements = new HashMap<>(); - replacements.put("%x%", String.valueOf(lastPlot.getId().x)); - replacements.put("%z%", lastPlot.getId().y + ""); - replacements.put("%world%", plot.getArea().toString()); - replacements.put("%greeting%", greeting); - replacements.put("%alias", plot.toString()); - replacements.put("%s", MainUtil.getName(plot.owner)); - String main = StringMan - .replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements); - String sub = StringMan - .replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements); - AbstractTitle.sendTitle(player, main, sub); - } + TaskManager.runTaskLaterAsync(() -> { + Plot lastPlot = player.getMeta(PlotPlayer.META_LAST_PLOT); + if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { + Map replacements = new HashMap<>(); + replacements.put("%x%", String.valueOf(lastPlot.getId().x)); + replacements.put("%z%", lastPlot.getId().y + ""); + replacements.put("%world%", plot.getArea().toString()); + replacements.put("%greeting%", greeting); + replacements.put("%alias", plot.toString()); + replacements.put("%s", MainUtil.getName(plot.guessOwner())); + String main = + StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements); + String sub = StringMan + .replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements); + AbstractTitle.sendTitle(player, main, sub); } }, 20); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java index 8f0e344ce..880de7dc3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java @@ -805,14 +805,12 @@ public class Plot { Runnable run = new Runnable() { @Override public void run() { if (queue.isEmpty()) { - Runnable run = new Runnable() { - @Override public void run() { - for (RegionWrapper region : regions) { - Location[] corners = region.getCorners(getWorldName()); - ChunkManager.manager.clearAllEntities(corners[0], corners[1]); - } - TaskManager.runTask(whenDone); + Runnable run = () -> { + for (RegionWrapper region : regions) { + Location[] corners = region.getCorners(getWorldName()); + ChunkManager.manager.clearAllEntities(corners[0], corners[1]); } + TaskManager.runTask(whenDone); }; for (Plot current : plots) { if (isDelete || current.owner == null) { @@ -927,11 +925,9 @@ public class Plot { current.setMerged(merged); } if (createSign) { - GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override public void run() { - for (Plot current : plots) { - current.setSign(MainUtil.getName(current.owner)); - } + GlobalBlockQueue.IMP.addTask(() -> { + for (Plot current : plots) { + current.setSign(MainUtil.getName(current.owner)); } }); } @@ -950,11 +946,7 @@ public class Plot { if (!isLoaded()) return; if (!PlotSquared.get().isMainThread(Thread.currentThread())) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - Plot.this.setSign(name); - } - }); + TaskManager.runTask(() -> Plot.this.setSign(name)); return; } PlotManager manager = this.area.getPlotManager(); @@ -1044,13 +1036,11 @@ public class Plot { return false; } final Set plots = this.getConnectedPlots(); - this.clear(false, true, new Runnable() { - @Override public void run() { - for (Plot current : plots) { - current.unclaim(); - } - TaskManager.runTask(whenDone); + this.clear(false, true, () -> { + for (Plot current : plots) { + current.unclaim(); } + TaskManager.runTask(whenDone); }); return true; } @@ -1483,12 +1473,10 @@ public class Plot { this.getDenied().clear(); this.settings = new PlotSettings(); if (this.area.addPlot(this)) { - DBFunc.createPlotAndSettings(this, new Runnable() { - @Override public void run() { - PlotArea plotworld = Plot.this.area; - if (notify && plotworld.AUTO_MERGE) { - Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true); - } + DBFunc.createPlotAndSettings(this, () -> { + PlotArea plotworld = Plot.this.area; + if (notify && plotworld.AUTO_MERGE) { + Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true); } }); return true; @@ -1837,16 +1825,14 @@ public class Plot { TaskManager.runTask(whenDone); } } else { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - String name = Plot.this.id + "," + Plot.this.area + ',' + MainUtil - .getName(Plot.this.owner); - boolean result = SchematicHandler.manager.save(value, - Settings.Paths.SCHEMATICS + File.separator + name + ".schematic"); - if (whenDone != null) { - whenDone.value = result; - TaskManager.runTask(whenDone); - } + TaskManager.runTaskAsync(() -> { + String name = Plot.this.id + "," + Plot.this.area + ',' + MainUtil + .getName(Plot.this.owner); + boolean result = SchematicHandler.manager.save(value, + Settings.Paths.SCHEMATICS + File.separator + name + ".schematic"); + if (whenDone != null) { + whenDone.value = result; + TaskManager.runTask(whenDone); } }); } @@ -2556,9 +2542,7 @@ public class Plot { } Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); - for (PlotId id : MainUtil.getPlotSelectionIds(bot, top)) { - visited.add(id); - } + visited.addAll(MainUtil.getPlotSelectionIds(bot, top)); for (int x = bot.x; x <= top.x; x++) { Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); if (plot.getMerged(2)) { @@ -2625,12 +2609,10 @@ public class Plot { * - Usually called when the plot state changes (unclaimed/claimed/flag change etc) */ public void reEnter() { - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - for (PlotPlayer pp : Plot.this.getPlayersInPlot()) { - PlotListener.plotExit(pp, Plot.this); - PlotListener.plotEntry(pp, Plot.this); - } + TaskManager.runTaskLater(() -> { + for (PlotPlayer pp : Plot.this.getPlayersInPlot()) { + PlotListener.plotExit(pp, Plot.this); + PlotListener.plotEntry(pp, Plot.this); } }, 1); } @@ -2686,17 +2668,15 @@ public class Plot { MainUtil.sendMessage(player, C.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + ""); final String name = player.getName(); TaskManager.TELEPORT_QUEUE.add(name); - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - if (!TaskManager.TELEPORT_QUEUE.contains(name)) { - MainUtil.sendMessage(player, C.TELEPORT_FAILED); - return; - } - TaskManager.TELEPORT_QUEUE.remove(name); - if (player.isOnline()) { - MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); - player.teleport(location); - } + TaskManager.runTaskLater(() -> { + if (!TaskManager.TELEPORT_QUEUE.contains(name)) { + MainUtil.sendMessage(player, C.TELEPORT_FAILED); + return; + } + TaskManager.TELEPORT_QUEUE.remove(name); + if (player.isOnline()) { + MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); + player.teleport(location); } }, Settings.Teleport.DELAY * 20); return true; @@ -2883,11 +2863,8 @@ public class Plot { final Location pos2 = corners[1]; Location newPos = pos1.clone().add(offsetX, 0, offsetZ); newPos.setWorld(destination.getWorldName()); - ChunkManager.manager.copyRegion(pos1, pos2, newPos, new Runnable() { - @Override public void run() { - ChunkManager.manager.regenerateRegion(pos1, pos2, false, task); - } - }); + ChunkManager.manager.copyRegion(pos1, pos2, newPos, + () -> ChunkManager.manager.regenerateRegion(pos1, pos2, false, task)); } }; Runnable swap = new Runnable() { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java index a8e1a3bb4..f1a05547d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java @@ -179,7 +179,7 @@ public abstract class PlotArea { } public Set getClusters() { - return this.clusters == null ? new HashSet() : this.clusters.getAll(); + return this.clusters == null ? new HashSet<>() : this.clusters.getAll(); } /** @@ -496,7 +496,7 @@ public abstract class PlotArea { final HashSet myPlots = new HashSet<>(); foreachPlotAbs(new RunnableVal() { @Override public void run(Plot value) { - if (uuid.equals(value.owner)) { + if (uuid.equals(value.guessOwner())) { myPlots.add(value); } } @@ -657,12 +657,7 @@ public abstract class PlotArea { public Set getBasePlots() { HashSet myPlots = new HashSet<>(getPlots()); - Iterator iterator = myPlots.iterator(); - while (iterator.hasNext()) { - if (!iterator.next().isBasePlot()) { - iterator.remove(); - } - } + myPlots.removeIf(plot -> !plot.isBasePlot()); return myPlots; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java index 79521908e..4f517b746 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java @@ -78,7 +78,7 @@ public abstract class PlotBlock implements ConfigurationSerializable { public static PlotBlock get(@NonNull final Object type) { if (blockRegistry == null) { - blockRegistry = PlotSquared.imp().getBlockRegistry(); + blockRegistry = PlotSquared.get().IMP.getBlockRegistry(); if (blockRegistry == null) { throw new UnsupportedOperationException( "The PlotSquared implementation has not registered a custom block registry." @@ -99,7 +99,7 @@ public abstract class PlotBlock implements ConfigurationSerializable { public T to(@NonNull final Class clazz) { if (blockRegistry == null) { - blockRegistry = PlotSquared.imp().getBlockRegistry(); + blockRegistry = PlotSquared.get().IMP.getBlockRegistry(); if (blockRegistry == null) { throw new UnsupportedOperationException( "The PlotSquared implementation has not registered a custom block registry." diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotHandler.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotHandler.java index 4faa17b76..43cf31f6c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotHandler.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotHandler.java @@ -5,7 +5,7 @@ import java.util.UUID; public class PlotHandler { public static boolean sameOwners(final Plot plot1, final Plot plot2) { - if (plot1.owner == null || plot2.owner == null) { + if (plot1.guessOwner() == null || plot2.guessOwner() == null) { return false; } final Set owners = plot1.getOwners(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotMessage.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotMessage.java index 47069a38e..9d2713e35 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotMessage.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotMessage.java @@ -5,6 +5,8 @@ import com.github.intellectualsites.plotsquared.plot.config.C; import com.github.intellectualsites.plotsquared.plot.object.chat.PlainChatManager; import com.github.intellectualsites.plotsquared.plot.util.ChatManager; +import java.util.Arrays; + public class PlotMessage { private Object builder; @@ -14,8 +16,8 @@ public class PlotMessage { reset(ChatManager.manager); } catch (Throwable e) { PlotSquared.debug( - PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + PlotSquared - .get().IMP.getServerVersion()); + PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + Arrays + .toString(PlotSquared.get().IMP.getServerVersion())); ChatManager.manager = new PlainChatManager(); reset(ChatManager.manager); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java index 23224c74c..a70b662d4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java @@ -222,7 +222,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { return getClusterCount(getLocation().getWorld()); } final AtomicInteger count = new AtomicInteger(0); - final UUID uuid = getUUID(); PlotSquared.get().foreachPlotArea(new RunnableVal() { @Override public void run(PlotArea value) { for (PlotCluster cluster : value.getClusters()) { @@ -259,7 +258,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } public int getClusterCount(String world) { - UUID uuid = getUUID(); int count = 0; for (PlotArea area : PlotSquared.get().getPlotAreas(world)) { for (PlotCluster cluster : area.getClusters()) { @@ -569,31 +567,27 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { final Location loc = new Location(plot.getWorldName(), x, y, z); if (plot.isLoaded()) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - if (getMeta("teleportOnLogin", true)) { - teleport(loc); - sendMessage(C.TELEPORTED_TO_PLOT.f() - + " (quitLoc) (" + plotX + "," - + plotZ + ")"); - } + TaskManager.runTask(() -> { + if (getMeta("teleportOnLogin", true)) { + teleport(loc); + sendMessage(C.TELEPORTED_TO_PLOT.f() + + " (quitLoc) (" + plotX + "," + + plotZ + ")"); } }); } else if (!PlotSquared.get() .isMainThread(Thread.currentThread())) { if (getMeta("teleportOnLogin", true)) { if (plot.teleportPlayer(PlotPlayer.this)) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - if (getMeta("teleportOnLogin", - true)) { - teleport(loc); - sendMessage( - C.TELEPORTED_TO_PLOT.f() - + " (quitLoc-unloaded) (" - + plotX + "," - + plotZ + ")"); - } + TaskManager.runTask(() -> { + if (getMeta("teleportOnLogin", + true)) { + teleport(loc); + sendMessage( + C.TELEPORTED_TO_PLOT.f() + + " (quitLoc-unloaded) (" + + plotX + "," + plotZ + + ")"); } }); } @@ -618,9 +612,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } public void removePersistentMeta(String key) { - if (this.metaMap.containsKey(key)) { - this.metaMap.remove(key); - } + this.metaMap.remove(key); if (Settings.Enabled_Components.PERSISTENT_META) { DBFunc.removePersistentMeta(getUUID(), key); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java index 2eadd85ff..bd4505643 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java @@ -14,12 +14,6 @@ import java.util.*; */ public class PlotSettings { - /** - * Merged plots. - * - * @deprecated Raw access - */ - @Deprecated public boolean[] merged = new boolean[] {false, false, false, false}; /** * Plot alias. * @@ -32,20 +26,24 @@ public class PlotSettings { * @deprecated Raw access */ @Deprecated public List comments = null; - /** * The ratings for a plot. * * @deprecated Raw access */ @Deprecated public HashMap ratings; - /** * Flags. * * @deprecated Raw access */ @Deprecated public HashMap, Object> flags = new HashMap<>(); + /** + * Merged plots. + * + * @deprecated Raw access + */ + @Deprecated private boolean[] merged = new boolean[] {false, false, false, false}; /** * Home Position. * diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/CommentInbox.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/CommentInbox.java index 30d9b1230..999eb0a49 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/CommentInbox.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/CommentInbox.java @@ -14,10 +14,8 @@ public abstract class CommentInbox { public boolean canRead(Plot plot, PlotPlayer player) { if (Permissions.hasPermission(player, "plots.inbox.read." + toString(), true)) { - if (plot.isOwner(player.getUUID()) || Permissions - .hasPermission(player, "plots.inbox.read." + toString() + ".other", true)) { - return true; - } + return plot.isOwner(player.getUUID()) || Permissions + .hasPermission(player, "plots.inbox.read." + toString() + ".other", true); } return false; } @@ -33,10 +31,8 @@ public abstract class CommentInbox { public boolean canModify(Plot plot, PlotPlayer player) { if (Permissions.hasPermission(player, "plots.inbox.modify." + toString(), true)) { - if (plot.isOwner(player.getUUID()) || Permissions - .hasPermission(player, "plots.inbox.modify." + toString() + ".other", true)) { - return true; - } + return plot.isOwner(player.getUUID()) || Permissions + .hasPermission(player, "plots.inbox.modify." + toString() + ".other", true); } return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxOwner.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxOwner.java index d15f194ba..1c681627e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxOwner.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxOwner.java @@ -27,7 +27,7 @@ public class InboxOwner extends CommentInbox { plot.getSettings().addComment(comment); } } else { - plot.getSettings().setComments(new ArrayList()); + plot.getSettings().setComments(new ArrayList<>()); } TaskManager.runTask(whenDone); } @@ -36,7 +36,7 @@ public class InboxOwner extends CommentInbox { } @Override public boolean addComment(Plot plot, PlotComment comment) { - if (plot.owner == null) { + if (plot.guessOwner() == null) { return false; } plot.getSettings().addComment(comment); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxReport.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxReport.java index 7c626d8e1..551371933 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxReport.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/comment/InboxReport.java @@ -20,7 +20,7 @@ public class InboxReport extends CommentInbox { } @Override public boolean addComment(Plot plot, PlotComment comment) { - if (plot.owner == null) { + if (plot.guessOwner() == null) { return false; } DBFunc.setComment(plot, comment); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java index 989948f0c..c8a71ba2d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java @@ -104,7 +104,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager { } @Override public void removePlotArea(PlotArea area) { - ArrayList globalAreas = new ArrayList(Arrays.asList(plotAreas)); + ArrayList globalAreas = new ArrayList<>(Arrays.asList(plotAreas)); globalAreas.remove(area); this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); if (globalAreas.isEmpty()) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java index e36f1e07d..08d73df8e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java @@ -113,8 +113,8 @@ public class SinglePlotArea extends GridPlotWorld { return p; } PlotSettings s = p.getSettings(); - p = new SinglePlot(p.getId(), p.owner, p.getTrusted(), p.getMembers(), p.getDenied(), - s.alias, s.getPosition(), null, this, s.merged, p.getTimestamp(), p.temp); + p = new SinglePlot(p.getId(), p.guessOwner(), p.getTrusted(), p.getMembers(), p.getDenied(), + s.alias, s.getPosition(), null, this, s.getMerged(), p.getTimestamp(), p.temp); p.getSettings().flags = s.flags; return p; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java index adc462f4e..20d432d52 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java @@ -35,8 +35,7 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager { if (chars.length == 1 && chars[0] == '*') { return true; } - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; + for (char c : chars) { switch (mode) { case 0: mode = 1; @@ -62,7 +61,6 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager { if ((c <= '/') || (c >= ':')) { return false; } - continue; } } return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java index 0222dc815..fbbcca0c0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java @@ -30,12 +30,10 @@ public class SinglePlotManager extends PlotManager { SetupUtils.manager.unload(plot.getWorldName(), false); final File worldFolder = new File(PlotSquared.get().IMP.getWorldContainer(), plot.getWorldName()); - TaskManager.IMP.taskAsync(new Runnable() { - @Override public void run() { - MainUtil.deleteDirectory(worldFolder); - if (whenDone != null) - whenDone.run(); - } + TaskManager.IMP.taskAsync(() -> { + MainUtil.deleteDirectory(worldFolder); + if (whenDone != null) + whenDone.run(); }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java index e863e1302..cf2ca96ed 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java @@ -71,41 +71,39 @@ public abstract class ChunkManager { public static void largeRegionTask(final String world, final RegionWrapper region, final RunnableVal task, final Runnable whenDone) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - HashSet chunks = new HashSet<>(); - Set mcrs = manager.getChunkChunks(world); - for (ChunkLoc mcr : mcrs) { - int bx = mcr.x << 9; - int bz = mcr.z << 9; - int tx = bx + 511; - int tz = bz + 511; - if (bx <= region.maxX && tx >= region.minX && bz <= region.maxZ - && tz >= region.minZ) { - for (int x = bx >> 4; x <= (tx >> 4); x++) { - int cbx = x << 4; - int ctx = cbx + 15; - if (cbx <= region.maxX && ctx >= region.minX) { - for (int z = bz >> 4; z <= (tz >> 4); z++) { - int cbz = z << 4; - int ctz = cbz + 15; - if (cbz <= region.maxZ && ctz >= region.minZ) { - chunks.add(new ChunkLoc(x, z)); - } + TaskManager.runTaskAsync(() -> { + HashSet chunks = new HashSet<>(); + Set mcrs = manager.getChunkChunks(world); + for (ChunkLoc mcr : mcrs) { + int bx = mcr.x << 9; + int bz = mcr.z << 9; + int tx = bx + 511; + int tz = bz + 511; + if (bx <= region.maxX && tx >= region.minX && bz <= region.maxZ + && tz >= region.minZ) { + for (int x = bx >> 4; x <= (tx >> 4); x++) { + int cbx = x << 4; + int ctx = cbx + 15; + if (cbx <= region.maxX && ctx >= region.minX) { + for (int z = bz >> 4; z <= (tz >> 4); z++) { + int cbz = z << 4; + int ctz = cbz + 15; + if (cbz <= region.maxZ && ctz >= region.minZ) { + chunks.add(new ChunkLoc(x, z)); } } } } } - TaskManager.objectTask(chunks, new RunnableVal() { - - @Override public void run(ChunkLoc value) { - if (manager.loadChunk(world, value, false)) { - task.run(value); - } - } - }, whenDone); } + TaskManager.objectTask(chunks, new RunnableVal() { + + @Override public void run(ChunkLoc value) { + if (manager.loadChunk(world, value, false)) { + task.run(value); + } + } + }, whenDone); }); } @@ -239,20 +237,18 @@ public abstract class ChunkManager { public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - for (ChunkLoc loc : chunks) { - String directory = - world + File.separator + "region" + File.separator + "r." + loc.x + "." - + loc.z + ".mca"; - File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory); - PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)"); - if (file.exists()) { - file.delete(); - } + TaskManager.runTaskAsync(() -> { + for (ChunkLoc loc : chunks) { + String directory = + world + File.separator + "region" + File.separator + "r." + loc.x + "." + loc.z + + ".mca"; + File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory); + PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)"); + if (file.exists()) { + file.delete(); } - TaskManager.runTask(whenDone); } + TaskManager.runTask(whenDone); }); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CmdConfirm.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CmdConfirm.java index 11c157320..d0b4012a6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CmdConfirm.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CmdConfirm.java @@ -19,11 +19,9 @@ public class CmdConfirm { removePending(player); if (commandStr != null) MainUtil.sendMessage(player, C.REQUIRES_CONFIRM, commandStr); - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - CmdInstance cmd = new CmdInstance(runnable); - player.setMeta("cmdConfirm", cmd); - } + TaskManager.runTaskLater(() -> { + CmdInstance cmd = new CmdInstance(runnable); + player.setMeta("cmdConfirm", cmd); }, 1); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java index 3dc43fe06..524ea7f67 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java @@ -20,34 +20,31 @@ public class CommentManager { if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) { return; } - TaskManager.runTaskLaterAsync(new Runnable() { - @Override public void run() { - Collection boxes = CommentManager.inboxes.values(); - final AtomicInteger count = new AtomicInteger(0); - final AtomicInteger size = new AtomicInteger(boxes.size()); - for (final CommentInbox inbox : inboxes.values()) { - inbox.getComments(plot, new RunnableVal>() { - @Override public void run(List value) { - int total; - if (value != null) { - int num = 0; - for (PlotComment comment : value) { - if (comment.timestamp > getTimestamp(player, - inbox.toString())) { - num++; - } + TaskManager.runTaskLaterAsync(() -> { + Collection boxes = CommentManager.inboxes.values(); + final AtomicInteger count = new AtomicInteger(0); + final AtomicInteger size = new AtomicInteger(boxes.size()); + for (final CommentInbox inbox : inboxes.values()) { + inbox.getComments(plot, new RunnableVal>() { + @Override public void run(List value) { + int total; + if (value != null) { + int num = 0; + for (PlotComment comment : value) { + if (comment.timestamp > getTimestamp(player, inbox.toString())) { + num++; } - total = count.addAndGet(num); - } else { - total = count.get(); - } - if ((size.decrementAndGet() == 0) && (total > 0)) { - AbstractTitle.sendTitle(player, "", - C.INBOX_NOTIFICATION.s().replaceAll("%s", "" + total)); } + total = count.addAndGet(num); + } else { + total = count.get(); } - }); - } + if ((size.decrementAndGet() == 0) && (total > 0)) { + AbstractTitle.sendTitle(player, "", + C.INBOX_NOTIFICATION.s().replaceAll("%s", "" + total)); + } + } + }); } }, 20); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java index 45052042a..2973a5443 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java @@ -76,11 +76,7 @@ public abstract class EventUtil { } final Plot plot = player.getCurrentPlot(); if (Settings.Teleport.ON_LOGIN && plot != null) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - plot.teleportPlayer(player); - } - }); + TaskManager.runTask(() -> plot.teleportPlayer(player)); MainUtil.sendMessage(player, C.TELEPORTED_TO_ROAD.f() + " (on-login) " + "(" + plot.getId().x + ";" + plot .getId().y + ")"); @@ -90,11 +86,7 @@ public abstract class EventUtil { public void doRespawnTask(final PlotPlayer player) { final Plot plot = player.getCurrentPlot(); if (Settings.Teleport.ON_DEATH && plot != null) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - plot.teleportPlayer(player); - } - }); + TaskManager.runTask(() -> plot.teleportPlayer(player)); MainUtil.sendMessage(player, C.TELEPORTED_TO_ROAD); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java index d2495b646..6f9d48188 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java @@ -51,7 +51,6 @@ public class HastebinUtility { List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; - int i = 0; while ((line = reader.readLine()) != null) { lines.add(line); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java index ad4d22847..0deed094e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java @@ -124,20 +124,18 @@ public class MainUtil { PrintWriter writer = new PrintWriter( new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { String CRLF = "\r\n"; - writer.append("--" + boundary).append(CRLF); + writer.append("--").append(boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); - writer.append( - "Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()) - .append(CRLF); + writer.append("Content-Type: text/plain; charset=") + .append(StandardCharsets.UTF_8.displayName()).append(CRLF); String param = "value"; writer.append(CRLF).append(param).append(CRLF).flush(); - writer.append("--" + boundary).append(CRLF); + writer.append("--").append(boundary).append(CRLF); writer.append( - "Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" - + filename + '"').append(CRLF); - writer - .append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)) - .append(CRLF); + "Content-Disposition: form-data; name=\"schematicFile\"; filename=\"") + .append(filename).append(String.valueOf('"')).append(CRLF); + writer.append("Content-Type: ") + .append(URLConnection.guessContentTypeFromName(filename)).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); writeTask.value = new AbstractDelegateOutputStream(output) { @@ -147,7 +145,7 @@ public class MainUtil { writeTask.run(); output.flush(); writer.append(CRLF).flush(); - writer.append("--" + boundary + "--").append(CRLF).flush(); + writer.append("--").append(boundary).append("--").append(CRLF).flush(); } try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) { @@ -203,30 +201,30 @@ public class MainUtil { if (time >= 33868800) { int years = (int) (time / 33868800); time -= years * 33868800; - toreturn.append(years + "y "); + toreturn.append(years).append("y "); } if (time >= 604800) { int weeks = (int) (time / 604800); time -= weeks * 604800; - toreturn.append(weeks + "w "); + toreturn.append(weeks).append("w "); } if (time >= 86400) { int days = (int) (time / 86400); time -= days * 86400; - toreturn.append(days + "d "); + toreturn.append(days).append("d "); } if (time >= 3600) { int hours = (int) (time / 3600); time -= hours * 3600; - toreturn.append(hours + "h "); + toreturn.append(hours).append("h "); } if (time >= 60) { int minutes = (int) (time / 60); time -= minutes * 60; - toreturn.append(minutes + "m "); + toreturn.append(minutes).append("m "); } if (toreturn.equals("") || time > 0) { - toreturn.append((time) + "s "); + toreturn.append(time).append("s "); } return toreturn.toString().trim(); } @@ -410,7 +408,7 @@ public class MainUtil { ArrayList> plotList = new ArrayList<>(size); for (int i = 0; i < size; i++) { - plotList.add(new ArrayList()); + plotList.add(new ArrayList<>()); } for (Plot plot : PlotSquared.get().getPlots()) { @@ -429,7 +427,7 @@ public class MainUtil { count++; } } - if (area != null && plot.getArea().equals(area)) { + if (plot.getArea().equals(area)) { count++; } if (alias != null && alias.equals(plot.getAlias())) { @@ -621,14 +619,12 @@ public class MainUtil { if (caption.s().isEmpty()) { return true; } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - String m = C.format(caption, args); - if (player == null) { - PlotSquared.log(m); - } else { - player.sendMessage(m); - } + TaskManager.runTaskAsync(() -> { + String m = C.format(caption, args); + if (player == null) { + PlotSquared.log(m); + } else { + player.sendMessage(m); } }); return true; @@ -774,31 +770,28 @@ public class MainUtil { info = info.replace("%desc%", "No description set."); if (info.contains("%rating%")) { final String newInfo = info; - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - int max = 10; - if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES - .isEmpty()) { - max = 8; - } - String info; - if (full && Settings.Ratings.CATEGORIES != null - && Settings.Ratings.CATEGORIES.size() > 1) { - double[] ratings = MainUtil.getAverageRatings(plot); - String rating = ""; - String prefix = ""; - for (int i = 0; i < ratings.length; i++) { - rating += prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String - .format("%.1f", ratings[i]); - prefix = ","; - } - info = newInfo.replaceAll("%rating%", rating); - } else { - info = newInfo.replaceAll("%rating%", - String.format("%.1f", plot.getAverageRating()) + '/' + max); - } - whenDone.run(info); + TaskManager.runTaskAsync(() -> { + int max = 10; + if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { + max = 8; } + String info1; + if (full && Settings.Ratings.CATEGORIES != null + && Settings.Ratings.CATEGORIES.size() > 1) { + double[] ratings = MainUtil.getAverageRatings(plot); + StringBuilder rating = new StringBuilder(); + String prefix = ""; + for (int i = 0; i < ratings.length; i++) { + rating.append(prefix).append(Settings.Ratings.CATEGORIES.get(i)).append('=') + .append(String.format("%.1f", ratings[i])); + prefix = ","; + } + info1 = newInfo.replaceAll("%rating%", rating.toString()); + } else { + info1 = newInfo.replaceAll("%rating%", + String.format("%.1f", plot.getAverageRating()) + '/' + max); + } + whenDone.run(info1); }); return; } @@ -809,10 +802,9 @@ public class MainUtil { if (directory.exists()) { File[] files = directory.listFiles(); if (null != files) { - for (int i = 0; i < files.length; i++) { - File file = files[i]; + for (File file : files) { if (file.isDirectory()) { - deleteDirectory(files[i]); + deleteDirectory(file); } else { PlotSquared.debug("Deleting file: " + file + " | " + file.delete()); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java index bcd71b186..5ab516b63 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java @@ -75,7 +75,7 @@ public class Permissions { String[] nodes = permission.split("\\."); StringBuilder n = new StringBuilder(); for (int i = 0; i <= (nodes.length - 1); i++) { - n.append(nodes[i] + "."); + n.append(nodes[i]).append("."); String combined = n + C.PERMISSION_STAR.s(); if (!permission.equals(combined)) { if (caller.hasPermission(combined)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java index f1ca31b4d..05eeee166 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java @@ -87,7 +87,7 @@ public abstract class SchematicHandler { } else { MainUtil.sendMessage(null, "&7 - &a success: " + plot.getId()); } - TaskManager.runTask(() -> THIS.run()); + TaskManager.runTask(THIS); }); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java index a0236c653..d488ab98f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java @@ -145,12 +145,7 @@ public class StringMan { public static String joinOrdered(Collection collection, String delimiter) { Object[] array = collection.toArray(); - Arrays.sort(array, new Comparator() { - @Override public int compare(Object a, Object b) { - return a.hashCode() - b.hashCode(); - } - - }); + Arrays.sort(array, Comparator.comparingInt(Object::hashCode)); return join(array, delimiter); } @@ -245,13 +240,12 @@ public class StringMan { } public static boolean isEqual(String a, String b) { - return (a == b) || ((a != null) && (b != null) && (a.length() == b.length()) && ( - a.hashCode() == b.hashCode()) && a.equals(b)); + return a.equals(b) || b != null && a.length() == b.length() && a.hashCode() == b.hashCode() + && a.equals(b); } public static boolean isEqualIgnoreCase(String a, String b) { - return (a == b) || ((a != null) && (b != null) && (a.length() == b.length()) && a - .equalsIgnoreCase(b)); + return a.equals(b) || b != null && a.length() == b.length() && a.equalsIgnoreCase(b); } public static String repeat(String s, int n) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java index aafba9da9..17fe89dac 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java @@ -55,7 +55,7 @@ public class UUIDHandler { PlotSquared.get().foreachPlotRaw(new RunnableVal() { @Override public void run(Plot plot) { if (plot.hasOwner()) { - uuids.add(plot.owner); + uuids.add(plot.guessOwner()); uuids.addAll(plot.getTrusted()); uuids.addAll(plot.getMembers()); uuids.addAll(plot.getDenied()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java index 02beb3dc5..eacaf804a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java @@ -19,8 +19,7 @@ public abstract class UUIDHandlerImplementation { public final HashSet unknown = new HashSet<>(); public UUIDWrapper uuidWrapper; private boolean cached = false; - private BiMap uuidMap = - HashBiMap.create(new HashMap()); + private BiMap uuidMap = HashBiMap.create(new HashMap<>()); // private BiMap nameMap = uuidMap.inverse(); public UUIDHandlerImplementation(UUIDWrapper wrapper) { @@ -106,51 +105,47 @@ public abstract class UUIDHandlerImplementation { * PlotMe conversion */ if (!Settings.UUID.OFFLINE && !this.unknown.isEmpty()) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - UUID offline = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8)); - if (!UUIDHandlerImplementation.this.unknown.contains(offline) && !name.value - .equals(name.value.toLowerCase())) { - offline = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + name.value.toLowerCase()).getBytes(Charsets.UTF_8)); - if (!UUIDHandlerImplementation.this.unknown.contains(offline)) { - offline = null; - } + TaskManager.runTaskAsync(() -> { + UUID offline = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8)); + if (!UUIDHandlerImplementation.this.unknown.contains(offline) && !name.value + .equals(name.value.toLowerCase())) { + offline = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + name.value.toLowerCase()).getBytes(Charsets.UTF_8)); + if (!UUIDHandlerImplementation.this.unknown.contains(offline)) { + offline = null; } - if (offline != null && !offline.equals(uuid)) { - UUIDHandlerImplementation.this.unknown.remove(offline); - Set plots = PlotSquared.get().getPlotsAbs(offline); - if (!plots.isEmpty()) { - for (Plot plot : plots) { - plot.owner = uuid; - } - DBFunc.replaceUUID(offline, uuid); - PlotSquared.debug("&cDetected invalid UUID stored for: " + name.value); - PlotSquared.debug( - "&7 - Did you recently switch to online-mode storage without running `uuidconvert`?"); - PlotSquared.debug("&6" + PlotSquared.imp().getPluginName() - + " will update incorrect entries when the user logs in, or you can reconstruct your database."); + } + if (offline != null && !offline.equals(uuid)) { + UUIDHandlerImplementation.this.unknown.remove(offline); + Set plots = PlotSquared.get().getPlotsAbs(offline); + if (!plots.isEmpty()) { + for (Plot plot : plots) { + plot.setOwner(uuid); } + DBFunc.replaceUUID(offline, uuid); + PlotSquared.debug("&cDetected invalid UUID stored for: " + name.value); + PlotSquared.debug( + "&7 - Did you recently switch to online-mode storage without running `uuidconvert`?"); + PlotSquared.debug("&6" + PlotSquared.get().IMP.getPluginName() + + " will update incorrect entries when the user logs in, or you can reconstruct your database."); } } }); } else if (Settings.UUID.FORCE_LOWERCASE && !this.unknown.isEmpty() && !name.value .equals(name.value.toLowerCase())) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - UUID offlineUpper = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8)); - if (UUIDHandlerImplementation.this.unknown.contains(offlineUpper) - && offlineUpper != null && !offlineUpper.equals(uuid)) { - UUIDHandlerImplementation.this.unknown.remove(offlineUpper); - Set plots = PlotSquared.get().getPlotsAbs(offlineUpper); - if (!plots.isEmpty()) { - for (Plot plot : plots) { - plot.owner = uuid; - } - replace(offlineUpper, uuid, name.value); + TaskManager.runTaskAsync(() -> { + UUID offlineUpper = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8)); + if (UUIDHandlerImplementation.this.unknown.contains(offlineUpper) && !offlineUpper + .equals(uuid)) { + UUIDHandlerImplementation.this.unknown.remove(offlineUpper); + Set plots = PlotSquared.get().getPlotsAbs(offlineUpper); + if (!plots.isEmpty()) { + for (Plot plot : plots) { + plot.setOwner(uuid); } + replace(offlineUpper, uuid, name.value); } } }); @@ -162,7 +157,7 @@ public abstract class UUIDHandlerImplementation { Set plots = PlotSquared.get().getPlots(offline); if (!plots.isEmpty()) { for (Plot plot : plots) { - plot.owner = uuid; + plot.setOwner(uuid); } replace(offline, uuid, name.value); } @@ -199,7 +194,7 @@ public abstract class UUIDHandlerImplementation { PlotSquared.debug("&cDetected invalid UUID stored for: " + name); PlotSquared.debug( "&7 - Did you recently switch to online-mode storage without running `uuidconvert`?"); - PlotSquared.debug("&6" + PlotSquared.imp().getPluginName() + PlotSquared.debug("&6" + PlotSquared.get().IMP.getPluginName() + " will update incorrect entries when the user logs in, or you can reconstruct your database."); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java index 3991cd78d..31e4cad7c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java @@ -81,52 +81,50 @@ public class GlobalBlockQueue { return false; } running.set(true); - TaskManager.runTaskRepeat(new Runnable() { - @Override public void run() { - if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) { - lastSuccess = System.currentTimeMillis(); - tasks(); - return; - } - SET_TASK.value1 = 50 + Math.min( - (50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last = - System.currentTimeMillis()), - GlobalBlockQueue.this.secondLast - System.currentTimeMillis()); - SET_TASK.value2 = getNextQueue(); - if (SET_TASK.value2 == null) { - return; - } - if (!PlotSquared.get().isMainThread(Thread.currentThread())) { - throw new IllegalStateException( - "This shouldn't be possible for placement to occur off the main thread"); - } - // Disable the async catcher as it can't discern async vs parallel - SET_TASK.value2.startSet(true); - try { - if (PARALLEL_THREADS <= 1) { - SET_TASK.run(); - } else { - ArrayList threads = new ArrayList(); - for (int i = 0; i < PARALLEL_THREADS; i++) { - threads.add(new Thread(SET_TASK)); - } - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + TaskManager.runTaskRepeat(() -> { + if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) { + lastSuccess = System.currentTimeMillis(); + tasks(); + return; + } + SET_TASK.value1 = 50 + Math.min( + (50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last = + System.currentTimeMillis()), + GlobalBlockQueue.this.secondLast - System.currentTimeMillis()); + SET_TASK.value2 = getNextQueue(); + if (SET_TASK.value2 == null) { + return; + } + if (!PlotSquared.get().isMainThread(Thread.currentThread())) { + throw new IllegalStateException( + "This shouldn't be possible for placement to occur off the main thread"); + } + // Disable the async catcher as it can't discern async vs parallel + SET_TASK.value2.startSet(true); + try { + if (PARALLEL_THREADS <= 1) { + SET_TASK.run(); + } else { + ArrayList threads = new ArrayList(); + for (int i = 0; i < PARALLEL_THREADS; i++) { + threads.add(new Thread(SET_TASK)); + } + for (Thread thread : threads) { + thread.start(); + } + for (Thread thread : threads) { + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); } } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - // Enable it again (note that we are still on the main thread) - SET_TASK.value2.endSet(true); } + } catch (Throwable e) { + e.printStackTrace(); + } finally { + // Enable it again (note that we are still on the main thread) + SET_TASK.value2.endSet(true); } }, 1); return true; @@ -168,7 +166,7 @@ public class GlobalBlockQueue { public List getAllQueues() { ArrayList list = - new ArrayList(activeQueues.size() + inactiveQueues.size()); + new ArrayList<>(activeQueues.size() + inactiveQueues.size()); list.addAll(inactiveQueues); list.addAll(activeQueues); return list; @@ -299,6 +297,6 @@ public class GlobalBlockQueue { } public enum QueueStage { - INACTIVE, ACTIVE, NONE; + INACTIVE, ACTIVE, NONE } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java index 352465aea..603be8db2 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java @@ -77,7 +77,6 @@ public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { PlotArea area = PlotSquared.get().getPlotArea(getWorld(), null); Location loc = new Location(getWorld(), bx, 0, bz); if (area != null) { - PlotManager manager = area.getPlotManager(); for (int x = 0; x < 16; x++) { loc.setX(bx + x); for (int z = 0; z < 16; z++) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java index b15877936..74232a319 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java @@ -98,28 +98,26 @@ public class ExpireManager { Iterator iter = plotsToDelete.iterator(); final Plot current = iter.next(); if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - pp.setMeta("ignoreExpireTask", true); - pp.teleport(current.getCenter()); - pp.deleteMeta("ignoreExpireTask"); - PlotMessage msg = new PlotMessage().text( - num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ") - .color("$1").text(current.toString()).color("$2") - .suggest("/plot list expired").tooltip("/plot list expired") - //.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired") - .text("\n - ").color("$3").text("Delete this (/plot delete)") - .color("$2").suggest("/plot delete").tooltip("/plot delete") - .text("\n - ").color("$3").text("Remind later (/plot set keep 1d)") - .color("$2").suggest("/plot set keep 1d") - .tooltip("/plot set keep 1d").text("\n - ").color("$3") - .text("Keep this (/plot set keep true)").color("$2") - .suggest("/plot set keep true").tooltip("/plot set keep true") - .text("\n - ").color("$3").text("Don't show me this").color("$2") - .suggest("/plot toggle clear-confirmation") - .tooltip("/plot toggle clear-confirmation"); - msg.send(pp); - } + TaskManager.runTask(() -> { + pp.setMeta("ignoreExpireTask", true); + pp.teleport(current.getCenter()); + pp.deleteMeta("ignoreExpireTask"); + PlotMessage msg = new PlotMessage() + .text(num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ") + .color("$1").text(current.toString()).color("$2") + .suggest("/plot list expired").tooltip("/plot list expired") + //.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired") + .text("\n - ").color("$3").text("Delete this (/plot delete)") + .color("$2").suggest("/plot delete").tooltip("/plot delete") + .text("\n - ").color("$3").text("Remind later (/plot set keep 1d)") + .color("$2").suggest("/plot set keep 1d").tooltip("/plot set keep 1d") + .text("\n - ").color("$3").text("Keep this (/plot set keep true)") + .color("$2").suggest("/plot set keep true") + .tooltip("/plot set keep true").text("\n - ").color("$3") + .text("Don't show me this").color("$2") + .suggest("/plot toggle clear-confirmation") + .tooltip("/plot toggle clear-confirmation"); + msg.send(pp); }); return; } else { @@ -220,12 +218,7 @@ public class ExpireManager { public ArrayDeque getTasks(PlotArea area) { ArrayDeque queue = new ArrayDeque<>(tasks); - Iterator iter = queue.iterator(); - while (iter.hasNext()) { - if (!iter.next().applies(area)) { - iter.remove(); - } - } + queue.removeIf(expiryTask -> !expiryTask.applies(area)); return queue; } @@ -255,7 +248,7 @@ public class ExpireManager { } this.running = 2; final ConcurrentLinkedDeque plots = - new ConcurrentLinkedDeque(PlotSquared.get().getPlots()); + new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots()); TaskManager.runTaskAsync(new Runnable() { @Override public void run() { final Runnable task = this; @@ -263,7 +256,6 @@ public class ExpireManager { ExpireManager.this.running = 0; return; } - long start = System.currentTimeMillis(); while (!plots.isEmpty()) { if (ExpireManager.this.running != 2) { ExpireManager.this.running = 0; @@ -279,11 +271,8 @@ public class ExpireManager { } for (ExpiryTask expiryTask : expired) { if (!expiryTask.needsAnalysis()) { - expiredTask.run(newPlot, new Runnable() { - @Override public void run() { - TaskManager.IMP.taskLaterAsync(task, 1); - } - }, expiryTask.requiresConfirmation()); + expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1), + expiryTask.requiresConfirmation()); return; } } @@ -292,26 +281,19 @@ public class ExpireManager { @Override public void run(final PlotAnalysis changed) { passesComplexity(changed, expired, new RunnableVal() { @Override public void run(Boolean confirmation) { - expiredTask.run(newPlot, new Runnable() { - @Override public void run() { - TaskManager.IMP.taskLaterAsync(task, 1); - } - }, confirmation); - } - }, new Runnable() { - @Override public void run() { - FlagManager - .addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList()); - TaskManager.runTaskLaterAsync(task, 20); + expiredTask.run(newPlot, + () -> TaskManager.IMP.taskLaterAsync(task, 1), + confirmation); } + }, () -> { + FlagManager + .addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList()); + TaskManager.runTaskLaterAsync(task, 20); }); } }; - final Runnable doAnalysis = new Runnable() { - @Override public void run() { - HybridUtils.manager.analyzePlot(newPlot, handleAnalysis); - } - }; + final Runnable doAnalysis = + () -> HybridUtils.manager.analyzePlot(newPlot, handleAnalysis); PlotAnalysis analysis = newPlot.getComplexity(null); if (analysis != null) { @@ -319,11 +301,7 @@ public class ExpireManager { @Override public void run(Boolean value) { doAnalysis.run(); } - }, new Runnable() { - @Override public void run() { - TaskManager.IMP.taskLaterAsync(task, 1); - } - }); + }, () -> TaskManager.IMP.taskLaterAsync(task, 1)); } else { doAnalysis.run(); } @@ -331,12 +309,10 @@ public class ExpireManager { } if (plots.isEmpty()) { ExpireManager.this.running = 3; - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - if (ExpireManager.this.running == 3) { - ExpireManager.this.running = 2; - runTask(expiredTask); - } + TaskManager.runTaskLater(() -> { + if (ExpireManager.this.running == 3) { + ExpireManager.this.running = 2; + runTask(expiredTask); } }, 86400000); } else { @@ -364,7 +340,7 @@ public class ExpireManager { } public HashSet getPendingExpired() { - return plotsToDelete == null ? new HashSet() : plotsToDelete; + return plotsToDelete == null ? new HashSet<>() : plotsToDelete; } public void deleteWithMessage(Plot plot, Runnable whenDone) { @@ -389,12 +365,12 @@ public class ExpireManager { int changes = changed == null ? 0 : changed.changes_sd; int modified = changed == null ? 0 : changed.changes; PlotSquared.debug( - "$2[&5Expire&dManager$2] &cDeleted expired plot: " + plot + " User:" + plot.owner + "$2[&5Expire&dManager$2] &cDeleted expired plot: " + plot + " User:" + plot.guessOwner() + " Delta:" + changes + "/" + modified + " Connected: " + StringMan .getString(plots)); PlotSquared.debug("$4 - Area: " + plot.getArea()); if (plot.hasOwner()) { - PlotSquared.debug("$4 - Owner: " + UUIDHandler.getName(plot.owner)); + PlotSquared.debug("$4 - Owner: " + UUIDHandler.getName(plot.guessOwner())); } else { PlotSquared.debug("$4 - Owner: Unowned"); } @@ -429,8 +405,8 @@ public class ExpireManager { } public long getAccountAge(Plot plot) { - if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.owner) - || UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) { + if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.guessOwner()) + || UUIDHandler.getPlayer(plot.guessOwner()) != null || plot.getRunning() > 0) { return Long.MAX_VALUE; } long max = 0; @@ -442,8 +418,8 @@ public class ExpireManager { } public long getAge(Plot plot) { - if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.owner) - || UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) { + if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.guessOwner()) + || UUIDHandler.getPlayer(plot.guessOwner()) != null || plot.getRunning() > 0) { return 0; } Optional keep = plot.getFlag(Flags.KEEP); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java index 118cda789..98abd7be0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java @@ -378,19 +378,19 @@ public class PlotAnalysis { } public static String log(Object obj) { - String result = ""; + StringBuilder result = new StringBuilder(); if (obj.getClass().isArray()) { String prefix = ""; for (int i = 0; i < Array.getLength(obj); i++) { - result += prefix + log(Array.get(obj, i)); + result.append(prefix).append(log(Array.get(obj, i))); prefix = ","; } return "( " + result + " )"; } else if (obj instanceof List) { String prefix = ""; for (Object element : (List) obj) { - result += prefix + log(element); + result.append(prefix).append(log(element)); prefix = ","; } return "[ " + result + " ]";