From cf82bc5efbb9d5ec18e9ef87954a88c9971fb6f9 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Mon, 4 Feb 2019 15:18:50 +0000 Subject: [PATCH] Revert 8ac9b86 --- .../plotsquared/bukkit/BukkitMain.java | 9 +- .../plotsquared/bukkit/chat/FancyMessage.java | 33 +- .../bukkit/events/ClusterFlagRemoveEvent.java | 63 ++ .../bukkit/listeners/ChunkListener.java | 117 +-- .../bukkit/listeners/PlayerEvents.java | 39 +- .../bukkit/listeners/PlotPlusListener.java | 73 +- .../bukkit/listeners/SingleWorldListener.java | 4 +- .../entity/ReplicatingEntityWrapper.java | 21 +- .../bukkit/object/schematic/StateWrapper.java | 3 +- .../bukkit/titles/TitleManager.java | 6 +- .../bukkit/titles/TitleManager_1_11.java | 2 +- .../bukkit/util/BukkitEventUtil.java | 4 + .../bukkit/util/BukkitHybridUtils.java | 1 - .../bukkit/util/BukkitInventoryUtil.java | 4 +- .../plotsquared/bukkit/util/SendChunk.java | 29 +- .../bukkit/util/block/BukkitLocalQueue.java | 3 +- .../bukkit/uuid/DefaultUUIDWrapper.java | 9 +- .../bukkit/uuid/FileUUIDHandler.java | 350 ++++----- .../bukkit/uuid/OfflineUUIDWrapper.java | 24 +- .../bukkit/uuid/SQLUUIDHandler.java | 235 +++--- .../configuration/Configuration.java | 3 +- .../configuration/ConfigurationOptions.java | 4 +- .../configuration/ConfigurationSection.java | 9 +- .../configuration/MemoryConfiguration.java | 3 +- .../configuration/MemorySection.java | 56 +- .../configuration/file/FileConfiguration.java | 3 +- .../configuration/file/YamlConfiguration.java | 2 +- .../file/YamlConfigurationOptions.java | 2 +- .../configuration/file/YamlConstructor.java | 2 +- .../plotsquared/plot/IPlotMain.java | 4 +- .../plotsquared/plot/Platform.java | 2 +- .../plotsquared/plot/PlotSquared.java | 293 ++++--- .../plotsquared/plot/commands/Area.java | 112 +-- .../plotsquared/plot/commands/Claim.java | 22 +- .../plotsquared/plot/commands/Cluster.java | 7 +- .../plotsquared/plot/commands/Condense.java | 13 +- .../plotsquared/plot/commands/Database.java | 46 +- .../plotsquared/plot/commands/Help.java | 4 +- .../plotsquared/plot/commands/Inbox.java | 5 +- .../plotsquared/plot/commands/Merge.java | 4 +- .../plotsquared/plot/commands/Purge.java | 30 +- .../plotsquared/plot/commands/Rate.java | 72 +- .../plotsquared/plot/database/AbstractDB.java | 8 + .../plotsquared/plot/database/DBFunc.java | 68 +- .../plotsquared/plot/database/Database.java | 16 +- .../plotsquared/plot/database/MySQL.java | 2 +- .../plotsquared/plot/database/SQLManager.java | 712 +++++++++++------- .../plotsquared/plot/database/SQLite.java | 2 +- .../plotsquared/plot/flag/FlagManager.java | 42 +- .../plot/generator/HybridPlotWorld.java | 6 +- .../plotsquared/plot/logger/ILogger.java | 2 +- .../plotsquared/plot/object/Expression.java | 4 +- .../plotsquared/plot/object/Plot.java | 383 ++++++---- .../plotsquared/plot/object/PlotArea.java | 3 - .../plotsquared/plot/object/PlotCluster.java | 20 +- .../plotsquared/plot/object/PlotMessage.java | 1 - .../plotsquared/plot/object/PlotPlayer.java | 108 ++- .../plotsquared/plot/object/PlotSettings.java | 9 +- .../stream/AbstractDelegateOutputStream.java | 5 +- .../object/worlds/DefaultPlotAreaManager.java | 18 +- .../plot/object/worlds/PlotAreaManager.java | 20 +- .../plot/object/worlds/SinglePlot.java | 3 +- .../object/worlds/SinglePlotAreaManager.java | 3 +- .../plot/object/worlds/SinglePlotManager.java | 10 +- .../plotsquared/plot/util/AbstractTitle.java | 2 +- .../plotsquared/plot/util/ChunkManager.java | 76 +- .../plotsquared/plot/util/CmdConfirm.java | 8 +- .../plotsquared/plot/util/CommentManager.java | 47 +- .../plotsquared/plot/util/EventUtil.java | 8 +- .../plotsquared/plot/util/MainUtil.java | 66 +- .../plot/util/SchematicHandler.java | 2 +- .../plot/util/block/GlobalBlockQueue.java | 93 +-- .../plot/util/expiry/ExpireManager.java | 105 ++- .../plot/util/expiry/PlotAnalysis.java | 33 +- .../plotsquared/plot/uuid/UUIDWrapper.java | 14 +- .../plot/database/AbstractDBTest.java | 3 + .../plotsquared/plot/util/EventUtilTest.java | 4 + 77 files changed, 2105 insertions(+), 1528 deletions(-) create mode 100644 Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java 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 0693e1070..78cd3a189 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 @@ -81,7 +81,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain private final BlockRegistry blockRegistry = new BukkitBlockRegistry(Material.values()); private int[] version; - private String pluginName; + @Getter private String pluginName; @Getter private SingleWorldListener singleWorldListener; private Method methodUnloadChunk0; private boolean methodUnloadSetup = false; @@ -112,9 +112,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return Bukkit.getVersion(); } - @Override public void onEnable() { this.pluginName = getDescription().getName(); + getServer().getName(); PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer); @@ -266,10 +266,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return getDescription().getVersion(); } - @Override public String getPluginName() { - return pluginName; - } - @Override public void registerCommands() { final BukkitCommand bukkitCommand = new BukkitCommand(); final PluginCommand plotCommand = getCommand("plots"); @@ -537,7 +533,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain @Override @Nullable public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { - PlotSquared.log("DEFAULT WORLD GENERATOR RUN"); final IndependentPlotGenerator result; if (id != null && id.equalsIgnoreCase("single")) { result = new SingleWorldGenerator(); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java index 5e87231df..41ec91e49 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java @@ -5,10 +5,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.Statistic; +import org.bukkit.*; import org.bukkit.Statistic.Type; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -323,6 +320,34 @@ public class FancyMessage return this; } + /** + * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param which The achievement to display. + * @return This builder instance. + */ + public FancyMessage achievementTooltip(final Achievement which) { + try { + Object achievement = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", + Achievement.class).invoke(null, which); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name") + .get(achievement)); + } catch (IllegalAccessException e) { + Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); + return this; + } catch (IllegalArgumentException e) { + Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); + return this; + } catch (InvocationTargetException e) { + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); + return this; + } + } + /** * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java new file mode 100644 index 000000000..40acef111 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java @@ -0,0 +1,63 @@ +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called when a flag is removed from a plot. + */ +public class ClusterFlagRemoveEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final PlotCluster cluster; + private final Flag flag; + private boolean cancelled; + + /** + * PlotFlagRemoveEvent: Called when a flag is removed from a plot. + * + * @param flag Flag that was removed + * @param cluster PlotCluster from which the flag was removed + */ + public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) { + this.cluster = cluster; + this.flag = flag; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the cluster involved. + * + * @return PlotCluster + */ + public PlotCluster getCluster() { + return this.cluster; + } + + /** + * Get the flag involved. + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean b) { + this.cancelled = b; + } +} 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 a57a8dbe3..af9ed712a 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 @@ -59,45 +59,48 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils for (World world : Bukkit.getWorlds()) { world.setAutoSave(false); } - 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())) { + 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)) { continue; } - int x = chunk.getX(); - int z = chunk.getZ(); - if (!shouldSave(worldName, x, z)) { - unloadChunk(worldName, chunk, false); - 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); } - toUnload.add(chunk); } - } - if (toUnload.isEmpty()) { - return; - } - long start = System.currentTimeMillis(); - for (Chunk chunk : toUnload) { - if (System.currentTimeMillis() - start > 5) { + if (toUnload.isEmpty()) { return; } - chunk.unload(true, false); + long start = System.currentTimeMillis(); + for (Chunk chunk : toUnload) { + if (System.currentTimeMillis() - start > 5) { + return; + } + chunk.unload(true, false); + } + } catch (Throwable e) { + e.printStackTrace(); } - } catch (Throwable e) { - e.printStackTrace(); } }, 1); } @@ -108,7 +111,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()) { + if ((Boolean) field.get() == true) { field.set(false); if (chunk.isLoaded()) { ignoreUnload = true; @@ -219,26 +222,9 @@ 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(() -> { - 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) { + Integer task = TaskManager.runTaskRepeat(new Runnable() { + @Override public void run() { + if (!chunk.isLoaded()) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); PlotSquared @@ -246,8 +232,29 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils chunk.unload(true, true); return; } - tiles[i].getBlock().setType(Material.AIR, false); - i++; + 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++; + } } }, 5); TaskManager.tasks.put(currentIndex, task); 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 d0511aaa7..e8ab247a7 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 @@ -42,7 +42,6 @@ import org.bukkit.help.HelpTopic; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.material.Directional; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; @@ -673,9 +672,8 @@ import java.util.regex.Pattern; if (passenger instanceof Player) { final Player player = (Player) passenger; // reset - if (moveTmp == null) { + if (moveTmp == null) moveTmp = new PlayerMoveEvent(null, from, to); - } moveTmp.setFrom(from); moveTmp.setTo(to); moveTmp.setCancelled(false); @@ -703,7 +701,7 @@ import java.util.regex.Pattern; vehicle.eject(); vehicle.setVelocity(new Vector(0d, 0d, 0d)); vehicle.teleport(dest); - vehicle.addPassenger(player); + vehicle.setPassenger(player); } return; } @@ -785,7 +783,7 @@ import java.util.regex.Pattern; this.tmpTeleport = true; return; } - int border = area.getBorder(); + Integer border = area.getBorder(); if (x2 > border && this.tmpTeleport) { to.setX(x2 - 1); this.tmpTeleport = false; @@ -848,7 +846,7 @@ import java.util.regex.Pattern; this.tmpTeleport = true; return; } - int border = area.getBorder(); + Integer border = area.getBorder(); if (z2 > border && this.tmpTeleport) { to.setZ(z2 - 1); this.tmpTeleport = false; @@ -866,9 +864,8 @@ import java.util.regex.Pattern; } @EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { - if (event.isCancelled()) { + if (event.isCancelled()) return; - } PlotPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer()); Location location = plotPlayer.getLocation(); @@ -1085,9 +1082,8 @@ import java.util.regex.Pattern; PlotArea area = location.getPlotArea(); if (area != null) { Plot plot = area.getOwnedPlot(location); - if (plot != null && Flags.MOB_BREAK.isTrue(plot)) { + if (plot != null && Flags.MOB_BREAK.isTrue(plot)) return; - } event.setCancelled(true); } } @@ -1454,11 +1450,11 @@ import java.util.regex.Pattern; switch (type) { case WATER_BUCKET: case LAVA_BUCKET: { - if (event.getBlock().getType() == Material.DROPPER) { + if (event.getBlock().getType() == Material.DROPPER) return; - } BlockFace targetFace = - ((Directional) event.getBlock().getState().getData()).getFacing(); + ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()) + .getFacing(); Location location = BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); if (location.isPlotRoad()) { @@ -1579,9 +1575,8 @@ import java.util.regex.Pattern; switch (newItem.getType()) { case LEGACY_BANNER: case PLAYER_HEAD: - if (newMeta != null) { + if (newMeta != null) break; - } default: return; } @@ -1597,13 +1592,11 @@ import java.util.regex.Pattern; switch (stateType) { case LEGACY_STANDING_BANNER: case LEGACY_WALL_BANNER: - if (itemType == Material.LEGACY_BANNER) { + if (itemType == Material.LEGACY_BANNER) break; - } case LEGACY_SKULL: - if (itemType == Material.LEGACY_SKULL_ITEM) { + if (itemType == Material.LEGACY_SKULL_ITEM) break; - } default: return; } @@ -2571,11 +2564,11 @@ import java.util.regex.Pattern; } } - @EventHandler(priority = EventPriority.HIGHEST) + @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { - EntityDamageByEntityEvent eventChange = - new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); + EntityDamageByEntityEvent eventChange = null; + eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), + EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); onEntityDamageByEntityEvent(eventChange); if (eventChange.isCancelled()) { event.setCancelled(true); 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 33a63dbde..d95a7c199 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 @@ -10,7 +10,6 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.block.Block; -import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; @@ -37,43 +36,45 @@ import java.util.UUID; private static final HashMap healRunnable = new HashMap<>(); public static void startRunnable(JavaPlugin plugin) { - 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)); + 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)); + } } } } - } - 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)); + } } } } @@ -104,7 +105,7 @@ import java.util.UUID; if (event.getEntityType() != EntityType.PLAYER) { return; } - Entity player = event.getEntity(); + Player player = (Player) event.getEntity(); Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); if (plot == null) { return; 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 b0912fea2..6a3e26d59 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 (NoSuchFieldException exception) { - exception.printStackTrace(); + } catch (Throwable ignore) { + ignore.printStackTrace(); } Bukkit.getPluginManager().registerEvents(this, plugin); } 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 0b6921f88..e71373771 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 @@ -135,11 +135,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { Horse horse = (Horse) entity; this.horse = new HorseStats(); this.horse.jump = horse.getJumpStrength(); - if (horse instanceof ChestedHorse) { - this.horse.chest = ((ChestedHorse) horse).isCarryingChest(); - } else { - this.horse.chest = false; - } + this.horse.chest = horse.isCarryingChest(); this.horse.variant = horse.getVariant(); this.horse.style = horse.getStyle(); this.horse.color = horse.getColor(); @@ -179,12 +175,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { return; // END AGEABLE // case GUARDIAN: - //todo no longer works (possible exception thrown) this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0); storeLiving((LivingEntity) entity); return; case SKELETON: - //todo no longer works (possible exception thrown) this.dataByte = getOrdinal(Skeleton.SkeletonType.values(), ((Skeleton) entity).getSkeletonType()); storeLiving((LivingEntity) entity); @@ -430,7 +424,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { return entity; } if (this.base.passenger != null) { - entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); + try { + entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); + } catch (Exception ignored) { + } } if (this.base.fall != 0) { entity.setFallDistance(this.base.fall); @@ -515,10 +512,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case HORSE: Horse horse = (Horse) entity; horse.setJumpStrength(this.horse.jump); - if (horse instanceof ChestedHorse && this.horse.chest) { - ((ChestedHorse) horse).setCarryingChest(true); - } - //todo broken in 1.13 possible exception thrown + horse.setCarryingChest(this.horse.chest); horse.setVariant(this.horse.variant); horse.setStyle(this.horse.style); horse.setColor(this.horse.color); @@ -565,15 +559,12 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { return entity; case GUARDIAN: if (this.dataByte != 0) { - //todo broken in 1.13 possible exception thrown - ((Guardian) entity).setElder(true); } restoreLiving((LivingEntity) entity); return entity; case SKELETON: if (this.dataByte != 0) { - //todo broken in 1.13 possible exception thrown ((Skeleton) entity) .setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java index 4815c2e01..3557f33af 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -14,7 +14,6 @@ import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; import java.util.ArrayList; import java.util.HashMap; @@ -242,7 +241,7 @@ public class StateWrapper { public Map serializeItem(ItemStack item) { Map data = new HashMap<>(); data.put("id", new StringTag(item.getType().name())); - data.put("Damage", new ShortTag((short) ((Damageable) item.getItemMeta()).getDamage())); + data.put("Damage", new ShortTag(item.getDurability())); data.put("Count", new ByteTag((byte) item.getAmount())); if (!item.getEnchantments().isEmpty()) { List enchantmentList = new ArrayList<>(); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java index df16d07a2..f4c249f97 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java @@ -187,7 +187,11 @@ public abstract class TitleManager { throws IllegalArgumentException, ReflectiveOperationException, SecurityException; private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.getOrDefault(clazz, clazz); + if (CORRESPONDING_TYPES.containsKey(clazz)) { + return CORRESPONDING_TYPES.get(clazz); + } else { + return clazz; + } } private Class[] toPrimitiveTypeArray(Class[] classes) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java index 817417087..92155ba45 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java @@ -335,7 +335,7 @@ public class TitleManager_1_11 { } private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.getOrDefault(clazz, clazz); + return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; } private Class[] toPrimitiveTypeArray(Class[] classes) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java index 5a4cf885a..7fd22b55e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java @@ -101,6 +101,10 @@ public final class BukkitEventUtil extends EventUtil { new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner)); } + @Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) { + return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); + } + @Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { PlotRateEvent event = new PlotRateEvent(player, rating, plot); Bukkit.getServer().getPluginManager().callEvent(event); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java index 395523f35..3c2c75d2b 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -148,7 +148,6 @@ public class BukkitHybridUtils extends HybridUtils { } int y = MainUtil.y_loc[i][j]; oldBlocks[y][x][z] = airBucket; - } continue; } 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 d855f9e39..c40e13d09 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 @@ -83,7 +83,7 @@ public class BukkitInventoryUtil extends InventoryUtil { } // int id = item.getTypeId(); Material id = item.getType(); - //short data = item.getDurability(); + short data = item.getDurability(); int amount = item.getAmount(); String name = null; String[] lore = null; @@ -94,7 +94,7 @@ public class BukkitInventoryUtil extends InventoryUtil { } if (meta.hasLore()) { List itemLore = meta.getLore(); - lore = itemLore.toArray(new String[0]); + lore = itemLore.toArray(new String[itemLore.size()]); } } return new PlotItemStack(id.name(), amount, name, lore); 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 6be193778..f0987b219 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 @@ -26,8 +26,8 @@ import java.util.Map.Entry; import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; /** - * An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy - * NMS). + * An utility that can be used to send chunks, rather than using bukkit code + * to do so (uses heavy NMS). */ public class SendChunk { @@ -118,17 +118,20 @@ public class SendChunk { } } for (final Chunk chunk : chunks) { - 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)"); + 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)"); + } } }); } 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 eee467db1..77518690d 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 @@ -192,7 +192,8 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { for (int x = 0; x < lc.biomes.length; x++) { String[] biomes2 = lc.biomes[x]; if (biomes2 != null) { - for (String biomeStr : biomes2) { + for (int y = 0; y < biomes2.length; y++) { + String biomeStr = biomes2[y]; if (biomeStr != null) { if (last == null || !StringMan.isEqual(last, biomeStr)) { biome = Biome.valueOf(biomeStr.toUpperCase()); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java index 40305cca5..3660bef92 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java @@ -8,10 +8,9 @@ import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; -import java.util.Arrays; import java.util.UUID; -public class DefaultUUIDWrapper implements UUIDWrapper { +public class DefaultUUIDWrapper extends UUIDWrapper { @Override public UUID getUUID(PlotPlayer player) { return ((BukkitPlayer) player).player.getUniqueId(); @@ -31,7 +30,11 @@ public class DefaultUUIDWrapper implements UUIDWrapper { @Override public OfflinePlotPlayer[] getOfflinePlayers() { OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); - return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new); + BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; + for (int i = 0; i < ops.length; i++) { + toReturn[i] = new BukkitOfflinePlayer(ops[i]); + } + return toReturn; } @Override public OfflinePlotPlayer getOfflinePlayer(String name) { 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 42a83f466..2223feceb 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,196 +47,204 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } else { world = worlds.get(0).getName(); } - 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; + 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(); } - 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; + } + } 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); + } + } + } catch (Exception e) { + e.printStackTrace(); + PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current); } - 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(); + add(toAdd); + if (all.isEmpty()) { + if (whenDone != null) { + whenDone.run(); + } + return; + } else { + PlotSquared.debug("Failed to cache: " + all.size() + + " uuids - slowly processing all files"); + } } - } - 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); + 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); } - toAdd.put(new StringWrapper(name), uuid); + } + 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); } } - } 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"); + if (whenDone != null) { + whenDone.run(); } } - 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(() -> { - ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); - TaskManager.runTask(ifFetch); + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); + TaskManager.runTask(ifFetch); + } }); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java index 0f3b4d5ea..c44fa6e72 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java @@ -16,11 +16,10 @@ import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.Arrays; import java.util.Collection; import java.util.UUID; -public class OfflineUUIDWrapper implements UUIDWrapper { +public class OfflineUUIDWrapper extends UUIDWrapper { private final Object[] arg = new Object[0]; private Method getOnline = null; @@ -60,15 +59,18 @@ public class OfflineUUIDWrapper implements UUIDWrapper { return new BukkitOfflinePlayer(op); } } - return Arrays.stream(Bukkit.getOfflinePlayers()) - .filter(player -> getUUID(player).equals(uuid)).findFirst() - .map(BukkitOfflinePlayer::new).orElse(null); + for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { + if (getUUID(player).equals(uuid)) { + return new BukkitOfflinePlayer(player); + } + } + return null; } public Player[] getOnlinePlayers() { if (this.getOnline == null) { Collection onlinePlayers = Bukkit.getOnlinePlayers(); - return onlinePlayers.toArray(new Player[0]); + return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } try { Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); @@ -77,13 +79,13 @@ public class OfflineUUIDWrapper implements UUIDWrapper { } else { @SuppressWarnings("unchecked") Collection p = (Collection) players; - return p.toArray(new Player[0]); + return p.toArray(new Player[p.size()]); } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { PlotSquared.debug("Failed to resolve online players"); this.getOnline = null; Collection onlinePlayers = Bukkit.getOnlinePlayers(); - return onlinePlayers.toArray(new Player[0]); + return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } } @@ -93,7 +95,11 @@ public class OfflineUUIDWrapper implements UUIDWrapper { @Override public OfflinePlotPlayer[] getOfflinePlayers() { OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); - return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new); + BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; + for (int i = 0; i < ops.length; i++) { + toReturn[i] = new BukkitOfflinePlayer(ops[i]); + } + return toReturn; } @Override public OfflinePlotPlayer getOfflinePlayer(String name) { 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 234059e02..1c9a30bba 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 @@ -71,82 +71,96 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { if (!super.startCaching(whenDone)) { return false; } - 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); + 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); + } } - } - 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 (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 (toFetch.isEmpty()) { 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(() -> { - 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); + 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; } } - connection.disconnect(); + if (whenDone != null) { + whenDone.run(); + } + return; } - } 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(); - } - return; }); - }); - } catch (SQLException e) { - throw new SQLUUIDHandlerException("Couldn't select :s", e); + } catch (SQLException e) { + throw new SQLUUIDHandlerException("Couldn't select :s", e); + } } }); return true; @@ -158,32 +172,34 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { if (ifFetch == null) { return; } - 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.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.runTask(ifFetch); }); } @@ -199,15 +215,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { @Override public boolean add(final StringWrapper name, final UUID uuid) { // Ignoring duplicates if (super.add(name, uuid)) { - 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(); + 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(); + } } }); return true; @@ -220,16 +239,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { */ @Override public void rename(final UUID uuid, final StringWrapper name) { super.rename(uuid, name); - 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(); + 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(); + } } }); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java index 9d694c1ec..c2b4b4d95 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.configuration; -import javax.annotation.Nonnull; import java.util.Map; /** @@ -21,7 +20,7 @@ public interface Configuration extends ConfigurationSection { * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ - @Override void addDefault(@Nonnull String path, Object value); + @Override void addDefault(String path, Object value); /** * Sets the default values of the given paths as provided. diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java index f86016031..5d13920e4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java @@ -31,7 +31,7 @@ class ConfigurationOptions { * * @return Path separator */ - char pathSeparator() { + public char pathSeparator() { return pathSeparator; } @@ -64,7 +64,7 @@ class ConfigurationOptions { * * @return Whether or not defaults are directly copied */ - boolean copyDefaults() { + public boolean copyDefaults() { return copyDefaults; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java index 9e15a9030..0752dfb57 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.configuration; -import javax.annotation.Nonnull; import java.util.List; import java.util.Map; import java.util.Set; @@ -53,7 +52,7 @@ public interface ConfigurationSection { * default or being set. * @throws IllegalArgumentException Thrown when path is {@code null}. */ - boolean contains(@Nonnull String path); + boolean contains(String path); /** * Checks if this {@link ConfigurationSection} has a value set for the @@ -67,7 +66,7 @@ public interface ConfigurationSection { * having a default. * @throws IllegalArgumentException Thrown when path is {@code null}. */ - boolean isSet(@Nonnull String path); + boolean isSet(String path); /** * Gets the path of this {@link ConfigurationSection} from its root {@link @@ -152,7 +151,7 @@ public interface ConfigurationSection { * @param defaultValue The default value to return if the path is not found. * @return Requested Object. */ - Object getOrDefault(@Nonnull String path, Object defaultValue); + Object get(String path, Object defaultValue); /** * Sets the specified path to the given value. @@ -645,5 +644,5 @@ public interface ConfigurationSection { * @param value Value to set the default to * @throws IllegalArgumentException Thrown if path is {@code null} */ - void addDefault(@Nonnull String path, Object value); + void addDefault(String path, Object value); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java index d1677c54d..20131cbe1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.configuration; -import javax.annotation.Nonnull; import java.util.Map; /** @@ -29,7 +28,7 @@ public class MemoryConfiguration extends MemorySection implements Configuration this.defaults = defaults; } - @Override public void addDefault(@Nonnull String path, Object value) { + @Override public void addDefault(String path, Object value) { if (this.defaults == null) { this.defaults = new MemoryConfiguration(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java index 26f6760c8..0f87931f4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.configuration; -import javax.annotation.Nonnull; import java.util.*; /** @@ -15,12 +14,14 @@ public class MemorySection implements ConfigurationSection { private final String fullPath; /** - * Creates an empty MemorySection for use as a root {@link Configuration} section. + * Creates an empty MemorySection for use as a root {@link Configuration} + * section. * *

Note that calling this without being yourself a {@link Configuration} * will throw an exception! * - * @throws IllegalStateException Thrown if this is not a {@link Configuration} root. + * @throws IllegalStateException Thrown if this is not a {@link + * Configuration} root. */ protected MemorySection() { if (!(this instanceof Configuration)) { @@ -38,9 +39,10 @@ public class MemorySection implements ConfigurationSection { * Creates an empty MemorySection with the specified parent and path. * * @param parent Parent section that contains this own section. - * @param path Path that you may access this section from via the root {@link Configuration}. - * @throws IllegalArgumentException Thrown is parent or path is null, or if parent contains no - * root Configuration. + * @param path Path that you may access this section from via the root + * {@link Configuration}. + * @throws IllegalArgumentException Thrown is parent or path is null, or + * if parent contains no root Configuration. */ protected MemorySection(ConfigurationSection parent, String path) { this.path = path; @@ -109,8 +111,8 @@ public class MemorySection implements ConfigurationSection { } /** - * Creates a full path to the given {@link ConfigurationSection} from its root {@link - * Configuration}. + * Creates a full path to the given {@link ConfigurationSection} from its + * root {@link Configuration}. * *

You may use this method for any given {@link ConfigurationSection}, not * only {@link MemorySection}. @@ -124,8 +126,8 @@ public class MemorySection implements ConfigurationSection { } /** - * Creates a relative path to the given {@link ConfigurationSection} from the given relative - * section. + * Creates a relative path to the given {@link ConfigurationSection} from + * the given relative section. * *

You may use this method for any given {@link ConfigurationSection}, not * only {@link MemorySection}. @@ -198,11 +200,11 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override public boolean contains(@Nonnull String path) { + @Override public boolean contains(String path) { return get(path) != null; } - @Override public boolean isSet(@Nonnull String path) { + @Override public boolean isSet(String path) { Configuration root = getRoot(); if (root == null) { return false; @@ -210,7 +212,7 @@ public class MemorySection implements ConfigurationSection { if (root.options().copyDefaults()) { return contains(path); } - return getOrDefault(path, null) != null; + return get(path, null) != null; } @Override public String getCurrentPath() { @@ -229,7 +231,7 @@ public class MemorySection implements ConfigurationSection { return this.parent; } - @Override public void addDefault(@Nonnull String path, Object value) { + @Override public void addDefault(String path, Object value) { Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot add default without root"); @@ -289,10 +291,14 @@ public class MemorySection implements ConfigurationSection { } @Override public Object get(String path) { - return getOrDefault(path, getDefault(path)); + return get(path, getDefault(path)); } - @Override public Object getOrDefault(@Nonnull String path, Object defaultValue) { + @Override public Object get(String path, Object defaultValue) { + if (path == null) { + throw new NullPointerException("Path cannot be null"); + } + if (path.isEmpty()) { return this; } @@ -324,7 +330,7 @@ public class MemorySection implements ConfigurationSection { return result; } } - return section.getOrDefault(key, defaultValue); + return section.get(key, defaultValue); } @Override public ConfigurationSection createSection(String path) { @@ -379,7 +385,7 @@ public class MemorySection implements ConfigurationSection { } @Override public String getString(String path, String def) { - Object val = getOrDefault(path, def); + Object val = get(path, def); if (val != null) { return val.toString(); } else { @@ -398,7 +404,7 @@ public class MemorySection implements ConfigurationSection { } @Override public int getInt(String path, int def) { - Object val = getOrDefault(path, def); + Object val = get(path, def); return toInt(val, def); } @@ -417,7 +423,7 @@ public class MemorySection implements ConfigurationSection { } @Override public boolean getBoolean(String path, boolean defaultValue) { - Object val = getOrDefault(path, defaultValue); + Object val = get(path, defaultValue); if (val instanceof Boolean) { return (Boolean) val; } else { @@ -436,7 +442,7 @@ public class MemorySection implements ConfigurationSection { } @Override public double getDouble(String path, double defaultValue) { - Object val = getOrDefault(path, defaultValue); + Object val = get(path, defaultValue); return toDouble(val, defaultValue); } @@ -451,7 +457,7 @@ public class MemorySection implements ConfigurationSection { } @Override public long getLong(String path, long def) { - Object val = getOrDefault(path, def); + Object val = get(path, def); return toLong(val, def); } @@ -467,7 +473,7 @@ public class MemorySection implements ConfigurationSection { } @Override public List getList(String path, List def) { - Object val = getOrDefault(path, def); + Object val = get(path, def); return (List) ((val instanceof List) ? val : def); } @@ -688,12 +694,12 @@ public class MemorySection implements ConfigurationSection { } @Override public ConfigurationSection getConfigurationSection(String path) { - Object val = getOrDefault(path, null); + Object val = get(path, null); if (val != null) { return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; } - val = getOrDefault(path, getDefault(path)); + val = get(path, getDefault(path)); return (val instanceof ConfigurationSection) ? createSection(path) : null; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java index bc0b375e9..668509bf3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java @@ -4,7 +4,6 @@ import com.github.intellectualsites.plotsquared.configuration.Configuration; import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException; import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration; -import javax.annotation.Nonnull; import java.io.*; import java.nio.charset.StandardCharsets; @@ -83,7 +82,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { * a valid Configuration. * @throws IllegalArgumentException Thrown when file is null. */ - public void load(@Nonnull File file) throws IOException, InvalidConfigurationException { + public void load(File file) throws IOException, InvalidConfigurationException { FileInputStream stream = new FileInputStream(file); 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 1e694f05a..d8c41c3da 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 = yaml.load(contents); + input = (Map) yaml.load(contents); } catch (YAMLException e) { throw new InvalidConfigurationException(e); } catch (ClassCastException ignored) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java index 730527652..a17bc3538 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java @@ -42,7 +42,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { * * @return How much to indent by */ - int indent() { + public int indent() { return indent; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java index cdc5eb821..1f52f7abb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java @@ -9,7 +9,7 @@ import org.yaml.snakeyaml.nodes.Tag; import java.util.LinkedHashMap; import java.util.Map; -class YamlConstructor extends SafeConstructor { +public class YamlConstructor extends SafeConstructor { YamlConstructor() { yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java index 2f6559a4e..e50ec9e8e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java @@ -76,9 +76,7 @@ public interface IPlotMain extends ILogger { * * @return */ - default String getPluginName() { - return "PlotSquared"; - } + String getPluginName(); /** * Get the version of Minecraft that is running. diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java index 9dfbf2ffb..b7eb33b83 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java @@ -1,6 +1,6 @@ package com.github.intellectualsites.plotsquared.plot; public enum Platform { - Bukkit, Sponge, Spigot + Bukkit, Sponge, Spigot, Cauldron } 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 63bbf8142..1db55bf28 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,8 @@ 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; @@ -214,8 +214,11 @@ import java.util.zip.ZipInputStream; } // Economy if (Settings.Enabled_Components.ECONOMY) { - TaskManager - .runTask(() -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler()); + TaskManager.runTask(new Runnable() { + @Override public void run() { + EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler(); + } + }); } /* // Check for updates @@ -244,20 +247,21 @@ import java.util.zip.ZipInputStream; 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); + 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); + } } } }, 1); @@ -338,21 +342,25 @@ import java.util.zip.ZipInputStream; } private void startUuidCatching() { - 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.owner) == null) { - UUIDHandler.implementation.unknown.add(plot.owner); + 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); + } + } } - } + }); + startExpiryTasks(); } }); - startExpiryTasks(); - }); + } }, 20); } @@ -487,8 +495,11 @@ import java.util.zip.ZipInputStream; if (this.plots_tmp == null) { this.plots_tmp = new HashMap<>(); } - HashMap map = - this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>()); + HashMap map = this.plots_tmp.get(area.toString()); + if (map == null) { + map = new HashMap<>(); + this.plots_tmp.put(area.toString(), map); + } for (Plot plot : area.getPlots()) { map.put(plot.getId(), plot); } @@ -508,7 +519,8 @@ import java.util.zip.ZipInputStream; } /** - * Get all the base plots in a single set (for merged plots it just returns the bottom plot). + * Get all the base plots in a single set (for merged plots it just returns + * the bottom plot). * * @return Set of base Plots */ @@ -555,7 +567,11 @@ import java.util.zip.ZipInputStream; result.add(plot); } } - overflow.sort(Comparator.comparingInt(Plot::hashCode)); + Collections.sort(overflow, new Comparator() { + @Override public int compare(Plot a, Plot b) { + return a.hashCode() - b.hashCode(); + } + }); result.addAll(overflow); return result; } @@ -564,11 +580,13 @@ import java.util.zip.ZipInputStream; * Sort plots by hashcode. * * @param plots the collection of plots to sort - * @return the sorted collection {@link #sortPlots(Collection, SortType, PlotArea)} which has + * @return the sorted collection + * @deprecated Unchecked, please use + * {@link #sortPlots(Collection, SortType, PlotArea)} which has * additional checks before calling this */ - // TODO: Re-evaluate this (previously public and deprecated), as it's being used internally - private ArrayList sortPlotsByHash(Collection plots) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public ArrayList sortPlotsByHash(Collection plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; @@ -609,11 +627,19 @@ import java.util.zip.ZipInputStream; } } Collections.addAll(result, overflowArray); - result.addAll(extra); + for (Plot plot : extra) { + result.add(plot); + } return result; } - private void sortPlotsByHash(Plot[] input) { + /** + * Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will in turn call this. + * + * @param input an array of plots to sort + */ + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public void sortPlotsByHash(Plot[] input) { List[] bucket = new ArrayList[32]; for (int i = 0; i < bucket.length; i++) { bucket[i] = new ArrayList<>(); @@ -640,7 +666,8 @@ import java.util.zip.ZipInputStream; } } - private ArrayList sortPlotsByTimestamp(Collection plots) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public ArrayList sortPlotsByTimestamp(Collection plots) { int hardMax = 256000; int max = 0; int overflowSize = 0; @@ -681,31 +708,48 @@ import java.util.zip.ZipInputStream; } } Collections.addAll(result, overflowArray); - result.addAll(extra); + for (Plot plot : extra) { + result.add(plot); + } return result; } /** * Sort plots by creation timestamp. + * + * @param input + * @return + * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks */ - - private List sortPlotsByModified(Collection input) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public List sortPlotsByModified(Collection input) { List list; if (input instanceof List) { list = (List) input; } else { list = new ArrayList<>(input); } - list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.owner))); + 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)); + } + }); return list; } + public ArrayList sortPlots(Collection plots) { + return sortPlots(plots, SortType.DISTANCE_FROM_ORIGIN, null); + } + /** - * Sort a collection of plots by world (with a priority world), then by hashcode. + * Sort a collection of plots by world (with a priority world), then + * by hashcode. * * @param plots the plots to sort * @param type The sorting method to use for each world (timestamp, or hash) - * @param priorityArea Use null, "world", or "gibberish" if you want default world order + * @param priorityArea Use null, "world", or "gibberish" if you + * want default world order * @return ArrayList of plot */ public ArrayList sortPlots(Collection plots, SortType type, @@ -720,7 +764,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; @@ -735,15 +779,17 @@ import java.util.zip.ZipInputStream; } } List areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); - areas.sort((a, b) -> { - if (priorityArea != null) { - if (a.equals(priorityArea)) { - return -1; - } else if (b.equals(priorityArea)) { - return 1; + 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; + } } + return a.hashCode() - b.hashCode(); } - return a.hashCode() - b.hashCode(); }); ArrayList toReturn = new ArrayList<>(plots.size()); for (PlotArea area : areas) { @@ -768,7 +814,8 @@ import java.util.zip.ZipInputStream; } /** - * A more generic way to filter plots - make your own method if you need complex filters. + * A more generic way to filter plots - make your own method + * if you need complex filters. * * @param filters the filter * @return a filtered set of plots @@ -813,29 +860,28 @@ import java.util.zip.ZipInputStream; return result; } - //TODO look at uncommenting or deleting tis. Is it useful and will it work? - //If it is readded make sure there is proper javadoc documentation for it. -/* - public void setPlots(HashMap> plots) { - if (this.plots_tmp == null) { - this.plots_tmp = new HashMap<>(); - } - for (Entry> entry : plots.entrySet()) { - String world = entry.getKey(); - PlotArea area = getPlotArea(world, null); - if (area == null) { - HashMap map = this.plots_tmp - .computeIfAbsent(world, k -> new HashMap<>()); - map.putAll(entry.getValue()); - } else { - for (Plot plot : entry.getValue().values()) { - plot.setArea(area); - area.addPlot(plot); + public void setPlots(HashMap> plots) { + if (this.plots_tmp == null) { + this.plots_tmp = new HashMap<>(); + } + for (Entry> entry : plots.entrySet()) { + 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); + } + map.putAll(entry.getValue()); + } else { + for (Plot plot : entry.getValue().values()) { + plot.setArea(area); + area.addPlot(plot); + } + } } - } } - } -*/ /** * Get all the plots owned by a player name. @@ -980,9 +1026,8 @@ import java.util.zip.ZipInputStream; public boolean hasPlot(final UUID uuid) { for (final PlotArea area : plotAreaManager.getAllPlotAreas()) { - if (area.hasPlot(uuid)) { + if (area.hasPlot(uuid)) return true; - } } return false; } @@ -1142,8 +1187,9 @@ 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); } @@ -1552,8 +1598,8 @@ import java.util.zip.ZipInputStream; // Close the connection DBFunc.close(); UUIDHandler.handleShutdown(); - } catch (NullPointerException exception) { - exception.printStackTrace(); + } catch (NullPointerException ignored) { + ignored.printStackTrace(); PlotSquared.log("&cCould not close database connection!"); } } @@ -1579,11 +1625,6 @@ import java.util.zip.ZipInputStream; return; } DBFunc.dbManager = new SQLManager(database, Storage.PREFIX, false); - PlotSquared.log("GETTING PLOTS NOW AND STORING TO PLOTS_TMP"); - for (PlotArea allPlotArea : plotAreaManager.getAllPlotAreas()) { - PlotSquared.log(allPlotArea.toString()); - } - this.plots_tmp = DBFunc.getPlots(); if (plotAreaManager instanceof SinglePlotAreaManager) { SinglePlotArea area = ((SinglePlotAreaManager) plotAreaManager).getArea(); @@ -1656,16 +1697,18 @@ 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 (IOException exception) { - exception.printStackTrace(); + } catch (Throwable ignore) { + ignore.printStackTrace(); } Settings.save(configFile); config = YamlConfiguration.loadConfiguration(configFile); } /** - * Setup all configuration files
- Config: settings.yml
- Storage: storage.yml
- - * Translation: PlotSquared.use_THIS.yml, style.yml
+ * Setup all configuration files
+ * - Config: settings.yml
+ * - Storage: storage.yml
+ * - Translation: PlotSquared.use_THIS.yml, style.yml
*/ public boolean setupConfigs() { File folder = new File(this.IMP.getDirectory(), "config"); @@ -1916,6 +1959,7 @@ import java.util.zip.ZipInputStream; * Note: An applicable plot area may not include the location i.e. clusters * * @param location the location + * @return */ public PlotArea getApplicablePlotArea(@NonNull final Location location) { return plotAreaManager.getApplicablePlotArea(location); @@ -1972,72 +2016,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 - * < p> - *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- *

- * 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/commands/Area.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java index ee7c1cb23..9dc5ce20e 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 @@ -104,34 +104,36 @@ import java.util.Set; final String path = "worlds." + area.worldname + ".areas." + area.id + '-' + object.min + '-' + object.max; - 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); + 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); } - } else { - MainUtil.sendMessage(player, - "An error occurred while creating the world: " - + area.worldname); } }; if (hasConfirmation(player)) { @@ -226,30 +228,32 @@ import java.util.Set; C.SETUP_WORLD_TAKEN.send(player, pa.worldname); return false; } - 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.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 = 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(); + } } }; if (hasConfirmation(player)) { @@ -418,7 +422,11 @@ import java.util.Set; @Override public void run(ChunkLoc value) { AugmentedUtils.generate(area.worldname, value.x, value.z, null); } - }, () -> player.sendMessage("Regen complete")); + }, new Runnable() { + @Override public void run() { + player.sendMessage("Regen complete"); + } + }); return true; } case "goto": 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 e49155b8d..88f102967 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 @@ -82,14 +82,22 @@ public class Claim extends SubCommand { if (plot.canClaim(player)) { plot.owner = player.getUUID(); final String finalSchematic = schematic; - 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); - } + 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); + } + } + }); } - }), () -> sendMessage(player, C.PLOT_NOT_CLAIMED)); + }, new Runnable() { + @Override public void run() { + 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/Cluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java index b4b24021f..9145d1b3d 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 @@ -301,7 +301,6 @@ import java.util.UUID; PlotArea area = player.getApplicablePlotArea(); if (area == null) { C.NOT_IN_PLOT_WORLD.send(player); - return false; } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { @@ -347,7 +346,6 @@ import java.util.UUID; PlotArea area = player.getApplicablePlotArea(); if (area == null) { C.NOT_IN_PLOT_WORLD.send(player); - return false; } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { @@ -406,7 +404,6 @@ import java.util.UUID; PlotArea area = player.getApplicablePlotArea(); if (area == null) { C.NOT_IN_PLOT_WORLD.send(player); - return false; } PlotCluster cluster; if (args.length == 2) { @@ -442,6 +439,7 @@ import java.util.UUID; PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) { PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { + player.getLocation().getWorld(); plot.unclaim(); } } @@ -463,7 +461,6 @@ import java.util.UUID; PlotArea area = player.getApplicablePlotArea(); if (area == null) { C.NOT_IN_PLOT_WORLD.send(player); - return false; } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { @@ -536,7 +533,6 @@ import java.util.UUID; PlotArea area = player.getApplicablePlotArea(); if (area == null) { C.NOT_IN_PLOT_WORLD.send(player); - return false; } PlotCluster cluster; if (args.length == 2) { @@ -584,7 +580,6 @@ import java.util.UUID; PlotArea area = player.getApplicablePlotArea(); if (area == null) { C.NOT_IN_PLOT_WORLD.send(player); - return false; } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { 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 44d0e5593..040fd97b8 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 @@ -65,7 +65,6 @@ import java.util.concurrent.atomic.AtomicBoolean; sizes.add(size - 1); } // Sort plots by size (buckets?)] - //noinspection unchecked ArrayList[] buckets = new ArrayList[maxSize]; for (int i = 0; i < plots.size(); i++) { Plot plot = plots.get(i); @@ -127,11 +126,13 @@ import java.util.concurrent.atomic.AtomicBoolean; } i++; final AtomicBoolean result = new AtomicBoolean(false); - result.set(origin.move(possible, () -> { - if (result.get()) { - MainUtil.sendMessage(player, - "Moving: " + origin + " -> " + possible); - TaskManager.runTaskLater(task, 1); + result.set(origin.move(possible, new Runnable() { + @Override public void run() { + 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/Database.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java index e94850121..b760bc282 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,18 +30,25 @@ import java.util.Map.Entry; public static void insertPlots(final SQLManager manager, final List plots, final PlotPlayer player) { - 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(); + 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(); + } } }); } @@ -123,13 +130,20 @@ import java.util.Map.Entry; plots.add(plot); } } else { - HashMap plotmap = PlotSquared.get().plots_tmp - .computeIfAbsent(areaname, k -> new HashMap<>()); + HashMap plotmap = + PlotSquared.get().plots_tmp.get(areaname); + if (plotmap == null) { + plotmap = new HashMap<>(); + PlotSquared.get().plots_tmp.put(areaname, plotmap); + } plotmap.putAll(entry.getValue()); } } - DBFunc.createPlotsAndData(plots, - () -> MainUtil.sendMessage(player, "&6Database conversion finished!")); + DBFunc.createPlotsAndData(plots, new Runnable() { + @Override public void run() { + 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/Help.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java index ff697953c..f0ff64af1 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,7 +57,9 @@ 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")) { + if (StringMan.isEqualIgnoreCase(cat, "all")) { + catEnum = null; + } else { for (CommandCategory c : CommandCategory.values()) { if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { catEnum = c; 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 908e35afc..5c7cfc0ac 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 @@ -165,8 +165,9 @@ import java.util.Optional; inbox.clearInbox(plot); Optional> comments = plot.getSettings().getComments(inbox.toString()); - comments - .ifPresent(plotComments -> plot.getSettings().removeComments(plotComments)); + if (comments.isPresent()) { + plot.getSettings().removeComments(comments.get()); + } MainUtil.sendMessage(player, C.COMMENT_REMOVED, "*"); return true; default: 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 94152175e..a944be561 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 @@ -60,9 +60,9 @@ public class Merge extends SubCommand { } final PlotArea plotArea = plot.getArea(); Expression priceExr = - plotArea.PRICES.getOrDefault("merge", Expression.constant(0d)); + plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; final int size = plot.getConnectedPlots().size(); - final double price = priceExr.evaluate((double) size); + final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d && EconHandler.manager.getMoney(player) < price) { sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); 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 8cd4d9e56..b8b38e298 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 @@ -108,7 +108,9 @@ import java.util.UUID; if (unknown && UUIDHandler.getName(plot.owner) != null) { continue; } - toDelete.addAll(plot.getConnectedPlots()); + for (Plot current : plot.getConnectedPlots()) { + toDelete.add(current); + } } if (PlotSquared.get().plots_tmp != null) { for (Entry> entry : PlotSquared.get().plots_tmp @@ -141,21 +143,23 @@ import java.util.UUID; } String cmd = "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; - 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); + 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(); } - 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 d8103e5b8..7141df96e 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,10 +10,8 @@ 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.ArrayList; -import java.util.HashMap; +import java.util.*; 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, @@ -24,23 +22,25 @@ import java.util.UUID; switch (args[0].toLowerCase()) { case "next": { ArrayList plots = new ArrayList<>(PlotSquared.get().getBasePlots()); - plots.sort((p1, p2) -> { - double v1 = 0; - if (!p1.getRatings().isEmpty()) { - for (Entry entry : p1.getRatings().entrySet()) { - v1 -= 11 - entry.getValue().getAverageRating(); + 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(); + } } - } - double v2 = 0; - if (!p2.getRatings().isEmpty()) { - for (Entry entry : p2.getRatings().entrySet()) { - v2 -= 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; } - if (v1 == v2) { - return -0; - } - return v2 > v1 ? 1 : -1; }); UUID uuid = player.getUUID(); for (Plot p : plots) { @@ -123,7 +123,7 @@ import java.util.UUID; return true; } }; - inventory.setItem(0, new PlotItemStack("minecraft:brown_wool", 0, "0/8")); + 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")); @@ -137,9 +137,11 @@ import java.util.UUID; }; if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { - TaskManager.runTaskAsync(() -> { - plot.getSettings().ratings = DBFunc.getRatings(plot); - run.run(); + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); + } }); return true; } @@ -165,22 +167,26 @@ import java.util.UUID; return false; } final UUID uuid = player.getUUID(); - 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()); + 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()); + } } }; if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { - TaskManager.runTaskAsync(() -> { - plot.getSettings().ratings = DBFunc.getRatings(plot); - run.run(); + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); + } }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java index e5341103d..a26d4d02e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java @@ -143,6 +143,14 @@ public interface AbstractDB { */ void setFlags(Plot plot, HashMap, Object> flags); + /** + * Set cluster flags. + * + * @param cluster PlotCluster Object + * @param flags flags to set (flag[]) + */ + void setFlags(PlotCluster cluster, HashMap, Object> flags); + /** * Rename a cluster to the given name. * diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java index 1127a6ed2..5050c699f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java @@ -13,7 +13,7 @@ import java.util.*; * Database Functions * - These functions do not update the local plot objects and only make changes to the DB */ -@SuppressWarnings("deprecation") public class DBFunc { +public class DBFunc { /** * The "global" uuid. */ @@ -298,6 +298,17 @@ import java.util.*; DBFunc.dbManager.setFlags(plot, flags); } + public static void setFlags(PlotCluster cluster, HashMap, Object> flags) { + if (dbManager == null) { + return; + } + DBFunc.dbManager.setFlags(cluster, flags); + } + + /** + * @param plot + * @param alias + */ public static void setAlias(Plot plot, String alias) { if (plot.temp == -1 || dbManager == null) { return; @@ -319,6 +330,10 @@ import java.util.*; DBFunc.dbManager.purge(area, plotIds); } + /** + * @param plot + * @param position + */ public static void setPosition(Plot plot, String position) { if (plot.temp == -1 || dbManager == null) { return; @@ -326,6 +341,10 @@ import java.util.*; DBFunc.dbManager.setPosition(plot, position); } + /** + * @param plot + * @param comment + */ public static void removeComment(Plot plot, PlotComment comment) { if (plot.temp == -1 || dbManager == null) { return; @@ -340,6 +359,10 @@ import java.util.*; DBFunc.dbManager.clearInbox(plot, inbox); } + /** + * @param plot + * @param comment + */ public static void setComment(Plot plot, PlotComment comment) { if (plot != null && plot.temp == -1 || dbManager == null) { return; @@ -347,6 +370,9 @@ import java.util.*; DBFunc.dbManager.setComment(plot, comment); } + /** + * @param plot + */ public static void getComments(Plot plot, String inbox, RunnableVal> whenDone) { if (plot != null && plot.temp == -1 || dbManager == null) { @@ -355,6 +381,10 @@ import java.util.*; DBFunc.dbManager.getComments(plot, inbox, whenDone); } + /** + * @param plot + * @param uuid + */ public static void removeTrusted(Plot plot, UUID uuid) { if (plot.temp == -1 || dbManager == null) { return; @@ -362,6 +392,10 @@ import java.util.*; DBFunc.dbManager.removeTrusted(plot, uuid); } + /** + * @param cluster + * @param uuid + */ public static void removeHelper(PlotCluster cluster, UUID uuid) { if (dbManager == null) { return; @@ -369,6 +403,9 @@ import java.util.*; DBFunc.dbManager.removeHelper(cluster, uuid); } + /** + * @param cluster + */ public static void createCluster(PlotCluster cluster) { if (dbManager == null) { return; @@ -376,6 +413,11 @@ import java.util.*; DBFunc.dbManager.createCluster(cluster); } + /** + * @param current + * @param min + * @param max + */ public static void resizeCluster(PlotCluster current, PlotId min, PlotId max) { if (dbManager == null) { return; @@ -383,6 +425,10 @@ import java.util.*; DBFunc.dbManager.resizeCluster(current, min, max); } + /** + * @param plot + * @param uuid + */ public static void removeMember(Plot plot, UUID uuid) { if (plot.temp == -1 || dbManager == null) { return; @@ -390,6 +436,10 @@ import java.util.*; DBFunc.dbManager.removeMember(plot, uuid); } + /** + * @param cluster + * @param uuid + */ public static void removeInvited(PlotCluster cluster, UUID uuid) { if (dbManager == null) { return; @@ -397,6 +447,10 @@ import java.util.*; DBFunc.dbManager.removeInvited(cluster, uuid); } + /** + * @param plot + * @param uuid + */ public static void setTrusted(Plot plot, UUID uuid) { if (plot.temp == -1 || dbManager == null) { return; @@ -411,6 +465,10 @@ import java.util.*; DBFunc.dbManager.setHelper(cluster, uuid); } + /** + * @param plot + * @param uuid + */ public static void setMember(Plot plot, UUID uuid) { if (plot.temp == -1 || dbManager == null) { return; @@ -425,6 +483,10 @@ import java.util.*; DBFunc.dbManager.setInvited(cluster, uuid); } + /** + * @param plot + * @param uuid + */ public static void removeDenied(Plot plot, UUID uuid) { if (plot.temp == -1 || dbManager == null) { return; @@ -432,6 +494,10 @@ import java.util.*; DBFunc.dbManager.removeDenied(plot, uuid); } + /** + * @param plot + * @param uuid + */ public static void setDenied(Plot plot, UUID uuid) { if (plot.temp == -1 || dbManager == null) { return; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/Database.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/Database.java index 8626a1a24..4acecc01f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/Database.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/Database.java @@ -11,9 +11,9 @@ import java.sql.Statement; * @author -_Husky_- * @author tips48 */ -public interface Database { +public abstract class Database { - Connection forceConnection() throws SQLException, ClassNotFoundException; + public abstract Connection forceConnection() throws SQLException, ClassNotFoundException; /** * Opens a connection with the database. @@ -22,7 +22,7 @@ public interface Database { * @throws SQLException if the connection can not be opened * @throws ClassNotFoundException if the driver cannot be found */ - Connection openConnection() throws SQLException, ClassNotFoundException; + public abstract Connection openConnection() throws SQLException, ClassNotFoundException; /** * Checks if a connection is open with the database. @@ -30,14 +30,14 @@ public interface Database { * @return true if the connection is open * @throws SQLException if the connection cannot be checked */ - boolean checkConnection() throws SQLException; + public abstract boolean checkConnection() throws SQLException; /** * Gets the connection with the database. * * @return Connection with the database, null if none */ - Connection getConnection(); + public abstract Connection getConnection(); /** * Closes the connection with the database. @@ -45,7 +45,7 @@ public interface Database { * @return true if successful * @throws SQLException if the connection cannot be closed */ - boolean closeConnection() throws SQLException; + public abstract boolean closeConnection() throws SQLException; /** * Executes a SQL Query. @@ -56,7 +56,7 @@ public interface Database { * @throws SQLException If the query cannot be executed * @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()} */ - ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; + public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; /** * Executes an Update SQL Query. @@ -68,5 +68,5 @@ public interface Database { * @throws SQLException If the query cannot be executed * @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()} */ - int updateSQL(String query) throws SQLException, ClassNotFoundException; + public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException; } 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 4a0e655c5..7e7df9124 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 @@ -11,7 +11,7 @@ import java.sql.*; * @author -_Husky_- * @author tips48 */ -public class MySQL implements Database { +public class MySQL extends Database { private final String user; private final String database; 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 3e197a16d..66a21174d 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 @@ -14,7 +14,6 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.google.common.base.Charsets; -import javax.annotation.Nonnull; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -49,7 +48,13 @@ import java.util.concurrent.atomic.AtomicInteger; */ public volatile Queue notifyTasks; /** - * plot plot_denied plot_helpers plot_trusted plot_comments plot_settings plot_rating + * plot + * plot_denied + * plot_helpers + * plot_trusted + * plot_comments + * plot_settings + * plot_rating */ public volatile ConcurrentHashMap> plotTasks; /** @@ -57,7 +62,10 @@ import java.util.concurrent.atomic.AtomicInteger; */ public volatile ConcurrentHashMap> playerTasks; /** - * cluster cluster_helpers cluster_invited cluster_settings + * cluster + * cluster_helpers + * cluster_invited + * cluster_settings */ public volatile ConcurrentHashMap> clusterTasks; // Private @@ -67,7 +75,10 @@ import java.util.concurrent.atomic.AtomicInteger; /** * Constructor * - * @param p prefix + * @param database + * @param p prefix + * @throws SQLException + * @throws ClassNotFoundException */ public SQLManager(final Database database, String p, boolean debug) throws SQLException, ClassNotFoundException { @@ -110,40 +121,42 @@ import java.util.concurrent.atomic.AtomicInteger; } catch (SQLException e) { e.printStackTrace(); } - 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(); + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + long last = System.currentTimeMillis(); + while (true) { + if (SQLManager.this.closed) { + break; } - if (!sendBatch()) { - try { - if (!getNotifyTasks().isEmpty()) { - for (Runnable task : getNotifyTasks()) { - TaskManager.runTask(task); + 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(); } - getNotifyTasks().clear(); + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); } - Thread.sleep(50); + } + } else { + try { + Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } - } else { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } } } }); @@ -183,9 +196,15 @@ import java.util.concurrent.atomic.AtomicInteger; return this.notifyTasks; } - public synchronized void addPlotTask(@Nonnull Plot plot, UniqueStatement task) { - Queue tasks = - this.plotTasks.computeIfAbsent(plot, plot1 -> new ConcurrentLinkedQueue<>()); + public synchronized void addPlotTask(Plot plot, UniqueStatement task) { + if (plot == null) { + plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE)); + } + Queue tasks = this.plotTasks.get(plot); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + this.plotTasks.put(plot, tasks); + } if (task == null) { task = new UniqueStatement(String.valueOf(plot.hashCode())) { @@ -211,8 +230,11 @@ import java.util.concurrent.atomic.AtomicInteger; if (uuid == null) { return; } - Queue tasks = - this.playerTasks.computeIfAbsent(uuid, uuid1 -> new ConcurrentLinkedQueue<>()); + Queue tasks = this.playerTasks.get(uuid); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + this.playerTasks.put(uuid, tasks); + } if (task == null) { task = new UniqueStatement(String.valueOf(uuid.hashCode())) { @@ -235,8 +257,11 @@ import java.util.concurrent.atomic.AtomicInteger; } public synchronized void addClusterTask(PlotCluster cluster, UniqueStatement task) { - Queue tasks = this.clusterTasks - .computeIfAbsent(cluster, plotCluster -> new ConcurrentLinkedQueue<>()); + Queue tasks = this.clusterTasks.get(cluster); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + this.clusterTasks.put(cluster, tasks); + } if (task == null) { task = new UniqueStatement(String.valueOf(cluster.hashCode())) { @@ -490,74 +515,92 @@ import java.util.concurrent.atomic.AtomicInteger; } @Override public void createPlotsAndData(final List myList, final Runnable whenDone) { - 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<>(); + 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<>(); - // 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)); + // 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)); + } + } } - for (UUID uuid : plot.getMembers()) { - trusted.add(new UUIDPair(id, uuid)); - } - for (UUID uuid : plot.getTrusted()) { - helpers.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(); + } + } + }); + } + }); + } + }); } + }); + } 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(); } } } - 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(); } - }); - } 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(); } } }); @@ -886,7 +929,11 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(1, pair.id); } }; - addGlobalTask(() -> setBulk(myList, mod, whenDone)); + addGlobalTask(new Runnable() { + @Override public void run() { + setBulk(myList, mod, whenDone); + } + }); } public void createEmptySettings(final ArrayList myList, final Runnable whenDone) { @@ -930,7 +977,11 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(1, id); } }; - addGlobalTask(() -> setBulk(myList, mod, whenDone)); + addGlobalTask(new Runnable() { + @Override public void run() { + setBulk(myList, mod, whenDone); + } + }); } public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) { @@ -975,16 +1026,14 @@ import java.util.concurrent.atomic.AtomicInteger; + "plot_settings`(`plot_plot_id`) VALUES(?)"); } }); - if (success != null) { + if (success != null) addNotifyTask(success); - } return; } } } - if (failure != null) { + if (failure != null) failure.run(); - } } }); } @@ -1046,6 +1095,8 @@ import java.util.concurrent.atomic.AtomicInteger; /** * Create tables. + * + * @throws SQLException */ @Override public void createTables() throws SQLException { String[] tables = @@ -1294,6 +1345,8 @@ import java.util.concurrent.atomic.AtomicInteger; /** * Delete a plot. + * + * @param plot */ @Override public void delete(final Plot plot) { PlotSquared.debug( @@ -1319,6 +1372,9 @@ import java.util.concurrent.atomic.AtomicInteger; /** * Create plot settings + * + * @param id + * @param plot */ @Override public void createPlotSettings(final int id, Plot plot) { PlotSquared.debug( @@ -1554,12 +1610,12 @@ import java.util.concurrent.atomic.AtomicInteger; ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas"); if (areaSection != null) { - areaSection.getKeys(false).forEach(s -> { - String[] split = s.split("(? { + o = resultSet.getString("owner"); + user = uuids.get(o); + if (user == null) { try { - return UUID.fromString(s); - } catch (IllegalArgumentException ignored) { + user = UUID.fromString(o); + } catch (IllegalArgumentException e) { if (Settings.UUID.FORCE_LOWERCASE) { - return UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + s.toLowerCase()) + user = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + o.toLowerCase()) .getBytes(Charsets.UTF_8)); } else { - return UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + s).getBytes(Charsets.UTF_8)); + user = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + o).getBytes(Charsets.UTF_8)); } } - }); + uuids.put(o, user); + } long time; try { Timestamp timestamp = resultSet.getTimestamp("timestamp"); @@ -1627,12 +1685,12 @@ import java.util.concurrent.atomic.AtomicInteger; time = System.currentTimeMillis() + id; } } - Plot plot = 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) { - Plot last = map.put(plot.getId(), plot); + Plot last = map.put(p.getId(), p); if (last != null) { if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(last.temp); @@ -1645,9 +1703,9 @@ import java.util.concurrent.atomic.AtomicInteger; } else { map = new HashMap<>(); newPlots.put(areaid, map); - map.put(plot.getId(), plot); + map.put(p.getId(), p); } - plots.put(id, plot); + plots.put(id, p); } deleteRows(toDelete, this.prefix + "plot", "id"); } @@ -1658,8 +1716,12 @@ import java.util.concurrent.atomic.AtomicInteger; ArrayList toDelete = new ArrayList<>(); while (r.next()) { id = r.getInt("plot_plot_id"); - owner = r.getString("player"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + o = r.getString("player"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } Plot plot = plots.get(id); if (plot != null) { plot.getSettings().getRatings().put(user, r.getInt("rating")); @@ -1683,8 +1745,12 @@ import java.util.concurrent.atomic.AtomicInteger; ArrayList toDelete = new ArrayList<>(); while (r.next()) { id = r.getInt("plot_plot_id"); - owner = r.getString("user_uuid"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + o = r.getString("user_uuid"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } Plot plot = plots.get(id); if (plot != null) { plot.getTrusted().add(user); @@ -1707,8 +1773,12 @@ import java.util.concurrent.atomic.AtomicInteger; ArrayList toDelete = new ArrayList<>(); while (r.next()) { id = r.getInt("plot_plot_id"); - owner = r.getString("user_uuid"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + o = r.getString("user_uuid"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } Plot plot = plots.get(id); if (plot != null) { plot.getMembers().add(user); @@ -1731,8 +1801,12 @@ import java.util.concurrent.atomic.AtomicInteger; ArrayList toDelete = new ArrayList<>(); while (r.next()) { id = r.getInt("plot_plot_id"); - owner = r.getString("user_uuid"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + o = r.getString("user_uuid"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } Plot plot = plots.get(id); if (plot != null) { plot.getDenied().add(user); @@ -1771,7 +1845,7 @@ import java.util.concurrent.atomic.AtomicInteger; } catch (Exception ignored) { } } - int m = resultSet.getInt("merged"); + Integer m = resultSet.getInt("merged"); boolean[] merged = new boolean[4]; for (int i = 0; i < 4; i++) { merged[3 - i] = (m & 1 << i) != 0; @@ -1962,98 +2036,103 @@ import java.util.concurrent.atomic.AtomicInteger; * Purge all plots with the following database IDs */ @Override public void purgeIds(final Set uniqueIds) { - addGlobalTask(() -> { - 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; + 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(); } - 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; } - } 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(() -> { - 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(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")); + } } } + 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); } }); } @@ -2444,7 +2523,11 @@ import java.util.concurrent.atomic.AtomicInteger; } resultSet.close(); - TaskManager.runTaskAsync(() -> result.run(metaMap)); + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + result.run(metaMap); + } + }); } }); @@ -2501,11 +2584,18 @@ import java.util.concurrent.atomic.AtomicInteger; } } owner = resultSet.getString("owner"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + user = uuids.get(owner); + if (user == null) { + user = UUID.fromString(owner); + uuids.put(owner, user); + } cluster = new PlotCluster(null, pos1, pos2, user, id); clusters.put(id, cluster); - Set set = - newClusters.computeIfAbsent(areaid, k -> new HashSet<>()); + Set set = newClusters.get(areaid); + if (set == null) { + set = new HashSet<>(); + newClusters.put(areaid, set); + } set.add(cluster); } //Getting helpers @@ -2514,7 +2604,11 @@ import java.util.concurrent.atomic.AtomicInteger; while (resultSet.next()) { id = resultSet.getInt("cluster_id"); owner = resultSet.getString("user_uuid"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + user = uuids.get(owner); + if (user == null) { + user = UUID.fromString(owner); + uuids.put(owner, user); + } cluster = clusters.get(id); if (cluster != null) { cluster.helpers.add(user); @@ -2529,7 +2623,11 @@ import java.util.concurrent.atomic.AtomicInteger; while (resultSet.next()) { id = resultSet.getInt("cluster_id"); owner = resultSet.getString("user_uuid"); - user = uuids.computeIfAbsent(owner, UUID::fromString); + user = uuids.get(owner); + if (user == null) { + user = UUID.fromString(owner); + uuids.put(owner, user); + } cluster = clusters.get(id); if (cluster != null) { cluster.invited.add(user); @@ -2562,7 +2660,7 @@ import java.util.concurrent.atomic.AtomicInteger; } catch (Exception ignored) { } } - int m = resultSet.getInt("merged"); + Integer m = resultSet.getInt("merged"); boolean[] merged = new boolean[4]; for (int i = 0; i < 4; i++) { merged[3 - i] = (m & 1 << i) != 0; @@ -2628,6 +2726,32 @@ import java.util.concurrent.atomic.AtomicInteger; return newClusters; } + @Override public void setFlags(final PlotCluster cluster, HashMap, Object> flags) { + final StringBuilder flag_string = new StringBuilder(); + int i = 0; + for (Entry, Object> flag : flags.entrySet()) { + if (i != 0) { + flag_string.append(','); + } + flag_string.append(flag.getKey().getName()).append(':').append( + flag.getKey().valueToString(flag.getValue()).replaceAll(":", "\u00AF") + .replaceAll(",", "´")); + i++; + } + addClusterTask(cluster, new UniqueStatement("setFlags") { + @Override public void set(PreparedStatement stmt) throws SQLException { + stmt.setString(1, flag_string.toString()); + stmt.setInt(2, getClusterId(cluster)); + } + + @Override public PreparedStatement get() throws SQLException { + return SQLManager.this.connection.prepareStatement( + "UPDATE `" + SQLManager.this.prefix + + "cluster_settings` SET `flags` = ? WHERE `cluster_id` = ?"); + } + }); + } + @Override public void setClusterName(final PlotCluster cluster, final String name) { addClusterTask(cluster, new UniqueStatement("setClusterName") { @Override public void set(PreparedStatement stmt) throws SQLException { @@ -2706,7 +2830,7 @@ import java.util.concurrent.atomic.AtomicInteger; new UniqueStatement("createCluster_settings_" + cluster.hashCode()) { @Override public void set(PreparedStatement stmt) throws SQLException { stmt.setInt(1, getClusterId(cluster)); - stmt.setString(2, cluster.getAlias()); + stmt.setString(2, cluster.settings.getAlias()); } @Override public PreparedStatement get() throws SQLException { @@ -2945,83 +3069,87 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min, final PlotId max) { - 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(); + 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(); + } } } }); } @Override public void replaceUUID(final UUID old, final UUID now) { - 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(); + 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(); + } } }); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java index d42b1d67b..3675ad0cd 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java @@ -9,7 +9,7 @@ import java.sql.*; /** * Connects to and uses a SQLite database. */ -public class SQLite implements Database { +public class SQLite extends Database { private final String dbLocation; private Connection connection; 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 1bac3e526..06be89e15 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 @@ -2,10 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.flag; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.object.Plot; -import com.github.intellectualsites.plotsquared.plot.object.PlotArea; -import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.object.PlotSettings; +import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.google.common.collect.ImmutableSet; @@ -117,7 +114,7 @@ public class FlagManager { * @param flag * @return */ - @SuppressWarnings("deprecation") public static V getPlotFlagRaw(Plot plot, Flag flag) { + public static V getPlotFlagRaw(Plot plot, Flag flag) { if (plot.owner == null) { return null; } @@ -144,6 +141,13 @@ public class FlagManager { return true; } + public static boolean addClusterFlag(PlotCluster cluster, Flag flag, V value) { + getSettingFlag(cluster.area, cluster.settings, flag); + cluster.settings.flags.put(flag, value); + DBFunc.setFlags(cluster, cluster.settings.flags); + return true; + } + /** * Returns a map of the {@link Flag}s and their values for the specified plot. * @@ -213,6 +217,20 @@ public class FlagManager { return true; } + public static boolean removeClusterFlag(PlotCluster cluster, Flag id) { + Object object = cluster.settings.flags.remove(id); + if (object == null) { + return false; + } + boolean result = EventUtil.manager.callFlagRemove(id, object, cluster); + if (!result) { + cluster.settings.flags.put(id, object); + return false; + } + DBFunc.setFlags(cluster, cluster.settings.flags); + return true; + } + public static void setPlotFlags(Plot origin, HashMap, Object> flags) { for (Plot plot : origin.getConnectedPlots()) { if (flags != null && !flags.isEmpty()) { @@ -230,6 +248,20 @@ public class FlagManager { } } + public static void setClusterFlags(PlotCluster cluster, Set flags) { + if (flags != null && !flags.isEmpty()) { + cluster.settings.flags.clear(); + for (Flag flag : flags) { + cluster.settings.flags.put(flag, flag); + } + } else if (cluster.settings.flags.isEmpty()) { + return; + } else { + cluster.settings.flags.clear(); + } + DBFunc.setFlags(cluster, cluster.settings.flags); + } + /** * Get a list of registered {@link Flag} objects based on player permissions. * diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java index 53a9d6891..ea3a23691 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java @@ -277,7 +277,11 @@ public class HybridPlotWorld extends ClassicPlotWorld { id = rotate(id); } int pair = MathMan.pair(x, z); - BaseBlock[] existing = this.G_SCH.computeIfAbsent(pair, k -> new BaseBlock[height]); + BaseBlock[] existing = this.G_SCH.get(pair); + if (existing == null) { + existing = new BaseBlock[height]; + this.G_SCH.put(pair, existing); + } existing[y] = id; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/logger/ILogger.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/logger/ILogger.java index 29a45ac27..16fb343bf 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/logger/ILogger.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/logger/ILogger.java @@ -1,5 +1,5 @@ package com.github.intellectualsites.plotsquared.plot.logger; -@FunctionalInterface public interface ILogger { +public interface ILogger { void log(String message); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Expression.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Expression.java index da9c2c09d..bb466c082 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Expression.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Expression.java @@ -4,12 +4,10 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.commands.DebugExec; import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; -import javax.annotation.Nonnull; import javax.script.ScriptException; public abstract class Expression { - - @Nonnull public static Expression constant(final U value) { + public static Expression constant(final U value) { return new Expression() { @Override public U evaluate(U arg) { return value; 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 c31404cd5..85349cd55 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 @@ -20,7 +20,6 @@ import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableSet; import com.sk89q.jnbt.CompoundTag; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.geom.Area; import java.awt.geom.PathIterator; @@ -33,10 +32,12 @@ import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; /** - * The plot class
[IMPORTANT] - Unclaimed plots will not have persistent information. - Any - * information set/modified in an unclaimed object may not be reflected in other instances - Using - * the `new` operator will create an unclaimed plot instance - Use the methods from the - * PlotArea/PS/Location etc to get existing plots + * The plot class
+ * [IMPORTANT] + * - Unclaimed plots will not have persistent information. + * - Any information set/modified in an unclaimed object may not be reflected in other instances + * - Using the `new` operator will create an unclaimed plot instance + * - Use the methods from the PlotArea/PS/Location etc to get existing plots */ public class Plot { @@ -50,8 +51,9 @@ public class Plot { */ private final PlotId id; /** - * plot owner (Merged plots can have multiple owners) Direct access is Deprecated: use - * getOwners() + * plot owner + * (Merged plots can have multiple owners) + * Direct access is Deprecated: use getOwners() */ @Deprecated public UUID owner; /** @@ -59,9 +61,9 @@ public class Plot { */ public boolean countsTowardsMax = true; /** - * Represents whatever the database manager needs it to:
- A value of -1 usually indicates - * the plot will not be stored in the DB
- A value of 0 usually indicates that the DB manager - * hasn't set a value
+ * Represents whatever the database manager needs it to:
+ * - A value of -1 usually indicates the plot will not be stored in the DB
+ * - A value of 0 usually indicates that the DB manager hasn't set a value
* * @deprecated magical */ @@ -84,14 +86,15 @@ public class Plot { */ private HashSet denied; /** - * External settings class. - Please favor the methods over direct access to this class
- The - * methods are more likely to be left unchanged from version changes
+ * External settings class. + * - Please favor the methods over direct access to this class
+ * - The methods are more likely to be left unchanged from version changes
*/ private PlotSettings settings; /** * The {@link PlotArea}. */ - @Nonnull private PlotArea area; + private PlotArea area; /** * Session only plot metadata (session is until the server stops)
*
@@ -101,42 +104,43 @@ public class Plot { */ private ConcurrentHashMap meta; /** - * The cached origin plot. - The origin plot is used for plot grouping and relational data + * The cached origin plot. + * - The origin plot is used for plot grouping and relational data */ private Plot origin; /** - * Constructor for a new plot. (Only changes after plot.create() will be properly set in the - * database) + * Constructor for a new plot. + * (Only changes after plot.create() will be properly set in the database) * * @param area the PlotArea where the plot is located * @param id the plot id * @param owner the plot owner * @see Plot#getPlot(Location) for existing plots */ - public Plot(@Nonnull PlotArea area, PlotId id, UUID owner) { + public Plot(PlotArea area, PlotId id, UUID owner) { this.area = area; this.id = id; this.owner = owner; } /** - * Constructor for an unowned plot. (Only changes after plot.create() will be properly set in the - * database) + * Constructor for an unowned plot. + * (Only changes after plot.create() will be properly set in the database) * * @param area the PlotArea where the plot is located * @param id the plot id * @see Plot#getPlot(Location) for existing plots */ - public Plot(@Nonnull PlotArea area, PlotId id) { + public Plot(PlotArea area, PlotId id) { this.area = area; this.id = id; } /** - * Constructor for a temporary plot (use -1 for temp)
The database will ignore any queries - * regarding temporary plots. Please note that some bulk plot management functions may still - * affect temporary plots (TODO: fix this) + * Constructor for a temporary plot (use -1 for temp)
+ * The database will ignore any queries regarding temporary plots. + * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this) * * @param area the PlotArea where the plot is located * @param id the plot id @@ -144,7 +148,7 @@ public class Plot { * @param temp Represents whatever the database manager needs it to * @see Plot#getPlot(Location) for existing plots */ - public Plot(@Nonnull PlotArea area, PlotId id, UUID owner, int temp) { + public Plot(PlotArea area, PlotId id, UUID owner, int temp) { this.area = area; this.id = id; this.owner = owner; @@ -163,7 +167,7 @@ public class Plot { */ public Plot(PlotId id, UUID owner, HashSet trusted, HashSet members, HashSet denied, String alias, BlockLoc position, Collection flags, - @Nonnull PlotArea area, boolean[] merged, long timestamp, int temp) { + PlotArea area, boolean[] merged, long timestamp, int temp) { this.id = id; this.area = area; this.owner = owner; @@ -264,8 +268,9 @@ public class Plot { } /** - * Delete the metadata for a key
- metadata is session only - deleting other plugin's metadata - * may cause issues + * Delete the metadata for a key
+ * - metadata is session only + * - deleting other plugin's metadata may cause issues * * @param key key to delete */ @@ -285,9 +290,9 @@ public class Plot { } /** - * Efficiently get the players currently inside this plot
- Will return an empty list if no - * players are in the plot
- Remember, you can cast a PlotPlayer to it's respective - * implementation (BukkitPlayer, SpongePlayer) to obtain the player object + * Efficiently get the players currently inside this plot
+ * - Will return an empty list if no players are in the plot
+ * - Remember, you can cast a PlotPlayer to it's respective implementation (BukkitPlayer, SpongePlayer) to obtain the player object * * @return list of PlotPlayer(s) or an empty list */ @@ -348,7 +353,7 @@ public class Plot { } if (isMerged()) { Set plots = getConnectedPlots(); - Plot[] array = plots.toArray(new Plot[0]); + Plot[] array = plots.toArray(new Plot[plots.size()]); ImmutableSet.Builder owners = ImmutableSet.builder(); UUID last = this.owner; owners.add(this.owner); @@ -403,38 +408,41 @@ public class Plot { /** * Get the {@link PlotId}. */ - @Nonnull public PlotId getId() { + public PlotId getId() { return this.id; } /** - * Get the plot world object for this plot
- The generic PlotArea object can be casted to its - * respective class for more control (e.g. HybridPlotWorld) + * Get the plot world object for this plot
+ * - The generic PlotArea object can be casted to its respective class for more control (e.g. HybridPlotWorld) * * @return PlotArea */ - @Nonnull public PlotArea getArea() { + public PlotArea getArea() { return this.area; } /** - * Assign this plot to a plot area.
(Mostly used during startup when worlds are being - * created)
Note: Using this when it doesn't make sense will result in strange behavior + * Assign this plot to a plot area.
+ * (Mostly used during startup when worlds are being created)
+ * Note: Using this when it doesn't make sense will result in strange behavior * * @param area area to assign to */ - public void setArea(@Nonnull PlotArea area) { + public void setArea(PlotArea area) { if (this.getArea() == area) { return; } - this.area.removePlot(this.id); + if (this.getArea() != null) { + this.area.removePlot(this.id); + } this.area = area; area.addPlot(this); } /** - * Get the plot manager object for this plot
- The generic PlotManager object can be casted to - * its respective class for more control (e.g. HybridPlotManager) + * Get the plot manager object for this plot
+ * - The generic PlotManager object can be casted to its respective class for more control (e.g. HybridPlotManager) * * @return PlotManager */ @@ -448,7 +456,7 @@ public class Plot { * @return PlotSettings * @deprecated use equivalent plot method; */ - @Deprecated @Nonnull public PlotSettings getSettings() { + @Deprecated public PlotSettings getSettings() { if (this.settings == null) { this.settings = new PlotSettings(); } @@ -456,7 +464,8 @@ public class Plot { } /** - * Returns true if the plot is not merged, or it is the base plot of multiple merged plots. + * Returns true if the plot is not merged, or it is the base + * plot of multiple merged plots. * * @return Boolean */ @@ -466,9 +475,10 @@ public class Plot { /** * The base plot is an arbitrary but specific connected plot. It is useful for the following:
- * - Merged plots need to be treated as a single plot for most purposes
- Some data such as - * home location needs to be associated with the group rather than each plot
- If the plot is - * not merged it will return itself.
- The result is cached locally + * - Merged plots need to be treated as a single plot for most purposes
+ * - Some data such as home location needs to be associated with the group rather than each plot
+ * - If the plot is not merged it will return itself.
+ * - The result is cached locally * * @return base Plot */ @@ -508,8 +518,9 @@ public class Plot { } /** - * Get the timestamp of when the plot was created (unreliable)
- not accurate if the plot was - * created before this was implemented
- Milliseconds since the epoch
+ * Get the timestamp of when the plot was created (unreliable)
+ * - not accurate if the plot was created before this was implemented
+ * - Milliseconds since the epoch
* * @return the creation date of the plot */ @@ -521,11 +532,19 @@ public class Plot { } /** - * Get if the plot is merged in a direction
------- Actual -------
0 = north
1 = - * east
2 = south
3 = west
----- Artificial -----
4 = north-east
5 = - * south-east
6 = south-west
7 = north-west
----------
Note: A plot that is merged - * north and east will not be merged northeast if the northeast plot is not part of the same - * group
+ * Get if the plot is merged in a direction
+ * ------- Actual -------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----- Artificial -----
+ * 4 = north-east
+ * 5 = south-east
+ * 6 = south-west
+ * 7 = north-west
+ * ----------
+ * Note: A plot that is merged north and east will not be merged northeast if the northeast plot is not part of the same group
* * @param direction direction to check for merged plot * @return true if merged in that direction @@ -737,9 +756,8 @@ public class Plot { public boolean setOwner(UUID owner, PlotPlayer initiator) { boolean result = EventUtil.manager .callOwnerChange(initiator, this, owner, hasOwner() ? this.owner : null, hasOwner()); - if (!result) { + if (!result) return false; - } if (!hasOwner()) { this.owner = owner; create(); @@ -934,9 +952,8 @@ public class Plot { * @param name name */ public void setSign(final String name) { - if (!isLoaded()) { + if (!isLoaded()) return; - } if (!PlotSquared.get().isMainThread(Thread.currentThread())) { TaskManager.runTask(() -> Plot.this.setSign(name)); return; @@ -1045,8 +1062,13 @@ public class Plot { * Count the entities in a plot * * @return array of entity counts - * @see ChunkManager#countEntities(Plot) 0 = Entity 1 = Animal 2 = Monster 3 = Mob 4 = Boat 5 = - * Misc + * @see ChunkManager#countEntities(Plot) + * 0 = Entity + * 1 = Animal + * 2 = Monster + * 3 = Mob + * 4 = Boat + * 5 = Misc */ public int[] countEntities() { int[] count = new int[6]; @@ -1076,8 +1098,8 @@ public class Plot { } /** - * Decrement the number of tracked tasks this plot is running
- Used to track/limit the number - * of things a player can do on the plot at once + * Decrement the number of tracked tasks this plot is running
+ * - Used to track/limit the number of things a player can do on the plot at once * * @return previous number of tasks (int) */ @@ -1096,8 +1118,8 @@ public class Plot { } /** - * Get the number of tracked running tasks for this plot
- Used to track/limit the number of - * things a player can do on the plot at once + * Get the number of tracked running tasks for this plot
+ * - Used to track/limit the number of things a player can do on the plot at once * * @return number of tasks (int) */ @@ -1107,8 +1129,7 @@ public class Plot { } /** - * Unclaim the plot (does not modify terrain). Changes made to this plot will not be reflected in - * unclaimed plot objects. + * Unclaim the plot (does not modify terrain). Changes made to this plot will not be reflected in unclaimed plot objects. * * @return false if the Plot has no owner, otherwise true. */ @@ -1148,9 +1169,8 @@ public class Plot { Location bot = corners[1]; Location loc = new Location(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); - if (!isLoaded()) { + if (!isLoaded()) return loc; - } int y = isLoaded() ? WorldUtil.IMP.getHighestBlock(getWorldName(), loc.getX(), loc.getZ()) : 62; if (area.ALLOW_SIGNS) { @@ -1185,9 +1205,8 @@ public class Plot { Location bot = this.getBottomAbs(); Location loc = new Location(bot.getWorld(), bot.getX() + home.x, bot.getY() + home.y, bot.getZ() + home.z, home.yaw, home.pitch); - if (!isLoaded()) { + if (!isLoaded()) return loc; - } if (!WorldUtil.IMP.getBlock(loc).isAir()) { loc.setY(Math.max( 1 + WorldUtil.IMP.getHighestBlock(this.getWorldName(), loc.getX(), loc.getZ()), @@ -1216,8 +1235,8 @@ public class Plot { } /** - * Get the default home location for a plot
- Ignores any home location set for that specific - * plot + * Get the default home location for a plot
+ * - Ignores any home location set for that specific plot * * @return Location */ @@ -1277,7 +1296,8 @@ public class Plot { } /** - * Set a rating for a user
- If the user has already rated, the following will return false + * Set a rating for a user
+ * - If the user has already rated, the following will return false * * @param uuid uuid of rater * @param rating rating @@ -1308,7 +1328,8 @@ public class Plot { } /** - * Get the ratings associated with a plot
- The rating object may contain multiple categories + * Get the ratings associated with a plot
+ * - The rating object may contain multiple categories * * @return Map of user who rated to the rating */ @@ -1330,7 +1351,8 @@ public class Plot { } /** - * Resend all chunks inside the plot to nearby players
This should not need to be called + * Resend all chunks inside the plot to nearby players
+ * This should not need to be called */ public void refreshChunks() { LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(getWorldName(), false); @@ -1372,9 +1394,10 @@ public class Plot { } /** - * Register a plot and create it in the database
- The plot will not be created if the owner - * is null
- Any setting from before plot creation will not be saved until the server is - * stopped properly. i.e. Set any values/options after plot creation. + * Register a plot and create it in the database
+ * - The plot will not be created if the owner is null
+ * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot + * creation. * * @return true if plot was created successfully */ @@ -1436,9 +1459,10 @@ public class Plot { } /** - * Register a plot and create it in the database
- The plot will not be created if the owner - * is null
- Any setting from before plot creation will not be saved until the server is - * stopped properly. i.e. Set any values/options after plot creation. + * Register a plot and create it in the database
+ * - The plot will not be created if the owner is null
+ * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot + * creation. * * @param uuid the uuid of the plot owner * @param notify notify @@ -1478,7 +1502,8 @@ public class Plot { } /** - * Set components such as border, wall, floor. (components are generator specific) + * Set components such as border, wall, floor. + * (components are generator specific) */ public boolean setComponent(String component, String blocks) { BlockBucket parsed = Configuration.BLOCK_BUCKET.parseString(blocks); @@ -1497,6 +1522,8 @@ public class Plot { /** * Return the top location for the plot. + * + * @return */ public Location getTopAbs() { Location top = this.area.getPlotManager().getPlotTopLocAbs(this.area, this.id); @@ -1506,6 +1533,8 @@ public class Plot { /** * Return the bottom location for the plot. + * + * @return */ public Location getBottomAbs() { Location loc = this.area.getPlotManager().getPlotBottomLocAbs(this.area, this.id); @@ -1518,6 +1547,7 @@ public class Plot { * * @param plot the plot to swap data with * @param whenDone the task to run at the end of this method. + * @return */ public boolean swapData(Plot plot, Runnable whenDone) { if (this.owner == null) { @@ -1552,7 +1582,9 @@ public class Plot { /** * Move the settings for a plot. * - * @param plot the plot to move + * @param plot the plot to move + * @param whenDone + * @return */ public boolean moveData(Plot plot, Runnable whenDone) { if (this.owner == null) { @@ -1576,8 +1608,8 @@ public class Plot { } /** - * Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like - * each plot treated as a small plot use getPlotTopLocAbs(...) + * Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like each plot treated as + * a small plot use getPlotTopLocAbs(...) * * @return Location top of mega plot */ @@ -1596,8 +1628,9 @@ public class Plot { } /** - * Gets the bottom location for a plot.
- Does not respect mega plots
- Merged plots, only - * the road will be considered part of the plot
+ * Gets the bottom location for a plot.
+ * - Does not respect mega plots
+ * - Merged plots, only the road will be considered part of the plot
* * @return Location bottom of mega plot */ @@ -1616,9 +1649,9 @@ public class Plot { } /** - * Returns the top and bottom location.
- If the plot is not connected, it will return its own - * corners
- the returned locations will not necessarily correspond to claimed plots if the - * connected plots do not form a rectangular shape + * Returns the top and bottom location.
+ * - If the plot is not connected, it will return its own corners
+ * - the returned locations will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape * * @return new Location[] { bottom, top } * @deprecated as merged plots no longer need to be rectangular @@ -1631,7 +1664,8 @@ public class Plot { } /** - * Remove the east road section of a plot
- Used when a plot is merged
+ * Remove the east road section of a plot
+ * - Used when a plot is merged
*/ public void removeRoadEast() { if (this.area.TYPE != 0 && this.area.TERRAIN > 1) { @@ -1650,6 +1684,7 @@ public class Plot { } /** + * @return * @deprecated in favor of getCorners()[0];
*/ // Won't remove as suggestion also points to deprecated method @@ -1667,8 +1702,8 @@ public class Plot { } /** - * Swap the plot contents and settings with another location
- The destination must correspond - * to a valid plot of equal dimensions + * Swap the plot contents and settings with another location
+ * - The destination must correspond to a valid plot of equal dimensions * * @param destination The other plot to swap with * @param whenDone A task to run when finished, or null @@ -1682,7 +1717,8 @@ public class Plot { } /** - * Move the plot to an empty location
- The location must be empty + * Move the plot to an empty location
+ * - The location must be empty * * @param destination Where to move the plot * @param whenDone A task to run when done, or null @@ -1706,7 +1742,10 @@ public class Plot { /** - * Remove a denied player (use DBFunc as well)
Using the * uuid will remove all users + * Remove a denied player (use DBFunc as well)
+ * Using the * uuid will remove all users + * + * @param uuid */ public boolean removeDenied(UUID uuid) { if (uuid == DBFunc.EVERYONE && !denied.contains(uuid)) { @@ -1731,7 +1770,10 @@ public class Plot { } /** - * Remove a helper (use DBFunc as well)
Using the * uuid will remove all users + * Remove a helper (use DBFunc as well)
+ * Using the * uuid will remove all users + * + * @param uuid */ public boolean removeTrusted(UUID uuid) { if (uuid == DBFunc.EVERYONE && !trusted.contains(uuid)) { @@ -1756,7 +1798,10 @@ public class Plot { } /** - * Remove a trusted user (use DBFunc as well)
Using the * uuid will remove all users + * Remove a trusted user (use DBFunc as well)
+ * Using the * uuid will remove all users + * + * @param uuid */ public boolean removeMember(UUID uuid) { if (this.members == null) { @@ -1785,6 +1830,8 @@ public class Plot { /** * Export the plot as a schematic to the configured output directory. + * + * @return */ public void export(final RunnableVal whenDone) { SchematicHandler.manager.getCompoundTag(this, new RunnableVal() { @@ -1824,10 +1871,11 @@ public class Plot { } /** - * Upload this plot as a world file
- The mca files are each 512x512, so depending on the plot - * size it may also download adjacent plots
- Works best when (plot width + road width) % 512 - * == 0
+ * Upload this plot as a world file
+ * - The mca files are each 512x512, so depending on the plot size it may also download adjacent plots
+ * - Works best when (plot width + road width) % 512 == 0
* + * @param whenDone * @see WorldUtil */ public void uploadWorld(RunnableVal whenDone) { @@ -1850,8 +1898,10 @@ public class Plot { } /** - * Get the plot hashcode
Note: The hashcode is unique if:
- Plots are in the same - * world
- The x,z coordinates are between Short.MIN_VALUE and Short.MAX_VALUE
+ * Get the plot hashcode
+ * Note: The hashcode is unique if:
+ * - Plots are in the same world
+ * - The x,z coordinates are between Short.MIN_VALUE and Short.MAX_VALUE
* * @return integer. */ @@ -1860,7 +1910,10 @@ public class Plot { } /** - * Get the flags specific to this plot
- Does not take default flags into account
+ * Get the flags specific to this plot
+ * - Does not take default flags into account
+ * + * @return */ public HashMap, Object> getFlags() { return this.getSettings().flags; @@ -1868,13 +1921,16 @@ public class Plot { /** * Set a flag for this plot. + * + * @param flags */ public void setFlags(HashMap, Object> flags) { FlagManager.setPlotFlags(this, flags); } /** - * Get the plot alias. - Returns an empty string if no alias is set + * Get the plot alias. + * - Returns an empty string if no alias is set * * @return The plot alias */ @@ -1905,10 +1961,20 @@ public class Plot { } /** - * Set the raw merge data
- Updates DB
- Does not modify terrain
----------
0 = - * north
1 = east
2 = south
3 = west
----------
+ * Set the raw merge data
+ * - Updates DB
+ * - Does not modify terrain
+ * ----------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----------
+ * + * @param direction + * @param value */ - private void setMerged(int direction, boolean value) { + public void setMerged(int direction, boolean value) { if (this.getSettings().setMerged(direction, value)) { if (value) { Plot other = this.getRelative(direction).getBasePlot(false); @@ -1942,9 +2008,19 @@ public class Plot { } /** - * Set the raw merge data
- Updates DB
- Does not modify terrain
Get if the plot is - * merged in a direction
----------
0 = north
1 = east
2 = south
3 = west
- * ----------
Note: Diagonal merging (4-7) must be done by merging the corresponding plots. + * Set the raw merge data
+ * - Updates DB
+ * - Does not modify terrain
+ * Get if the plot is merged in a direction
+ * ----------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----------
+ * Note: Diagonal merging (4-7) must be done by merging the corresponding plots. + * + * @param merged */ public void setMerged(boolean[] merged) { this.getSettings().setMerged(merged); @@ -1952,7 +2028,7 @@ public class Plot { clearCache(); } - private void clearCache() { + public void clearCache() { connected_cache = null; regions_cache = null; if (this.origin != null) { @@ -1962,9 +2038,10 @@ public class Plot { } /** - * Get the set home location or 0,0,0 if no location is set
- Does not take the default home - * location into account + * Get the set home location or 0,0,0 if no location is set
+ * - Does not take the default home location into account * + * @return * @see #getHome() */ public BlockLoc getPosition() { @@ -1975,6 +2052,7 @@ public class Plot { * Check if a plot can be claimed by the provided player. * * @param player the claiming player + * @return */ public boolean canClaim(@Nullable PlotPlayer player) { PlotCluster cluster = this.getCluster(); @@ -1988,8 +2066,8 @@ public class Plot { } /** - * Guess the owner of a plot either by the value in memory, or the sign data
Note: Recovering - * from sign information is useful if e.g. PlotMe conversion wasn't successful + * Guess the owner of a plot either by the value in memory, or the sign data
+ * Note: Recovering from sign information is useful if e.g. PlotMe conversion wasn't successful * * @return UUID */ @@ -2055,7 +2133,8 @@ public class Plot { } /** - * Remove the south road section of a plot
- Used when a plot is merged
+ * Remove the south road section of a plot
+ * - Used when a plot is merged
*/ public void removeRoadSouth() { if (this.area.TYPE != 0 && this.area.TERRAIN > 1) { @@ -2076,8 +2155,12 @@ public class Plot { /** * Auto merge a plot in a specific direction
* - * @param dir The direction to merge
-1 = All directions
0 = north
1 = east
2 = - * south
3 = west
+ * @param dir The direction to merge
+ * -1 = All directions
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
* @param max The max number of merges to do * @param uuid The UUID it is allowed to merge with * @param removeRoads Whether to remove roads @@ -2162,7 +2245,10 @@ public class Plot { } /** - * Merge the plot settings
- Used when a plot is merged
+ * Merge the plot settings
+ * - Used when a plot is merged
+ * + * @param b */ public void mergeData(Plot b) { HashMap, Object> flags1 = this.getFlags(); @@ -2224,9 +2310,11 @@ public class Plot { } /** - * Get the plot in a relative location
Note: May be null if the partial plot area does not - * include the relative location + * Get the plot in a relative location
+ * Note: May be null if the partial plot area does not include the relative location * + * @param x + * @param y * @return Plot */ public Plot getRelative(int x, int y) { @@ -2238,18 +2326,28 @@ public class Plot { } /** - * Get the plot in a relative direction
0 = north
1 = east
2 = south
3 = west
+ * Get the plot in a relative direction
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
* Note: May be null if the partial plot area does not include the relative location + * + * @param direction + * @return */ public Plot getRelative(int direction) { return this.area.getPlotAbs(this.id.getRelative(direction)); } /** - * Get a set of plots connected (and including) this plot
- This result is cached globally + * Get a set of plots connected (and including) this plot
+ * - This result is cached globally + * + * @return */ public Set getConnectedPlots() { - if (this.settings == null || !this.isMerged()) { + if (this.settings == null) { return Collections.singleton(this); } boolean[] merged = this.getMerged(); @@ -2377,8 +2475,11 @@ public class Plot { } /** - * This will combine each plot into effective rectangular regions
- This result is cached - * globally
- Useful for handling non rectangular shapes + * This will combine each plot into effective rectangular regions
+ * - This result is cached globally
+ * - Useful for handling non rectangular shapes + * + * @return */ public HashSet getRegions() { if (regions_cache != null && connected_cache != null && connected_cache.contains(this)) { @@ -2461,7 +2562,9 @@ public class Plot { } Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); - visited.addAll(MainUtil.getPlotSelectionIds(bot, top)); + for (PlotId id : MainUtil.getPlotSelectionIds(bot, top)) { + visited.add(id); + } for (int x = bot.x; x <= top.x; x++) { Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); if (plot.getMerged(2)) { @@ -2504,8 +2607,9 @@ public class Plot { } /** - * Attempt to find the largest rectangular region in a plot (as plots can form non rectangular - * shapes) + * Attempt to find the largest rectangular region in a plot (as plots can form non rectangular shapes) + * + * @return */ public RegionWrapper getLargestRegion() { HashSet regions = this.getRegions(); @@ -2523,8 +2627,8 @@ public class Plot { } /** - * Do the plot entry tasks for each player in the plot
- Usually called when the plot state - * changes (unclaimed/claimed/flag change etc) + * Do the plot entry tasks for each player in the plot
+ * - Usually called when the plot state changes (unclaimed/claimed/flag change etc) */ public void reEnter() { TaskManager.runTaskLater(() -> { @@ -2618,8 +2722,13 @@ public class Plot { } /** - * Set a component for a plot to the provided blocks
- E.g. floor, wall, border etc.
- The - * available components depend on the generator being used
+ * Set a component for a plot to the provided blocks
+ * - E.g. floor, wall, border etc.
+ * - The available components depend on the generator being used
+ * + * @param component + * @param blocks + * @return */ public boolean setComponent(String component, BlockBucket blocks) { if (StringMan @@ -2654,8 +2763,10 @@ public class Plot { } /** - * Merges 2 plots Removes the road in-between
- Assumes plots are directly next to each other - *
- saves to DB + * Merges 2 plots Removes the road in-between
- Assumes plots are directly next to each other
- saves to DB + * + * @param lesserPlot + * @param removeRoads */ public void mergePlot(Plot lesserPlot, boolean removeRoads) { Plot greaterPlot = this; @@ -2805,6 +2916,10 @@ public class Plot { /** * Copy a plot to a location, both physically and the settings + * + * @param destination + * @param whenDone + * @return */ public boolean copy(final Plot destination, final Runnable whenDone) { PlotId offset = new PlotId(destination.getId().x - this.getId().x, 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 00a30e22d..48ebb759a 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 @@ -721,9 +721,6 @@ public abstract class PlotArea { } else { start = start.getNextId(1); } - if (start == null) { - PlotSquared.debug("NPE possible in getNextFreePlot"); - } currentId = new PlotId(center.x + start.x, center.y + start.y); Plot plot = getPlotAbs(currentId); if (plot != null && plot.canClaim(player)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java index ed9ca5fd8..a1134cbce 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java @@ -2,24 +2,22 @@ package com.github.intellectualsites.plotsquared.plot.object; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -import lombok.Getter; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.UUID; public class PlotCluster { public PlotArea area; - @Nonnull @Getter public PlotSettings settings; + public PlotSettings settings; public UUID owner; public HashSet helpers = new HashSet<>(); public HashSet invited = new HashSet<>(); public int temp; - @Nonnull private PlotId pos1; - @Nonnull private PlotId pos2; + private PlotId pos1; + private PlotId pos2; private RegionWrapper region; - public PlotCluster(PlotArea area, @Nonnull PlotId pos1, @Nonnull PlotId pos2, UUID owner) { + public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner) { this.area = area; this.pos1 = pos1; this.pos2 = pos2; @@ -29,7 +27,7 @@ public class PlotCluster { setRegion(); } - public PlotCluster(PlotArea area, @Nonnull PlotId pos1, PlotId pos2, UUID owner, int temp) { + public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner, int temp) { this.area = area; this.pos1 = pos1; this.pos2 = pos2; @@ -84,14 +82,6 @@ public class PlotCluster { return this.settings.getAlias(); } - public void setName(String name) { - this.settings.setAlias(name); - } - - public String getAlias() { - return this.settings.getAlias(); - } - /** * Get the area (in plots). * 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 6db234de3..47069a38e 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 @@ -13,7 +13,6 @@ public class PlotMessage { try { reset(ChatManager.manager); } catch (Throwable e) { - assert PlotSquared.imp() != null; PlotSquared.debug( PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + PlotSquared .get().IMP.getServerVersion()); 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 2fc42059f..d535c625e 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 @@ -48,17 +48,25 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } /** - * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's - * already cached)
- Accepts sponge/bukkit Player (online) - Accepts player name (online) - - * Accepts UUID - Accepts bukkit OfflinePlayer (offline) + * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)
+ * - Accepts sponge/bukkit Player (online) + * - Accepts player name (online) + * - Accepts UUID + * - Accepts bukkit OfflinePlayer (offline) + * + * @param player + * @return */ public static PlotPlayer wrap(Object player) { return PlotSquared.get().IMP.wrapPlayer(player); } /** - * Get the cached PlotPlayer from a username
- This will return null if the player has not - * finished logging in or is not online + * Get the cached PlotPlayer from a username
+ * - This will return null if the player has not finished logging in or is not online + * + * @param name + * @return */ public static PlotPlayer get(String name) { return UUIDHandler.getPlayer(name); @@ -66,6 +74,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Set some session only metadata for this player. + * + * @param key + * @param value */ public void setMeta(String key, Object value) { if (value == null) { @@ -101,8 +112,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } /** - * Delete the metadata for a key. - metadata is session only - deleting other plugin's metadata - * may cause issues + * Delete the metadata for a key. + * - metadata is session only + * - deleting other plugin's metadata may cause issues + * + * @param key */ public Object deleteMeta(String key) { return this.meta == null ? null : this.meta.remove(key); @@ -120,8 +134,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Get this player's current plot. * - * @return the plot the player is standing on or null if standing on a road or not in a {@link - * PlotArea} + * @return the plot the player is standing on or null if standing on a road or not in a {@link PlotArea} */ public Plot getCurrentPlot() { Plot value = getMeta(PlotPlayer.META_LAST_PLOT); @@ -132,11 +145,10 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } /** - * Get the total number of allowed plots Possibly relevant: (To increment the player's allowed - * plots, see the example script on the wiki) + * Get the total number of allowed plots + * Possibly relevant: (To increment the player's allowed plots, see the example script on the wiki) * - * @return number of allowed plots within the scope (globally, or in the player's current world as - * defined in the settings.yml) + * @return number of allowed plots within the scope (globally, or in the player's current world as defined in the settings.yml) */ public int getAllowedPlots() { return Permissions.hasPermissionRange(this, "plots.plot", Settings.Limit.MAX_PLOTS); @@ -145,8 +157,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Get the total number of allowed clusters * - * @return number of allowed clusters within the scope (globally, or in the player's current world - * as defined in the settings.yml) + * @return number of allowed clusters within the scope (globally, or in the player's current world as defined in the settings.yml) */ public int getAllowedClusters() { return Permissions.hasPermissionRange(this, "plots.cluster", Settings.Limit.MAX_PLOTS); @@ -180,8 +191,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Get the number of plots this player owns. * - * @return number of plots within the scope (globally, or in the player's current world as defined - * in the settings.yml) + * @return number of plots within the scope (globally, or in the player's current world as defined in the settings.yml) * @see #getPlotCount(String); * @see #getPlots() */ @@ -229,6 +239,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { * Get the number of plots this player owns in the world. * * @param world the name of the plotworld to check. + * @return */ public int getPlotCount(String world) { UUID uuid = getUUID(); @@ -273,6 +284,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Return the PlotArea this player is currently in, or null. + * + * @return */ public PlotArea getPlotAreaAbs() { return PlotSquared.get().getPlotAreaAbs(getLocation()); @@ -305,15 +318,18 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Get this player's full location (including yaw/pitch) + * + * @return */ public abstract Location getLocationFull(); //////////////////////////////////////////////// /** - * Get this player's UUID. === !IMPORTANT ===
The UUID is dependent on the mode chosen in the - * settings.yml and may not be the same as Bukkit has (especially if using an old version of - * Bukkit that does not support UUIDs) + * Get this player's UUID. + * === !IMPORTANT ===
+ * The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has + * (especially if using an old version of Bukkit that does not support UUIDs) * * @return UUID */ @@ -356,8 +372,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { public abstract void setCompassTarget(Location location); /** - * Set player data that will persist restarts. - Please note that this is not intended to store - * large values - For session only data use meta + * Set player data that will persist restarts. + * - Please note that this is not intended to store large values + * - For session only data use meta + * + * @param key */ public void setAttribute(String key) { setPersistentMeta("attrib_" + key, new byte[] {(byte) 1}); @@ -366,6 +385,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Retrieves the attribute of this player. * + * @param key * @return the attribute will be either true or false */ public boolean getAttribute(String key) { @@ -377,6 +397,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Remove an attribute from a player. + * + * @param key */ public void removeAttribute(String key) { removePersistentMeta("attrib_" + key); @@ -470,7 +492,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { owned.deletePlot(null); PlotSquared.debug(String .format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned", - owned.getId(), getName())); + plot.getId(), getName())); } } String name = getName(); @@ -483,6 +505,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * Get the amount of clusters this player owns in the specific world. + * + * @param world + * @return */ public int getPlayerClusterCount(String world) { UUID uuid = getUUID(); @@ -555,27 +580,31 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { final Location loc = new Location(plot.getWorldName(), x, y, z); if (plot.isLoaded()) { - TaskManager.runTask(() -> { - if (getMeta("teleportOnLogin", true)) { - teleport(loc); - sendMessage(C.TELEPORTED_TO_PLOT.f() - + " (quitLoc) (" + plotX + "," - + plotZ + ")"); + TaskManager.runTask(new Runnable() { + @Override public void run() { + 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(() -> { - if (getMeta("teleportOnLogin", - true)) { - teleport(loc); - sendMessage( - C.TELEPORTED_TO_PLOT.f() - + " (quitLoc-unloaded) (" - + plotX + "," + plotZ - + ")"); + TaskManager.runTask(new Runnable() { + @Override public void run() { + if (getMeta("teleportOnLogin", + true)) { + teleport(loc); + sendMessage( + C.TELEPORTED_TO_PLOT.f() + + " (quitLoc-unloaded) (" + + plotX + "," + + plotZ + ")"); + } } }); } @@ -624,6 +653,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { /** * The amount of money this Player has. + * + * @return */ public double getMoney() { return EconHandler.manager == null ? 0 : EconHandler.manager.getMoney(this); @@ -642,7 +673,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } public interface PlotPlayerConverter { - PlotPlayer convert(BaseObject object); } } 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 2ccaa47a8..4f3701f56 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 @@ -42,7 +42,7 @@ public class PlotSettings { /** * Flags. * - * @deprecated Raw access. Not compatible with PlotClusters. + * @deprecated Raw access */ @Deprecated public HashMap, Object> flags = new HashMap<>(); /** @@ -85,7 +85,7 @@ public class PlotSettings { return this.ratings; } - boolean setMerged(int direction, boolean merged) { + public boolean setMerged(int direction, boolean merged) { if (this.merged[direction] != merged) { this.merged[direction] = merged; return true; @@ -142,7 +142,6 @@ public class PlotSettings { } } - //todo need a plot method public Optional> getComments(String inbox) { ArrayList c = new ArrayList<>(); if (this.comments == null) { @@ -156,26 +155,22 @@ public class PlotSettings { return Optional.of(c); } - //todo need a plot method public void setComments(List comments) { this.comments = comments; } - //todo need a plot method public void removeComment(PlotComment comment) { if (this.comments.contains(comment)) { this.comments.remove(comment); } } - //todo need a plot method public void removeComments(List comments) { for (PlotComment comment : comments) { removeComment(comment); } } - //todo need a plot method public void addComment(PlotComment comment) { if (this.comments == null) { this.comments = new ArrayList<>(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/stream/AbstractDelegateOutputStream.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/stream/AbstractDelegateOutputStream.java index 900471193..994f6a465 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/stream/AbstractDelegateOutputStream.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/stream/AbstractDelegateOutputStream.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.io.OutputStream; public class AbstractDelegateOutputStream extends OutputStream { - private final OutputStream parent; public AbstractDelegateOutputStream(OutputStream os) { @@ -19,6 +18,10 @@ public class AbstractDelegateOutputStream extends OutputStream { parent.write(b); } + @Override public void write(byte[] b, int off, int len) throws IOException { + parent.write(b, off, len); + } + @Override public void flush() throws IOException { parent.flush(); } 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 f53465b2a..989948f0c 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 @@ -88,8 +88,9 @@ public class DefaultPlotAreaManager implements PlotAreaManager { HashSet globalAreas = new HashSet<>(Arrays.asList(plotAreas)); localAreas.add(plotArea); globalAreas.add(plotArea); - this.plotAreas = globalAreas.toArray(new PlotArea[0]); - this.plotAreaMap.put(plotArea.worldname, localAreas.toArray(new PlotArea[0])); + this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); + this.plotAreaMap + .put(plotArea.worldname, localAreas.toArray(new PlotArea[localAreas.size()])); QuadMap map = this.plotAreaGrid.get(plotArea.worldname); if (map == null) { map = new QuadMap(Integer.MAX_VALUE, 0, 0) { @@ -103,14 +104,15 @@ 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[0]); + this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); if (globalAreas.isEmpty()) { this.plotAreaMap.remove(area.worldname); this.plotAreaGrid.remove(area.worldname); } else { - this.plotAreaMap.put(area.worldname, globalAreas.toArray(new PlotArea[0])); + this.plotAreaMap + .put(area.worldname, globalAreas.toArray(new PlotArea[globalAreas.size()])); this.plotAreaGrid.get(area.worldname).remove(area); } } @@ -204,7 +206,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager { return noPlotAreas; } else { Set found = areas.get(region); - return found.toArray(new PlotArea[0]); + return found.toArray(new PlotArea[found.size()]); } } @@ -215,14 +217,14 @@ public class DefaultPlotAreaManager implements PlotAreaManager { Set tmp = new LinkedHashSet<>(); Collections.addAll(tmp, worlds); tmp.add(worldName); - worlds = tmp.toArray(new String[0]); + worlds = tmp.toArray(new String[tmp.size()]); } @Override public void removeWorld(String worldName) { Set tmp = new LinkedHashSet<>(); Collections.addAll(tmp, worlds); tmp.remove(worldName); - worlds = tmp.toArray(new String[0]); + worlds = tmp.toArray(new String[tmp.size()]); } @Override public String[] getAllWorlds() { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java index 7a59dab9d..aef7f53a8 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java @@ -5,24 +5,24 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; public interface PlotAreaManager { - PlotArea getApplicablePlotArea(Location location); + public PlotArea getApplicablePlotArea(Location location); - PlotArea getPlotArea(Location location); + public PlotArea getPlotArea(Location location); - PlotArea getPlotArea(String world, String id); + public PlotArea getPlotArea(String world, String id); - PlotArea[] getPlotAreas(String world, RegionWrapper region); + public PlotArea[] getPlotAreas(String world, RegionWrapper region); - PlotArea[] getAllPlotAreas(); + public PlotArea[] getAllPlotAreas(); - String[] getAllWorlds(); + public String[] getAllWorlds(); - void addPlotArea(PlotArea area); + public void addPlotArea(PlotArea area); - void removePlotArea(PlotArea area); + public void removePlotArea(PlotArea area); - void addWorld(String worldName); + public void addWorld(String worldName); - void removeWorld(String worldName); + public void removeWorld(String worldName); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java index 5cf07cc14..5e153c02e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java @@ -4,7 +4,6 @@ import com.github.intellectualsites.plotsquared.plot.config.C; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.object.*; -import javax.annotation.Nonnull; import java.util.Collection; import java.util.HashSet; import java.util.UUID; @@ -41,7 +40,7 @@ public class SinglePlot extends Plot { return getId().toCommaSeparatedString(); } - @Nonnull @Override public SinglePlotArea getArea() { + @Override public SinglePlotArea getArea() { return (SinglePlotArea) super.getArea(); } 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 a3b398136..adc462f4e 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,7 +35,8 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager { if (chars.length == 1 && chars[0] == '*') { return true; } - for (char c : chars) { + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; switch (mode) { case 0: mode = 1; 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 f8e4ab000..8e5a6da12 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,10 +30,12 @@ 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(() -> { - MainUtil.deleteDirectory(worldFolder); - if (whenDone != null) - whenDone.run(); + TaskManager.IMP.taskAsync(new Runnable() { + @Override public void run() { + MainUtil.deleteDirectory(worldFolder); + if (whenDone != null) + whenDone.run(); + } }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java index 329230eaf..a5f75c96a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java @@ -15,6 +15,6 @@ public abstract class AbstractTitle { } } - protected abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, + public abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out); } 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 cf2ca96ed..e863e1302 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,39 +71,41 @@ public abstract class ChunkManager { public static void largeRegionTask(final String world, final RegionWrapper region, final RunnableVal task, final Runnable whenDone) { - 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.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.objectTask(chunks, new RunnableVal() { + TaskManager.objectTask(chunks, new RunnableVal() { - @Override public void run(ChunkLoc value) { - if (manager.loadChunk(world, value, false)) { - task.run(value); + @Override public void run(ChunkLoc value) { + if (manager.loadChunk(world, value, false)) { + task.run(value); + } } - } - }, whenDone); + }, whenDone); + } }); } @@ -237,18 +239,20 @@ public abstract class ChunkManager { public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { - 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.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.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 d0b4012a6..11c157320 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,9 +19,11 @@ public class CmdConfirm { removePending(player); if (commandStr != null) MainUtil.sendMessage(player, C.REQUIRES_CONFIRM, commandStr); - TaskManager.runTaskLater(() -> { - CmdInstance cmd = new CmdInstance(runnable); - player.setMeta("cmdConfirm", cmd); + TaskManager.runTaskLater(new Runnable() { + @Override public void run() { + 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 524ea7f67..3dc43fe06 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,31 +20,34 @@ public class CommentManager { if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) { return; } - 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++; + 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++; + } } + 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 7d82e5236..b8037944e 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 @@ -43,6 +43,8 @@ public abstract class EventUtil { public abstract boolean callFlagRemove(Flag flag, Plot plot, Object value); + public abstract boolean callFlagRemove(Flag flag, Object value, PlotCluster cluster); + public abstract boolean callMerge(Plot plot, int dir, int max); public abstract boolean callAutoMerge(Plot plot, List plots); @@ -76,7 +78,11 @@ public abstract class EventUtil { } final Plot plot = player.getCurrentPlot(); if (Settings.Teleport.ON_LOGIN && plot != null) { - TaskManager.runTask(() -> plot.teleportPlayer(player)); + TaskManager.runTask(new Runnable() { + @Override public void run() { + plot.teleportPlayer(player); + } + }); MainUtil.sendMessage(player, C.TELEPORTED_TO_ROAD.f() + " (on-login) " + "(" + plot.getId().x + ";" + plot .getId().y + ")"); 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 5dcc954a8..906c70595 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 @@ -411,7 +411,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()) { @@ -430,7 +430,7 @@ public class MainUtil { count++; } } - if (plot.getArea().equals(area)) { + if (area != null && plot.getArea().equals(area)) { count++; } if (alias != null && alias.equals(plot.getAlias())) { @@ -622,12 +622,14 @@ public class MainUtil { if (caption.s().isEmpty()) { return true; } - TaskManager.runTaskAsync(() -> { - String m = C.format(caption, args); - if (player == null) { - PlotSquared.log(m); - } else { - player.sendMessage(m); + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + String m = C.format(caption, args); + if (player == null) { + PlotSquared.log(m); + } else { + player.sendMessage(m); + } } }); return true; @@ -778,28 +780,31 @@ public class MainUtil { info = info.replace("%desc%", "No description set."); if (info.contains("%rating%")) { final String newInfo = 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); - 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 = ","; + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + int max = 10; + if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES + .isEmpty()) { + max = 8; } - info1 = newInfo.replaceAll("%rating%", rating); - } else { - info1 = newInfo.replaceAll("%rating%", - String.format("%.1f", plot.getAverageRating()) + '/' + max); + 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); } - whenDone.run(info1); }); return; } @@ -810,9 +815,10 @@ public class MainUtil { if (directory.exists()) { File[] files = directory.listFiles(); if (null != files) { - for (File file : files) { + for (int i = 0; i < files.length; i++) { + File file = files[i]; if (file.isDirectory()) { - deleteDirectory(file); + deleteDirectory(files[i]); } else { PlotSquared.debug("Deleting file: " + file + " | " + file.delete()); } 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 05eeee166..f1ca31b4d 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); + TaskManager.runTask(() -> THIS.run()); }); } } 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 84d5f7ef4..3991cd78d 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 @@ -21,8 +21,7 @@ public class GlobalBlockQueue { private final AtomicBoolean running; private QueueProvider provider; /** - * Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the - * server + * Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the server */ private long last; private long secondLast; @@ -82,50 +81,52 @@ public class GlobalBlockQueue { return false; } running.set(true); - 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(); + 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(); + } } } + } 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; @@ -167,7 +168,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; @@ -196,7 +197,7 @@ public class GlobalBlockQueue { if (PARALLEL_THREADS <= 1) { SET_TASK.run(); } else { - ArrayList threads = new ArrayList<>(); + ArrayList threads = new ArrayList(); for (int i = 0; i < PARALLEL_THREADS; i++) { threads.add(new Thread(SET_TASK)); } @@ -298,6 +299,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/expiry/ExpireManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java index 0362e0831..84f86daa2 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 @@ -65,6 +65,7 @@ public class ExpireManager { /** * Gets the account last joined - first joined (or Long.MAX_VALUE) * + * @param uuid * @return result */ public long getAccountAge(UUID uuid) { @@ -96,26 +97,28 @@ public class ExpireManager { Iterator iter = plotsToDelete.iterator(); final Plot current = iter.next(); if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) { - 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); + 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); + } }); return; } else { @@ -216,7 +219,12 @@ public class ExpireManager { public ArrayDeque getTasks(PlotArea area) { ArrayDeque queue = new ArrayDeque<>(tasks); - queue.removeIf(expiryTask -> !expiryTask.applies(area)); + Iterator iter = queue.iterator(); + while (iter.hasNext()) { + if (!iter.next().applies(area)) { + iter.remove(); + } + } return queue; } @@ -246,7 +254,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; @@ -270,8 +278,11 @@ public class ExpireManager { } for (ExpiryTask expiryTask : expired) { if (!expiryTask.needsAnalysis()) { - expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1), - expiryTask.requiresConfirmation()); + expiredTask.run(newPlot, new Runnable() { + @Override public void run() { + TaskManager.IMP.taskLaterAsync(task, 1); + } + }, expiryTask.requiresConfirmation()); return; } } @@ -280,19 +291,26 @@ public class ExpireManager { @Override public void run(final PlotAnalysis changed) { passesComplexity(changed, expired, new RunnableVal() { @Override public void run(Boolean confirmation) { - expiredTask.run(newPlot, - () -> TaskManager.IMP.taskLaterAsync(task, 1), - 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); } - }, () -> { - FlagManager - .addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList()); - TaskManager.runTaskLaterAsync(task, 20); }); } }; - final Runnable doAnalysis = - () -> HybridUtils.manager.analyzePlot(newPlot, handleAnalysis); + final Runnable doAnalysis = new Runnable() { + @Override public void run() { + HybridUtils.manager.analyzePlot(newPlot, handleAnalysis); + } + }; PlotAnalysis analysis = newPlot.getComplexity(null); if (analysis != null) { @@ -300,7 +318,11 @@ public class ExpireManager { @Override public void run(Boolean value) { doAnalysis.run(); } - }, () -> TaskManager.IMP.taskLaterAsync(task, 1)); + }, new Runnable() { + @Override public void run() { + TaskManager.IMP.taskLaterAsync(task, 1); + } + }); } else { doAnalysis.run(); } @@ -308,10 +330,12 @@ public class ExpireManager { } if (plots.isEmpty()) { ExpireManager.this.running = 3; - TaskManager.runTaskLater(() -> { - if (ExpireManager.this.running == 3) { - ExpireManager.this.running = 2; - runTask(expiredTask); + TaskManager.runTaskLater(new Runnable() { + @Override public void run() { + if (ExpireManager.this.running == 3) { + ExpireManager.this.running = 2; + runTask(expiredTask); + } } }, 86400000); } else { @@ -328,9 +352,8 @@ public class ExpireManager { long diff = time - existing; if (diff > 0) { Long account_age = this.account_age_cache.get(uuid); - if (account_age != null) { + if (account_age != null) this.account_age_cache.put(uuid, account_age + diff); - } } } } @@ -340,7 +363,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) { 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 2e7854828..b17f3ce47 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 @@ -118,14 +118,16 @@ public class PlotAnalysis { final AtomicInteger mi = new AtomicInteger(0); - Thread ratingAnalysis = new Thread(() -> { - for (; mi.intValue() < plots.size(); mi.incrementAndGet()) { - int i = mi.intValue(); - Plot plot = plots.get(i); - ratings[i] = (int) ( - (plot.getAverageRating() + plot.getSettings().getRatings().size()) - * 100); - PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]); + Thread ratingAnalysis = new Thread(new Runnable() { + @Override public void run() { + for (; mi.intValue() < plots.size(); mi.incrementAndGet()) { + int i = mi.intValue(); + Plot plot = plots.get(i); + ratings[i] = (int) ( + (plot.getAverageRating() + plot.getSettings().getRatings().size()) + * 100); + PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]); + } } }); ratingAnalysis.start(); @@ -422,6 +424,9 @@ public class PlotAnalysis { /** * A simple array squaring algorithm. * - Used for calculating the variance + * + * @param array + * @return */ public static int[] square(int[] array) { array = array.clone(); @@ -433,6 +438,9 @@ public class PlotAnalysis { /** * An optimized lossy standard deviation algorithm. + * + * @param ranks + * @return */ public static int[] getSD(int[]... ranks) { if (ranks.length == 0) { @@ -459,13 +467,20 @@ public class PlotAnalysis { * An optimized algorithm for ranking a very specific set of inputs
* - Input is an array of int with a max size of 102400
* - A reduced sample space allows for sorting (and ranking in this case) in linear time + * + * @param input + * @param input + * @return */ public static int[] rank(int[] input) { return rank(input, 102400); } /** - * An optimized algorithm for ranking a very specific set of inputs. + * An optimized algorithm for ranking a very specific set of inputs + * + * @param input + * @return */ public static int[] rank(int[] input, int size) { int[] cache = new int[size]; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java index 55f3697f7..235b51a34 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java @@ -5,17 +5,17 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import java.util.UUID; -public interface UUIDWrapper { +public abstract class UUIDWrapper { - UUID getUUID(PlotPlayer player); + public abstract UUID getUUID(PlotPlayer player); - UUID getUUID(OfflinePlotPlayer player); + public abstract UUID getUUID(OfflinePlotPlayer player); - UUID getUUID(String name); + public abstract UUID getUUID(String name); - OfflinePlotPlayer getOfflinePlayer(UUID uuid); + public abstract OfflinePlotPlayer getOfflinePlayer(UUID uuid); - OfflinePlotPlayer getOfflinePlayer(String name); + public abstract OfflinePlotPlayer getOfflinePlayer(String name); - OfflinePlotPlayer[] getOfflinePlayers(); + public abstract OfflinePlotPlayer[] getOfflinePlayers(); } diff --git a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java index 1ef04abba..7b29cdf97 100644 --- a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java +++ b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java @@ -84,6 +84,9 @@ public class AbstractDBTest implements AbstractDB { @Override public void setFlags(Plot plot, HashMap, Object> flags) { } + @Override public void setFlags(PlotCluster cluster, HashMap, Object> flags) { + } + @Override public void setClusterName(PlotCluster cluster, String name) { } diff --git a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java index 6ae75a86d..e9d1f29ec 100644 --- a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java +++ b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java @@ -40,6 +40,10 @@ public class EventUtilTest extends EventUtil { return true; } + @Override public boolean callFlagRemove(Flag flag, Object value, PlotCluster cluster) { + return true; + } + @Override public boolean callMerge(Plot plot, int dir, int max) { return false; }