Major cleanup.

Added todo comments to many 1.13 issues still lingering. Changed access to some methods to be weaker. Removed cluster flags (most of it). Java 8 stuff added. Hid more PlotSetting methods. etc.

Signed-off-by: matt <4009945+MattBDev@users.noreply.github.com>
This commit is contained in:
matt 2019-01-31 14:20:48 -05:00
parent cd8a1a0816
commit 8ac9b862f8
78 changed files with 14311 additions and 14509 deletions

View File

@ -134,7 +134,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
private final BlockRegistry<Material> blockRegistry = private final BlockRegistry<Material> blockRegistry =
new BukkitBlockRegistry(Material.values()); new BukkitBlockRegistry(Material.values());
private int[] version; private int[] version;
@Getter private String pluginName; private String pluginName;
@Getter private SingleWorldListener singleWorldListener; @Getter private SingleWorldListener singleWorldListener;
private Method methodUnloadChunk0; private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false; private boolean methodUnloadSetup = false;
@ -165,9 +165,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return Bukkit.getVersion(); return Bukkit.getVersion();
} }
@Override public void onEnable() { @Override public void onEnable() {
this.pluginName = getDescription().getName(); this.pluginName = getDescription().getName();
getServer().getName();
PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer); PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer);
@ -319,6 +319,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return getDescription().getVersion(); return getDescription().getVersion();
} }
@Override
public String getPluginName() {
return pluginName;
}
@Override public void registerCommands() { @Override public void registerCommands() {
final BukkitCommand bukkitCommand = new BukkitCommand(); final BukkitCommand bukkitCommand = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots"); final PluginCommand plotCommand = getCommand("plots");
@ -586,6 +591,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override @Nullable @Override @Nullable
public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
PlotSquared.log("DEFAULT WORLD GENERATOR RUN");
final IndependentPlotGenerator result; final IndependentPlotGenerator result;
if (id != null && id.equalsIgnoreCase("single")) { if (id != null && id.equalsIgnoreCase("single")) {
result = new SingleWorldGenerator(); result = new SingleWorldGenerator();
@ -802,7 +808,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
} }
ChunkGenerator gen = world.getGenerator(); ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) { if (gen instanceof BukkitPlotGenerator) {
PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); PlotSquared.get().loadWorld(worldName, (GeneratorWrapper<?>) gen);
} else if (gen != null) { } else if (gen != null) {
PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen)); PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen));
} else if (PlotSquared.get().worlds.contains("worlds." + worldName)) { } else if (PlotSquared.get().worlds.contains("worlds." + worldName)) {

View File

@ -320,34 +320,6 @@ public class FancyMessage
return this; return this;
} }
/**
* Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
* <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
*
* @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. * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text.
* <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p> * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>

View File

@ -1,63 +0,0 @@
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;
}
}

View File

@ -1,5 +1,7 @@
package com.github.intellectualsites.plotsquared.bukkit.listeners; package com.github.intellectualsites.plotsquared.bukkit.listeners;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C; import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.config.Settings;
@ -9,6 +11,8 @@ import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefCla
import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefField; import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefField;
import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod; import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import java.lang.reflect.Method;
import java.util.HashSet;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Material; import org.bukkit.Material;
@ -27,11 +31,6 @@ import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.ChunkUnloadEvent;
import java.lang.reflect.Method;
import java.util.HashSet;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class ChunkListener implements Listener { public class ChunkListener implements Listener {
@ -60,8 +59,7 @@ public class ChunkListener implements Listener {
for (World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false); world.setAutoSave(false);
} }
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(() -> {
@Override public void run() {
try { try {
HashSet<Chunk> toUnload = new HashSet<>(); HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
@ -102,7 +100,6 @@ public class ChunkListener implements Listener {
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}, 1); }, 1);
} }
@ -112,7 +109,7 @@ public class ChunkListener implements Listener {
} }
Object c = this.methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c); RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get() == true) { if ((Boolean) field.get()) {
field.set(false); field.set(false);
if (chunk.isLoaded()) { if (chunk.isLoaded()) {
ignoreUnload = true; ignoreUnload = true;
@ -226,8 +223,7 @@ public class ChunkListener implements Listener {
private void cleanChunk(final Chunk chunk) { private void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet(); TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get(); final Integer currentIndex = TaskManager.index.get();
Integer task = TaskManager.runTaskRepeat(new Runnable() { Integer task = TaskManager.runTaskRepeat(() -> {
@Override public void run() {
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex); TaskManager.tasks.remove(currentIndex);
@ -259,7 +255,6 @@ public class ChunkListener implements Listener {
tiles[i].getBlock().setType(Material.AIR, false); tiles[i].getBlock().setType(Material.AIR, false);
i++; i++;
} }
}
}, 5); }, 5);
TaskManager.tasks.put(currentIndex, task); TaskManager.tasks.put(currentIndex, task);
} }

View File

@ -16,7 +16,8 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@SuppressWarnings("unused") public class ForceFieldListener { @SuppressWarnings("unused")
public class ForceFieldListener {
private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) { private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer> players = new HashSet<>(); Set<PlotPlayer> players = new HashSet<>();

View File

@ -42,6 +42,7 @@ import org.bukkit.help.HelpTopic;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.Directional;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue; import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
@ -57,7 +58,8 @@ import java.util.regex.Pattern;
/** /**
* Player Events involving plots. * Player Events involving plots.
*/ */
@SuppressWarnings("unused") public class PlayerEvents extends PlotListener implements Listener { @SuppressWarnings("unused")
public class PlayerEvents extends PlotListener implements Listener {
private boolean pistonBlocks = true; private boolean pistonBlocks = true;
private float lastRadius; private float lastRadius;
@ -235,7 +237,8 @@ import java.util.regex.Pattern;
} }
} }
@EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { @EventHandler
public void onRedstoneEvent(BlockRedstoneEvent event) {
Block block = event.getBlock(); Block block = event.getBlock();
/* switch (block.getType()) { /* switch (block.getType()) {
case OBSERVER: case OBSERVER:
@ -416,7 +419,8 @@ import java.util.regex.Pattern;
} }
} }
@EventHandler public void onProjectileLaunch(ProjectileLaunchEvent event) { @EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent event) {
Projectile entity = event.getEntity(); Projectile entity = event.getEntity();
if (!(entity instanceof ThrownPotion)) { if (!(entity instanceof ThrownPotion)) {
return; return;
@ -437,7 +441,8 @@ import java.util.regex.Pattern;
} }
} }
@EventHandler public boolean onProjectileHit(ProjectileHitEvent event) { @EventHandler
public boolean onProjectileHit(ProjectileHitEvent event) {
Projectile entity = event.getEntity(); Projectile entity = event.getEntity();
Location loc = BukkitUtil.getLocation(entity); Location loc = BukkitUtil.getLocation(entity);
if (!PlotSquared.get().hasPlotArea(loc.getWorld())) { if (!PlotSquared.get().hasPlotArea(loc.getWorld())) {
@ -619,8 +624,10 @@ import java.util.regex.Pattern;
public void onTeleport(PlayerTeleportEvent event) { public void onTeleport(PlayerTeleportEvent event) {
if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld() if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld()
.equals(event.getTo().getWorld())) { .equals(event.getTo().getWorld())) {
final Object lastLoc = BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LOCATION); final Object lastLoc = BukkitUtil.getPlayer(event.getPlayer())
final Object lastPlot = BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LAST_PLOT); .deleteMeta(PlotPlayer.META_LOCATION);
final Object lastPlot = BukkitUtil.getPlayer(event.getPlayer())
.deleteMeta(PlotPlayer.META_LAST_PLOT);
org.bukkit.Location to = event.getTo(); org.bukkit.Location to = event.getTo();
if (to != null) { if (to != null) {
Player player = event.getPlayer(); Player player = event.getPlayer();
@ -669,8 +676,9 @@ import java.util.regex.Pattern;
if (passenger instanceof Player) { if (passenger instanceof Player) {
final Player player = (Player) passenger; final Player player = (Player) passenger;
// reset // reset
if (moveTmp == null) if (moveTmp == null) {
moveTmp = new PlayerMoveEvent(null, from, to); moveTmp = new PlayerMoveEvent(null, from, to);
}
moveTmp.setFrom(from); moveTmp.setFrom(from);
moveTmp.setTo(to); moveTmp.setTo(to);
moveTmp.setCancelled(false); moveTmp.setCancelled(false);
@ -698,7 +706,7 @@ import java.util.regex.Pattern;
vehicle.eject(); vehicle.eject();
vehicle.setVelocity(new Vector(0d, 0d, 0d)); vehicle.setVelocity(new Vector(0d, 0d, 0d));
vehicle.teleport(dest); vehicle.teleport(dest);
vehicle.setPassenger(player); vehicle.addPassenger(player);
} }
return; return;
} }
@ -780,7 +788,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true; this.tmpTeleport = true;
return; return;
} }
Integer border = area.getBorder(); int border = area.getBorder();
if (x2 > border && this.tmpTeleport) { if (x2 > border && this.tmpTeleport) {
to.setX(x2 - 1); to.setX(x2 - 1);
this.tmpTeleport = false; this.tmpTeleport = false;
@ -843,7 +851,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true; this.tmpTeleport = true;
return; return;
} }
Integer border = area.getBorder(); int border = area.getBorder();
if (z2 > border && this.tmpTeleport) { if (z2 > border && this.tmpTeleport) {
to.setZ(z2 - 1); to.setZ(z2 - 1);
this.tmpTeleport = false; this.tmpTeleport = false;
@ -860,9 +868,11 @@ import java.util.regex.Pattern;
} }
} }
@EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { @EventHandler(priority = EventPriority.LOW)
if (event.isCancelled()) public void onChat(AsyncPlayerChatEvent event) {
if (event.isCancelled()) {
return; return;
}
PlotPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer()); PlotPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer());
Location location = plotPlayer.getLocation(); Location location = plotPlayer.getLocation();
@ -912,7 +922,8 @@ import java.util.regex.Pattern;
PlotSquared.debug(full); PlotSquared.debug(full);
} }
@EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) { @EventHandler(priority = EventPriority.LOWEST)
public void blockDestroy(BlockBreakEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); Location location = BukkitUtil.getLocation(event.getBlock().getLocation());
PlotArea area = location.getPlotArea(); PlotArea area = location.getPlotArea();
@ -1079,8 +1090,9 @@ import java.util.regex.Pattern;
PlotArea area = location.getPlotArea(); PlotArea area = location.getPlotArea();
if (area != null) { if (area != null) {
Plot plot = area.getOwnedPlot(location); Plot plot = area.getOwnedPlot(location);
if (plot != null && Flags.MOB_BREAK.isTrue(plot)) if (plot != null && Flags.MOB_BREAK.isTrue(plot)) {
return; return;
}
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -1447,11 +1459,11 @@ import java.util.regex.Pattern;
switch (type) { switch (type) {
case WATER_BUCKET: case WATER_BUCKET:
case LAVA_BUCKET: { case LAVA_BUCKET: {
if (event.getBlock().getType() == Material.DROPPER) if (event.getBlock().getType() == Material.DROPPER) {
return; return;
}
BlockFace targetFace = BlockFace targetFace =
((org.bukkit.material.Dispenser) event.getBlock().getState().getData()) ((Directional) event.getBlock().getState().getData()).getFacing();
.getFacing();
Location location = Location location =
BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation());
if (location.isPlotRoad()) { if (location.isPlotRoad()) {
@ -1572,8 +1584,9 @@ import java.util.regex.Pattern;
switch (newItem.getType()) { switch (newItem.getType()) {
case LEGACY_BANNER: case LEGACY_BANNER:
case PLAYER_HEAD: case PLAYER_HEAD:
if (newMeta != null) if (newMeta != null) {
break; break;
}
default: default:
return; return;
} }
@ -1589,11 +1602,13 @@ import java.util.regex.Pattern;
switch (stateType) { switch (stateType) {
case LEGACY_STANDING_BANNER: case LEGACY_STANDING_BANNER:
case LEGACY_WALL_BANNER: case LEGACY_WALL_BANNER:
if (itemType == Material.LEGACY_BANNER) if (itemType == Material.LEGACY_BANNER) {
break; break;
}
case LEGACY_SKULL: case LEGACY_SKULL:
if (itemType == Material.LEGACY_SKULL_ITEM) if (itemType == Material.LEGACY_SKULL_ITEM) {
break; break;
}
default: default:
return; return;
} }
@ -2102,7 +2117,8 @@ import java.util.regex.Pattern;
} }
} }
@EventHandler public void onPrime(ExplosionPrimeEvent event) { @EventHandler
public void onPrime(ExplosionPrimeEvent event) {
this.lastRadius = event.getRadius() + 1; this.lastRadius = event.getRadius() + 1;
} }
@ -2267,7 +2283,8 @@ import java.util.regex.Pattern;
PlotInventory.removePlotInventoryOpen(BukkitUtil.getPlayer(player)); PlotInventory.removePlotInventoryOpen(BukkitUtil.getPlayer(player));
} }
@EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { @EventHandler(priority = EventPriority.MONITOR)
public void onLeave(PlayerQuitEvent event) {
TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName());
PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer());
pp.unregister(); pp.unregister();
@ -2561,10 +2578,10 @@ import java.util.regex.Pattern;
} }
} }
@SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange = null; EntityDamageByEntityEvent eventChange = new EntityDamageByEntityEvent(event.getCombuster(),
eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
onEntityDamageByEntityEvent(eventChange); onEntityDamageByEntityEvent(eventChange);
if (eventChange.isCancelled()) { if (eventChange.isCancelled()) {

View File

@ -10,6 +10,7 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -37,8 +38,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
private static final HashMap<UUID, Interval> healRunnable = new HashMap<>(); private static final HashMap<UUID, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) { public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
@Override public void run() {
if (!healRunnable.isEmpty()) { if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator = for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) { healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
@ -79,7 +79,6 @@ public class PlotPlusListener extends PlotListener implements Listener {
} }
} }
} }
}
}, 0L, 20L); }, 0L, 20L);
} }
@ -108,7 +107,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
if (event.getEntityType() != EntityType.PLAYER) { if (event.getEntityType() != EntityType.PLAYER) {
return; return;
} }
Player player = (Player) event.getEntity(); Entity player = event.getEntity();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) { if (plot == null) {
return; return;

View File

@ -1,9 +1,13 @@
package com.github.intellectualsites.plotsquared.bukkit.listeners; package com.github.intellectualsites.plotsquared.bukkit.listeners;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils; import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.World; import org.bukkit.World;
@ -14,11 +18,6 @@ import org.bukkit.event.world.ChunkEvent;
import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused") public class SingleWorldListener implements Listener { @SuppressWarnings("unused") public class SingleWorldListener implements Listener {
private Method methodGetHandleChunk; private Method methodGetHandleChunk;
@ -33,8 +32,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
this.done = classChunk.getField("done").getRealField(); this.done = classChunk.getField("done").getRealField();
this.lit = classChunk.getField("lit").getRealField(); this.lit = classChunk.getField("lit").getRealField();
this.s = classChunk.getField("s").getRealField(); this.s = classChunk.getField("s").getRealField();
} catch (Throwable ignore) { } catch (NoSuchFieldException exception) {
ignore.printStackTrace(); exception.printStackTrace();
} }
Bukkit.getPluginManager().registerEvents(this, plugin); Bukkit.getPluginManager().registerEvents(this, plugin);
} }

View File

@ -135,7 +135,11 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
Horse horse = (Horse) entity; Horse horse = (Horse) entity;
this.horse = new HorseStats(); this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength(); this.horse.jump = horse.getJumpStrength();
this.horse.chest = horse.isCarryingChest(); if (horse instanceof ChestedHorse) {
this.horse.chest = ((ChestedHorse) horse).isCarryingChest();
} else {
this.horse.chest = false;
}
this.horse.variant = horse.getVariant(); this.horse.variant = horse.getVariant();
this.horse.style = horse.getStyle(); this.horse.style = horse.getStyle();
this.horse.color = horse.getColor(); this.horse.color = horse.getColor();
@ -175,10 +179,12 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return; return;
// END AGEABLE // // END AGEABLE //
case GUARDIAN: case GUARDIAN:
//todo no longer works (possible exception thrown)
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0); this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
case SKELETON: case SKELETON:
//todo no longer works (possible exception thrown)
this.dataByte = getOrdinal(Skeleton.SkeletonType.values(), this.dataByte = getOrdinal(Skeleton.SkeletonType.values(),
((Skeleton) entity).getSkeletonType()); ((Skeleton) entity).getSkeletonType());
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
@ -186,7 +192,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case ARMOR_STAND: case ARMOR_STAND:
ArmorStand stand = (ArmorStand) entity; ArmorStand stand = (ArmorStand) entity;
this.inventory = this.inventory =
new ItemStack[] {stand.getItemInHand().clone(), stand.getHelmet().clone(), new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(),
stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(),
stand.getBoots().clone()}; stand.getBoots().clone()};
storeLiving(stand); storeLiving(stand);
@ -279,11 +285,13 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
} }
} }
@Override public boolean equals(Object obj) { @Override
public boolean equals(Object obj) {
return this.hash == obj.hashCode(); return this.hash == obj.hashCode();
} }
@Override public int hashCode() { @Override
public int hashCode() {
return this.hash; return this.hash;
} }
@ -396,7 +404,8 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
this.tamed.tamed = tamed.isTamed(); this.tamed.tamed = tamed.isTamed();
} }
@Override public Entity spawn(World world, int xOffset, int zOffset) { @Override
public Entity spawn(World world, int xOffset, int zOffset) {
Location location = new Location(world, this.x + xOffset, this.y, this.z + zOffset); Location location = new Location(world, this.x + xOffset, this.y, this.z + zOffset);
location.setYaw(this.yaw); location.setYaw(this.yaw);
location.setPitch(this.pitch); location.setPitch(this.pitch);
@ -424,10 +433,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity; return entity;
} }
if (this.base.passenger != null) { if (this.base.passenger != null) {
try { entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) {
}
} }
if (this.base.fall != 0) { if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall); entity.setFallDistance(this.base.fall);
@ -512,7 +518,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case HORSE: case HORSE:
Horse horse = (Horse) entity; Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump); horse.setJumpStrength(this.horse.jump);
horse.setCarryingChest(this.horse.chest); if (horse instanceof ChestedHorse && this.horse.chest) {
((ChestedHorse) horse).setCarryingChest(true);
}
//todo broken in 1.13 possible exception thrown
horse.setVariant(this.horse.variant); horse.setVariant(this.horse.variant);
horse.setStyle(this.horse.style); horse.setStyle(this.horse.style);
horse.setColor(this.horse.color); horse.setColor(this.horse.color);
@ -559,12 +568,15 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity; return entity;
case GUARDIAN: case GUARDIAN:
if (this.dataByte != 0) { if (this.dataByte != 0) {
//todo broken in 1.13 possible exception thrown
((Guardian) entity).setElder(true); ((Guardian) entity).setElder(true);
} }
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
case SKELETON: case SKELETON:
if (this.dataByte != 0) { if (this.dataByte != 0) {
//todo broken in 1.13 possible exception thrown
((Skeleton) entity) ((Skeleton) entity)
.setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]); .setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]);
} }

View File

@ -20,6 +20,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.bukkit.inventory.meta.Damageable;
public class StateWrapper { public class StateWrapper {
@ -241,7 +242,7 @@ public class StateWrapper {
public Map<String, Tag> serializeItem(ItemStack item) { public Map<String, Tag> serializeItem(ItemStack item) {
Map<String, Tag> data = new HashMap<>(); Map<String, Tag> data = new HashMap<>();
data.put("id", new StringTag(item.getType().name())); data.put("id", new StringTag(item.getType().name()));
data.put("Damage", new ShortTag(item.getDurability())); data.put("Damage", new ShortTag((short) ((Damageable)item.getItemMeta()).getDamage()));
data.put("Count", new ByteTag((byte) item.getAmount())); data.put("Count", new ByteTag((byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) { if (!item.getEnchantments().isEmpty()) {
List<CompoundTag> enchantmentList = new ArrayList<>(); List<CompoundTag> enchantmentList = new ArrayList<>();

View File

@ -187,11 +187,7 @@ public abstract class TitleManager {
throws IllegalArgumentException, ReflectiveOperationException, SecurityException; throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
private Class<?> getPrimitiveType(Class<?> clazz) { private Class<?> getPrimitiveType(Class<?> clazz) {
if (CORRESPONDING_TYPES.containsKey(clazz)) { return CORRESPONDING_TYPES.getOrDefault(clazz, clazz);
return CORRESPONDING_TYPES.get(clazz);
} else {
return clazz;
}
} }
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) { private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {

View File

@ -335,7 +335,7 @@ public class TitleManager_1_11 {
} }
private Class<?> getPrimitiveType(Class<?> clazz) { private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; return CORRESPONDING_TYPES.getOrDefault(clazz, clazz);
} }
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) { private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {

View File

@ -99,10 +99,6 @@ public final class BukkitEventUtil extends EventUtil {
new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner)); 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) { @Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot); PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);

View File

@ -83,7 +83,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
// int id = item.getTypeId(); // int id = item.getTypeId();
Material id = item.getType(); Material id = item.getType();
short data = item.getDurability(); //short data = item.getDurability();
int amount = item.getAmount(); int amount = item.getAmount();
String name = null; String name = null;
String[] lore = null; String[] lore = null;
@ -94,7 +94,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
if (meta.hasLore()) { if (meta.hasLore()) {
List<String> itemLore = meta.getLore(); List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]); lore = itemLore.toArray(new String[0]);
} }
} }
return new PlotItemStack(id.name(), amount, name, lore); return new PlotItemStack(id.name(), amount, name, lore);

View File

@ -1,5 +1,7 @@
package com.github.intellectualsites.plotsquared.bukkit.util; package com.github.intellectualsites.plotsquared.bukkit.util;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc;
@ -12,22 +14,19 @@ import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefFie
import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod; import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.bukkit.Bukkit;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Player;
/** /**
* An utility that can be used to send chunks, rather than using bukkit code * An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy
* to do so (uses heavy NMS). * NMS).
*/ */
public class SendChunk { public class SendChunk {
@ -118,8 +117,7 @@ public class SendChunk {
} }
} }
for (final Chunk chunk : chunks) { for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> {
@Override public void run() {
try { try {
chunk.unload(true, false); chunk.unload(true, false);
} catch (Throwable ignored) { } catch (Throwable ignored) {
@ -132,7 +130,6 @@ public class SendChunk {
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)"); + "/level_old.dat may be corrupt (try repairing or removing these)");
} }
}
}); });
} }
} }

View File

@ -192,8 +192,7 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
for (int x = 0; x < lc.biomes.length; x++) { for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x]; String[] biomes2 = lc.biomes[x];
if (biomes2 != null) { if (biomes2 != null) {
for (int y = 0; y < biomes2.length; y++) { for (String biomeStr : biomes2) {
String biomeStr = biomes2[y];
if (biomeStr != null) { if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) { if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = Biome.valueOf(biomeStr.toUpperCase()); biome = Biome.valueOf(biomeStr.toUpperCase());

View File

@ -5,12 +5,13 @@ import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import java.util.Arrays;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import java.util.UUID; import java.util.UUID;
public class DefaultUUIDWrapper extends UUIDWrapper { public class DefaultUUIDWrapper implements UUIDWrapper {
@Override public UUID getUUID(PlotPlayer player) { @Override public UUID getUUID(PlotPlayer player) {
return ((BukkitPlayer) player).player.getUniqueId(); return ((BukkitPlayer) player).player.getUniqueId();
@ -30,11 +31,8 @@ public class DefaultUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() { @Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; return Arrays.stream(ops).map(BukkitOfflinePlayer::new)
for (int i = 0; i < ops.length; i++) { .toArray(BukkitOfflinePlayer[]::new);
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
} }
@Override public OfflinePlotPlayer getOfflinePlayer(String name) { @Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -47,8 +47,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} else { } else {
world = worlds.get(0).getName(); world = worlds.get(0).getName();
} }
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world); PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) { if (uuidFile.exists()) {
@ -82,7 +81,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} }
} }
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>()); HashBiMap.create(new HashMap<>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) { if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS(); HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!"); PlotSquared.debug("&aFast mode UUID caching enabled!");
@ -133,11 +132,11 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
+ " uuids - slowly processing all files"); + " uuids - slowly processing all files");
} }
} }
HashSet<String> worlds = Sets.newHashSet(world, "world"); HashSet<String> worlds1 = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>(); HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>(); HashSet<String> names = new HashSet<>();
File playerDataFolder = null; File playerDataFolder = null;
for (String worldName : worlds) { for (String worldName : worlds1) {
// Getting UUIDs // Getting UUIDs
playerDataFolder = playerDataFolder =
new File(container, worldName + File.separator + "playerdata"); new File(container, worldName + File.separator + "playerdata");
@ -234,17 +233,14 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }
}
}); });
return true; return true;
} }
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) { @Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
}
}); });
} }
} }

View File

@ -9,6 +9,7 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.collect.BiMap; import com.google.common.collect.BiMap;
import java.util.Arrays;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.Server; import org.bukkit.Server;
@ -19,7 +20,7 @@ import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.UUID; import java.util.UUID;
public class OfflineUUIDWrapper extends UUIDWrapper { public class OfflineUUIDWrapper implements UUIDWrapper {
private final Object[] arg = new Object[0]; private final Object[] arg = new Object[0];
private Method getOnline = null; private Method getOnline = null;
@ -59,18 +60,15 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
return new BukkitOfflinePlayer(op); return new BukkitOfflinePlayer(op);
} }
} }
for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { return Arrays.stream(Bukkit.getOfflinePlayers())
if (getUUID(player).equals(uuid)) { .filter(player -> getUUID(player).equals(uuid)).findFirst()
return new BukkitOfflinePlayer(player); .map(BukkitOfflinePlayer::new).orElse(null);
}
}
return null;
} }
public Player[] getOnlinePlayers() { public Player[] getOnlinePlayers() {
if (this.getOnline == null) { if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers(); Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]); return onlinePlayers.toArray(new Player[0]);
} }
try { try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -79,13 +77,13 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
} else { } else {
@SuppressWarnings("unchecked") Collection<? extends Player> p = @SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players; (Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]); return p.toArray(new Player[0]);
} }
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
PlotSquared.debug("Failed to resolve online players"); PlotSquared.debug("Failed to resolve online players");
this.getOnline = null; this.getOnline = null;
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers(); Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]); return onlinePlayers.toArray(new Player[0]);
} }
} }
@ -95,11 +93,8 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() { @Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; return Arrays.stream(ops).map(BukkitOfflinePlayer::new)
for (int i = 0; i < ops.length; i++) { .toArray(BukkitOfflinePlayer[]::new);
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
} }
@Override public OfflinePlotPlayer getOfflinePlayer(String name) { @Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -71,11 +71,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) { if (!super.startCaching(whenDone)) {
return false; return false;
} }
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
try { try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>()); HashBiMap.create(new HashMap<>());
try (PreparedStatement statement = getConnection() try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); .prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) { ResultSet resultSet = statement.executeQuery()) {
@ -102,8 +101,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
FileUUIDHandler fileHandler = FileUUIDHandler fileHandler =
new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() { fileHandler.startCaching(() -> {
@Override public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode // 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 // 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 (Settings.UUID.OFFLINE) {
@ -113,8 +111,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
return; return;
} }
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
while (!toFetch.isEmpty()) { while (!toFetch.isEmpty()) {
try { try {
for (int i = 0; for (int i = 0;
@ -154,14 +151,11 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
whenDone.run(); whenDone.run();
} }
return; return;
}
}); });
}
}); });
} catch (SQLException e) { } catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e); throw new SQLUUIDHandlerException("Couldn't select :s", e);
} }
}
}); });
return true; return true;
} }
@ -172,8 +166,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (ifFetch == null) { if (ifFetch == null) {
return; return;
} }
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
try { try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
@ -191,7 +184,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
.parse(new InputStreamReader(connection.getInputStream())); .parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0); JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id"); String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name"); String name1 = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString( ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32)); + '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
@ -199,7 +192,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
}
}); });
} }
@ -215,8 +207,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override public boolean add(final StringWrapper name, final UUID uuid) { @Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates // Ignoring duplicates
if (super.add(name, uuid)) { if (super.add(name, uuid)) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
try (PreparedStatement statement = getConnection().prepareStatement( try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { "REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
@ -227,7 +218,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
return true; return true;
} }
@ -239,8 +229,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
*/ */
@Override public void rename(final UUID uuid, final StringWrapper name) { @Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name); super.rename(uuid, name);
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
try (PreparedStatement statement = getConnection() try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value); statement.setString(1, name.value);
@ -251,7 +240,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }

View File

@ -1,6 +1,7 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import java.util.Map; import java.util.Map;
import javax.annotation.Nonnull;
/** /**
* Represents a source of configurable options and settings. * Represents a source of configurable options and settings.
@ -20,7 +21,7 @@ public interface Configuration extends ConfigurationSection {
* @param value Value to set the default to. * @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null. * @throws IllegalArgumentException Thrown if path is null.
*/ */
@Override void addDefault(String path, Object value); @Override void addDefault(@Nonnull String path, Object value);
/** /**
* Sets the default values of the given paths as provided. * Sets the default values of the given paths as provided.

View File

@ -31,7 +31,7 @@ class ConfigurationOptions {
* *
* @return Path separator * @return Path separator
*/ */
public char pathSeparator() { char pathSeparator() {
return pathSeparator; return pathSeparator;
} }
@ -64,7 +64,7 @@ class ConfigurationOptions {
* *
* @return Whether or not defaults are directly copied * @return Whether or not defaults are directly copied
*/ */
public boolean copyDefaults() { boolean copyDefaults() {
return copyDefaults; return copyDefaults;
} }

View File

@ -3,6 +3,7 @@ package com.github.intellectualsites.plotsquared.configuration;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.annotation.Nonnull;
/** /**
* Represents a section of a {@link Configuration}. * Represents a section of a {@link Configuration}.
@ -52,7 +53,7 @@ public interface ConfigurationSection {
* default or being set. * default or being set.
* @throws IllegalArgumentException Thrown when path is {@code null}. * @throws IllegalArgumentException Thrown when path is {@code null}.
*/ */
boolean contains(String path); boolean contains(@Nonnull String path);
/** /**
* Checks if this {@link ConfigurationSection} has a value set for the * Checks if this {@link ConfigurationSection} has a value set for the
@ -66,7 +67,7 @@ public interface ConfigurationSection {
* having a default. * having a default.
* @throws IllegalArgumentException Thrown when path is {@code null}. * @throws IllegalArgumentException Thrown when path is {@code null}.
*/ */
boolean isSet(String path); boolean isSet(@Nonnull String path);
/** /**
* Gets the path of this {@link ConfigurationSection} from its root {@link * Gets the path of this {@link ConfigurationSection} from its root {@link
@ -151,7 +152,7 @@ public interface ConfigurationSection {
* @param defaultValue The default value to return if the path is not found. * @param defaultValue The default value to return if the path is not found.
* @return Requested Object. * @return Requested Object.
*/ */
Object get(String path, Object defaultValue); Object getOrDefault(@Nonnull String path, Object defaultValue);
/** /**
* Sets the specified path to the given value. * Sets the specified path to the given value.
@ -644,5 +645,5 @@ public interface ConfigurationSection {
* @param value Value to set the default to * @param value Value to set the default to
* @throws IllegalArgumentException Thrown if path is {@code null} * @throws IllegalArgumentException Thrown if path is {@code null}
*/ */
void addDefault(String path, Object value); void addDefault(@Nonnull String path, Object value);
} }

View File

@ -1,6 +1,7 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import java.util.Map; import java.util.Map;
import javax.annotation.Nonnull;
/** /**
* This is a {@link Configuration} implementation that does not save or load * This is a {@link Configuration} implementation that does not save or load
@ -28,7 +29,7 @@ public class MemoryConfiguration extends MemorySection implements Configuration
this.defaults = defaults; this.defaults = defaults;
} }
@Override public void addDefault(String path, Object value) { @Override public void addDefault(@Nonnull String path, Object value) {
if (this.defaults == null) { if (this.defaults == null) {
this.defaults = new MemoryConfiguration(); this.defaults = new MemoryConfiguration();
} }

View File

@ -1,6 +1,7 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import java.util.*; import java.util.*;
import javax.annotation.Nonnull;
/** /**
* A type of {@link ConfigurationSection} that is stored in memory. * A type of {@link ConfigurationSection} that is stored in memory.
@ -14,14 +15,12 @@ public class MemorySection implements ConfigurationSection {
private final String fullPath; private final String fullPath;
/** /**
* Creates an empty MemorySection for use as a root {@link Configuration} * Creates an empty MemorySection for use as a root {@link Configuration} section.
* section.
* *
* <p>Note that calling this without being yourself a {@link Configuration} * <p>Note that calling this without being yourself a {@link Configuration}
* will throw an exception! * will throw an exception!
* *
* @throws IllegalStateException Thrown if this is not a {@link * @throws IllegalStateException Thrown if this is not a {@link Configuration} root.
* Configuration} root.
*/ */
protected MemorySection() { protected MemorySection() {
if (!(this instanceof Configuration)) { if (!(this instanceof Configuration)) {
@ -39,10 +38,9 @@ public class MemorySection implements ConfigurationSection {
* Creates an empty MemorySection with the specified parent and path. * Creates an empty MemorySection with the specified parent and path.
* *
* @param parent Parent section that contains this own section. * @param parent Parent section that contains this own section.
* @param path Path that you may access this section from via the root * @param path Path that you may access this section from via the root {@link Configuration}.
* {@link Configuration}. * @throws IllegalArgumentException Thrown is parent or path is null, or if parent contains no
* @throws IllegalArgumentException Thrown is parent or path is null, or * root Configuration.
* if parent contains no root Configuration.
*/ */
protected MemorySection(ConfigurationSection parent, String path) { protected MemorySection(ConfigurationSection parent, String path) {
this.path = path; this.path = path;
@ -111,8 +109,8 @@ public class MemorySection implements ConfigurationSection {
} }
/** /**
* Creates a full path to the given {@link ConfigurationSection} from its * Creates a full path to the given {@link ConfigurationSection} from its root {@link
* root {@link Configuration}. * Configuration}.
* *
* <p>You may use this method for any given {@link ConfigurationSection}, not * <p>You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}. * only {@link MemorySection}.
@ -126,8 +124,8 @@ public class MemorySection implements ConfigurationSection {
} }
/** /**
* Creates a relative path to the given {@link ConfigurationSection} from * Creates a relative path to the given {@link ConfigurationSection} from the given relative
* the given relative section. * section.
* *
* <p>You may use this method for any given {@link ConfigurationSection}, not * <p>You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}. * only {@link MemorySection}.
@ -166,7 +164,8 @@ public class MemorySection implements ConfigurationSection {
return builder.toString(); return builder.toString();
} }
@Override public Set<String> getKeys(boolean deep) { @Override
public Set<String> getKeys(boolean deep) {
Set<String> result = new LinkedHashSet<>(); Set<String> result = new LinkedHashSet<>();
Configuration root = getRoot(); Configuration root = getRoot();
@ -183,7 +182,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public Map<String, Object> getValues(boolean deep) { @Override
public Map<String, Object> getValues(boolean deep) {
Map<String, Object> result = new LinkedHashMap<>(); Map<String, Object> result = new LinkedHashMap<>();
Configuration root = getRoot(); Configuration root = getRoot();
@ -200,11 +200,13 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public boolean contains(String path) { @Override
public boolean contains(@Nonnull String path) {
return get(path) != null; return get(path) != null;
} }
@Override public boolean isSet(String path) { @Override
public boolean isSet(@Nonnull String path) {
Configuration root = getRoot(); Configuration root = getRoot();
if (root == null) { if (root == null) {
return false; return false;
@ -212,26 +214,31 @@ public class MemorySection implements ConfigurationSection {
if (root.options().copyDefaults()) { if (root.options().copyDefaults()) {
return contains(path); return contains(path);
} }
return get(path, null) != null; return getOrDefault(path, null) != null;
} }
@Override public String getCurrentPath() { @Override
public String getCurrentPath() {
return this.fullPath; return this.fullPath;
} }
@Override public String getName() { @Override
public String getName() {
return this.path; return this.path;
} }
@Override public Configuration getRoot() { @Override
public Configuration getRoot() {
return this.root; return this.root;
} }
@Override public ConfigurationSection getParent() { @Override
public ConfigurationSection getParent() {
return this.parent; return this.parent;
} }
@Override public void addDefault(String path, Object value) { @Override
public void addDefault(@Nonnull String path, Object value) {
Configuration root = getRoot(); Configuration root = getRoot();
if (root == null) { if (root == null) {
throw new IllegalStateException("Cannot add default without root"); throw new IllegalStateException("Cannot add default without root");
@ -243,7 +250,8 @@ public class MemorySection implements ConfigurationSection {
root.addDefault(createPath(this, path), value); root.addDefault(createPath(this, path), value);
} }
@Override public ConfigurationSection getDefaultSection() { @Override
public ConfigurationSection getDefaultSection() {
Configuration root = getRoot(); Configuration root = getRoot();
Configuration defaults = root == null ? null : root.getDefaults(); Configuration defaults = root == null ? null : root.getDefaults();
@ -256,7 +264,8 @@ public class MemorySection implements ConfigurationSection {
return null; return null;
} }
@Override public void set(String path, Object value) { @Override
public void set(String path, Object value) {
Configuration root = getRoot(); Configuration root = getRoot();
if (root == null) { if (root == null) {
throw new IllegalStateException("Cannot use section without a root"); throw new IllegalStateException("Cannot use section without a root");
@ -290,15 +299,13 @@ public class MemorySection implements ConfigurationSection {
} }
} }
@Override public Object get(String path) { @Override
return get(path, getDefault(path)); public Object get(String path) {
} return getOrDefault(path, getDefault(path));
@Override public Object get(String path, Object defaultValue) {
if (path == null) {
throw new NullPointerException("Path cannot be null");
} }
@Override
public Object getOrDefault(@Nonnull String path, Object defaultValue) {
if (path.isEmpty()) { if (path.isEmpty()) {
return this; return this;
} }
@ -330,10 +337,11 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
} }
return section.get(key, defaultValue); return section.getOrDefault(key, defaultValue);
} }
@Override public ConfigurationSection createSection(String path) { @Override
public ConfigurationSection createSection(String path) {
Configuration root = getRoot(); Configuration root = getRoot();
if (root == null) { if (root == null) {
throw new IllegalStateException("Cannot create section without a root"); throw new IllegalStateException("Cannot create section without a root");
@ -364,7 +372,8 @@ public class MemorySection implements ConfigurationSection {
return section.createSection(key); return section.createSection(key);
} }
@Override public ConfigurationSection createSection(String path, Map<?, ?> map) { @Override
public ConfigurationSection createSection(String path, Map<?, ?> map) {
ConfigurationSection section = createSection(path); ConfigurationSection section = createSection(path);
for (Map.Entry<?, ?> entry : map.entrySet()) { for (Map.Entry<?, ?> entry : map.entrySet()) {
@ -379,13 +388,15 @@ public class MemorySection implements ConfigurationSection {
} }
// Primitives // Primitives
@Override public String getString(String path) { @Override
public String getString(String path) {
Object def = getDefault(path); Object def = getDefault(path);
return getString(path, def != null ? def.toString() : null); return getString(path, def != null ? def.toString() : null);
} }
@Override public String getString(String path, String def) { @Override
Object val = get(path, def); public String getString(String path, String def) {
Object val = getOrDefault(path, def);
if (val != null) { if (val != null) {
return val.toString(); return val.toString();
} else { } else {
@ -393,27 +404,32 @@ public class MemorySection implements ConfigurationSection {
} }
} }
@Override public boolean isString(String path) { @Override
public boolean isString(String path) {
Object val = get(path); Object val = get(path);
return val instanceof String; return val instanceof String;
} }
@Override public int getInt(String path) { @Override
public int getInt(String path) {
Object def = getDefault(path); Object def = getDefault(path);
return getInt(path, toInt(def, 0)); return getInt(path, toInt(def, 0));
} }
@Override public int getInt(String path, int def) { @Override
Object val = get(path, def); public int getInt(String path, int def) {
Object val = getOrDefault(path, def);
return toInt(val, def); return toInt(val, def);
} }
@Override public boolean isInt(String path) { @Override
public boolean isInt(String path) {
Object val = get(path); Object val = get(path);
return val instanceof Integer; return val instanceof Integer;
} }
@Override public boolean getBoolean(String path) { @Override
public boolean getBoolean(String path) {
Object def = getDefault(path); Object def = getDefault(path);
if (def instanceof Boolean) { if (def instanceof Boolean) {
return getBoolean(path, (Boolean) def); return getBoolean(path, (Boolean) def);
@ -422,8 +438,9 @@ public class MemorySection implements ConfigurationSection {
} }
} }
@Override public boolean getBoolean(String path, boolean defaultValue) { @Override
Object val = get(path, defaultValue); public boolean getBoolean(String path, boolean defaultValue) {
Object val = getOrDefault(path, defaultValue);
if (val instanceof Boolean) { if (val instanceof Boolean) {
return (Boolean) val; return (Boolean) val;
} else { } else {
@ -431,58 +448,69 @@ public class MemorySection implements ConfigurationSection {
} }
} }
@Override public boolean isBoolean(String path) { @Override
public boolean isBoolean(String path) {
Object val = get(path); Object val = get(path);
return val instanceof Boolean; return val instanceof Boolean;
} }
@Override public double getDouble(String path) { @Override
public double getDouble(String path) {
Object def = getDefault(path); Object def = getDefault(path);
return getDouble(path, toDouble(def, 0)); return getDouble(path, toDouble(def, 0));
} }
@Override public double getDouble(String path, double defaultValue) { @Override
Object val = get(path, defaultValue); public double getDouble(String path, double defaultValue) {
Object val = getOrDefault(path, defaultValue);
return toDouble(val, defaultValue); return toDouble(val, defaultValue);
} }
@Override public boolean isDouble(String path) { @Override
public boolean isDouble(String path) {
Object val = get(path); Object val = get(path);
return val instanceof Double; return val instanceof Double;
} }
@Override public long getLong(String path) { @Override
public long getLong(String path) {
Object def = getDefault(path); Object def = getDefault(path);
return getLong(path, toLong(def, 0)); return getLong(path, toLong(def, 0));
} }
@Override public long getLong(String path, long def) { @Override
Object val = get(path, def); public long getLong(String path, long def) {
Object val = getOrDefault(path, def);
return toLong(val, def); return toLong(val, def);
} }
@Override public boolean isLong(String path) { @Override
public boolean isLong(String path) {
Object val = get(path); Object val = get(path);
return val instanceof Long; return val instanceof Long;
} }
// Java // Java
@Override public List<?> getList(String path) { @Override
public List<?> getList(String path) {
Object def = getDefault(path); Object def = getDefault(path);
return getList(path, def instanceof List ? (List<?>) def : null); return getList(path, def instanceof List ? (List<?>) def : null);
} }
@Override public List<?> getList(String path, List<?> def) { @Override
Object val = get(path, def); public List<?> getList(String path, List<?> def) {
Object val = getOrDefault(path, def);
return (List<?>) ((val instanceof List) ? val : def); return (List<?>) ((val instanceof List) ? val : def);
} }
@Override public boolean isList(String path) { @Override
public boolean isList(String path) {
Object val = get(path); Object val = get(path);
return val instanceof List; return val instanceof List;
} }
@Override public List<String> getStringList(String path) { @Override
public List<String> getStringList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) { if (list == null) {
@ -500,7 +528,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Integer> getIntegerList(String path) { @Override
public List<Integer> getIntegerList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Integer> result = new ArrayList<>(); List<Integer> result = new ArrayList<>();
@ -523,7 +552,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Boolean> getBooleanList(String path) { @Override
public List<Boolean> getBooleanList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Boolean> result = new ArrayList<>(); List<Boolean> result = new ArrayList<>();
@ -543,7 +573,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Double> getDoubleList(String path) { @Override
public List<Double> getDoubleList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Double> result = new ArrayList<>(); List<Double> result = new ArrayList<>();
@ -566,7 +597,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Float> getFloatList(String path) { @Override
public List<Float> getFloatList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Float> result = new ArrayList<>(); List<Float> result = new ArrayList<>();
@ -589,7 +621,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Long> getLongList(String path) { @Override
public List<Long> getLongList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Long> result = new ArrayList<>(); List<Long> result = new ArrayList<>();
@ -612,7 +645,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Byte> getByteList(String path) { @Override
public List<Byte> getByteList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Byte> result = new ArrayList<>(); List<Byte> result = new ArrayList<>();
@ -635,7 +669,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Character> getCharacterList(String path) { @Override
public List<Character> getCharacterList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Character> result = new ArrayList<>(); List<Character> result = new ArrayList<>();
@ -657,7 +692,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Short> getShortList(String path) { @Override
public List<Short> getShortList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Short> result = new ArrayList<>(); List<Short> result = new ArrayList<>();
@ -680,7 +716,8 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public List<Map<?, ?>> getMapList(String path) { @Override
public List<Map<?, ?>> getMapList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
List<Map<?, ?>> result = new ArrayList<>(); List<Map<?, ?>> result = new ArrayList<>();
@ -693,17 +730,19 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public ConfigurationSection getConfigurationSection(String path) { @Override
Object val = get(path, null); public ConfigurationSection getConfigurationSection(String path) {
Object val = getOrDefault(path, null);
if (val != null) { if (val != null) {
return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
} }
val = get(path, getDefault(path)); val = getOrDefault(path, getDefault(path));
return (val instanceof ConfigurationSection) ? createSection(path) : null; return (val instanceof ConfigurationSection) ? createSection(path) : null;
} }
@Override public boolean isConfigurationSection(String path) { @Override
public boolean isConfigurationSection(String path) {
Object val = get(path); Object val = get(path);
return val instanceof ConfigurationSection; return val instanceof ConfigurationSection;
} }
@ -764,7 +803,8 @@ public class MemorySection implements ConfigurationSection {
} }
} }
@Override public String toString() { @Override
public String toString() {
Configuration root = getRoot(); Configuration root = getRoot();
if (root == null) { if (root == null) {
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null

View File

@ -6,6 +6,7 @@ import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguratio
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import javax.annotation.Nonnull;
/** /**
* This is a base class for all File based implementations of {@link * This is a base class for all File based implementations of {@link
@ -82,7 +83,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration. * a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void load(File file) throws IOException, InvalidConfigurationException { public void load(@Nonnull File file) throws IOException, InvalidConfigurationException {
FileInputStream stream = new FileInputStream(file); FileInputStream stream = new FileInputStream(file);

View File

@ -83,7 +83,7 @@ public class YamlConfiguration extends FileConfiguration {
Map<?, ?> input; Map<?, ?> input;
try { try {
input = (Map<?, ?>) yaml.load(contents); input = yaml.load(contents);
} catch (YAMLException e) { } catch (YAMLException e) {
throw new InvalidConfigurationException(e); throw new InvalidConfigurationException(e);
} catch (ClassCastException ignored) { } catch (ClassCastException ignored) {

View File

@ -42,7 +42,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
* *
* @return How much to indent by * @return How much to indent by
*/ */
public int indent() { int indent() {
return indent; return indent;
} }

View File

@ -9,7 +9,7 @@ import org.yaml.snakeyaml.nodes.Tag;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
public class YamlConstructor extends SafeConstructor { class YamlConstructor extends SafeConstructor {
YamlConstructor() { YamlConstructor() {
yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); yamlConstructors.put(Tag.MAP, new ConstructCustomObject());

View File

@ -76,7 +76,9 @@ public interface IPlotMain extends ILogger {
* *
* @return * @return
*/ */
String getPluginName(); default String getPluginName() {
return "PlotSquared";
}
/** /**
* Get the version of Minecraft that is running. * Get the version of Minecraft that is running.

View File

@ -1,6 +1,6 @@
package com.github.intellectualsites.plotsquared.plot; package com.github.intellectualsites.plotsquared.plot;
public enum Platform { public enum Platform {
Bukkit, Sponge, Spigot, Cauldron Bukkit, Sponge, Spigot
} }

File diff suppressed because one or more lines are too long

View File

@ -104,8 +104,7 @@ import java.util.Set;
final String path = final String path =
"worlds." + area.worldname + ".areas." + area.id + '-' "worlds." + area.worldname + ".areas." + area.id + '-'
+ object.min + '-' + object.max; + object.min + '-' + object.max;
Runnable run = new Runnable() { Runnable run = () -> {
@Override public void run() {
if (offsetX != 0) { if (offsetX != 0) {
PlotSquared.get().worlds PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX); .set(path + ".road.offset.x", offsetX);
@ -134,7 +133,6 @@ import java.util.Set;
"An error occurred while creating the world: " "An error occurred while creating the world: "
+ area.worldname); + area.worldname);
} }
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, CmdConfirm.addPending(player,
@ -228,8 +226,7 @@ import java.util.Set;
C.SETUP_WORLD_TAKEN.send(player, pa.worldname); C.SETUP_WORLD_TAKEN.send(player, pa.worldname);
return false; return false;
} }
Runnable run = new Runnable() { Runnable run = () -> {
@Override public void run() {
String path = "worlds." + pa.worldname; String path = "worlds." + pa.worldname;
if (!PlotSquared.get().worlds.contains(path)) { if (!PlotSquared.get().worlds.contains(path)) {
PlotSquared.get().worlds.createSection(path); PlotSquared.get().worlds.createSection(path);
@ -254,7 +251,6 @@ import java.util.Set;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, CmdConfirm.addPending(player,
@ -422,11 +418,7 @@ import java.util.Set;
@Override public void run(ChunkLoc value) { @Override public void run(ChunkLoc value) {
AugmentedUtils.generate(area.worldname, value.x, value.z, null); AugmentedUtils.generate(area.worldname, value.x, value.z, null);
} }
}, new Runnable() { }, () -> player.sendMessage("Regen complete"));
@Override public void run() {
player.sendMessage("Regen complete");
}
});
return true; return true;
} }
case "goto": case "goto":

View File

@ -82,22 +82,14 @@ public class Claim extends SubCommand {
if (plot.canClaim(player)) { if (plot.canClaim(player)) {
plot.owner = player.getUUID(); plot.owner = player.getUUID();
final String finalSchematic = schematic; final String finalSchematic = schematic;
DBFunc.createPlotSafe(plot, new Runnable() { DBFunc.createPlotSafe(plot, () -> TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override public void run() {
TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override public void run(Object value) { @Override public void run(Object value) {
plot.claim(player, true, finalSchematic, false); plot.claim(player, true, finalSchematic, false);
if (area.AUTO_MERGE) { if (area.AUTO_MERGE) {
plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); 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; return true;
} else { } else {
sendMessage(player, C.PLOT_NOT_CLAIMED); sendMessage(player, C.PLOT_NOT_CLAIMED);

View File

@ -302,6 +302,7 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area == null) { if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player); C.NOT_IN_PLOT_WORLD.send(player);
return false;
} }
PlotCluster cluster = area.getCluster(player.getLocation()); PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) { if (cluster == null) {
@ -347,6 +348,7 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area == null) { if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player); C.NOT_IN_PLOT_WORLD.send(player);
return false;
} }
PlotCluster cluster = area.getCluster(player.getLocation()); PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) { if (cluster == null) {
@ -405,6 +407,7 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area == null) { if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player); C.NOT_IN_PLOT_WORLD.send(player);
return false;
} }
PlotCluster cluster; PlotCluster cluster;
if (args.length == 2) { if (args.length == 2) {
@ -440,7 +443,6 @@ import java.util.UUID;
PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) { PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) {
PlotCluster current = plot.getCluster(); PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) { if (current != null && current.equals(cluster)) {
player.getLocation().getWorld();
plot.unclaim(); plot.unclaim();
} }
} }
@ -462,6 +464,7 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area == null) { if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player); C.NOT_IN_PLOT_WORLD.send(player);
return false;
} }
PlotCluster cluster = area.getCluster(player.getLocation()); PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) { if (cluster == null) {
@ -534,6 +537,7 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area == null) { if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player); C.NOT_IN_PLOT_WORLD.send(player);
return false;
} }
PlotCluster cluster; PlotCluster cluster;
if (args.length == 2) { if (args.length == 2) {
@ -581,6 +585,7 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area == null) { if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player); C.NOT_IN_PLOT_WORLD.send(player);
return false;
} }
PlotCluster cluster = area.getCluster(player.getLocation()); PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) { if (cluster == null) {

View File

@ -65,6 +65,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
sizes.add(size - 1); sizes.add(size - 1);
} }
// Sort plots by size (buckets?)] // Sort plots by size (buckets?)]
//noinspection unchecked
ArrayList<Plot>[] buckets = new ArrayList[maxSize]; ArrayList<Plot>[] buckets = new ArrayList[maxSize];
for (int i = 0; i < plots.size(); i++) { for (int i = 0; i < plots.size(); i++) {
Plot plot = plots.get(i); Plot plot = plots.get(i);
@ -126,14 +127,12 @@ import java.util.concurrent.atomic.AtomicBoolean;
} }
i++; i++;
final AtomicBoolean result = new AtomicBoolean(false); final AtomicBoolean result = new AtomicBoolean(false);
result.set(origin.move(possible, new Runnable() { result.set(origin.move(possible, () -> {
@Override public void run() {
if (result.get()) { if (result.get()) {
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"Moving: " + origin + " -> " + possible); "Moving: " + origin + " -> " + possible);
TaskManager.runTaskLater(task, 1); TaskManager.runTaskLater(task, 1);
} }
}
}, false)); }, false));
if (result.get()) { if (result.get()) {
break; break;

View File

@ -25,35 +25,30 @@ import java.util.Map.Entry;
@CommandDeclaration(command = "database", aliases = {"convert"}, @CommandDeclaration(command = "database", aliases = {"convert"},
category = CommandCategory.ADMINISTRATION, permission = "plots.database", category = CommandCategory.ADMINISTRATION, permission = "plots.database",
description = "Convert/Backup Storage", requiredType = RequiredType.CONSOLE, description = "Convert/Backup Storage", requiredType = RequiredType.CONSOLE,
usage = "/plot database [area] <sqlite|mysql|import>") public class Database usage = "/plot database [area] <sqlite|mysql|import>")
public class Database
extends SubCommand { extends SubCommand {
public static void insertPlots(final SQLManager manager, final List<Plot> plots, public static void insertPlots(final SQLManager manager, final List<Plot> plots,
final PlotPlayer player) { final PlotPlayer player) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
try { try {
ArrayList<Plot> ps = new ArrayList<>(); ArrayList<Plot> ps = new ArrayList<>(plots);
for (Plot p : plots) {
ps.add(p);
}
MainUtil.sendMessage(player, "&6Starting..."); MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, new Runnable() { manager.createPlotsAndData(ps, () -> {
@Override public void run() {
MainUtil.sendMessage(player, "&6Database conversion finished!"); MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close(); manager.close();
}
}); });
} catch (Exception e) { } catch (Exception e) {
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"Failed to insert plot objects, see stacktrace for info"); "Failed to insert plot objects, see stacktrace for info");
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override
public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length < 1) { if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [area] <sqlite|mysql|import>"); MainUtil.sendMessage(player, "/plot database [area] <sqlite|mysql|import>");
return false; return false;
@ -131,19 +126,13 @@ import java.util.Map.Entry;
} }
} else { } else {
HashMap<PlotId, Plot> plotmap = HashMap<PlotId, Plot> plotmap =
PlotSquared.get().plots_tmp.get(areaname); PlotSquared.get().plots_tmp
if (plotmap == null) { .computeIfAbsent(areaname, k -> new HashMap<>());
plotmap = new HashMap<>();
PlotSquared.get().plots_tmp.put(areaname, plotmap);
}
plotmap.putAll(entry.getValue()); plotmap.putAll(entry.getValue());
} }
} }
DBFunc.createPlotsAndData(plots, new Runnable() { DBFunc.createPlotsAndData(plots,
@Override public void run() { () -> MainUtil.sendMessage(player, "&6Database conversion finished!"));
MainUtil.sendMessage(player, "&6Database conversion finished!");
}
});
return true; return true;
case "mysql": case "mysql":
if (args.length < 6) { if (args.length < 6) {

View File

@ -57,9 +57,7 @@ public class Help extends Command {
public void displayHelp(PlotPlayer player, String cat, int page) { public void displayHelp(PlotPlayer player, String cat, int page) {
CommandCategory catEnum = null; CommandCategory catEnum = null;
if (cat != null) { if (cat != null) {
if (StringMan.isEqualIgnoreCase(cat, "all")) { if (!StringMan.isEqualIgnoreCase(cat, "all")) {
catEnum = null;
} else {
for (CommandCategory c : CommandCategory.values()) { for (CommandCategory c : CommandCategory.values()) {
if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) {
catEnum = c; catEnum = c;

View File

@ -165,9 +165,8 @@ import java.util.Optional;
inbox.clearInbox(plot); inbox.clearInbox(plot);
Optional<ArrayList<PlotComment>> comments = Optional<ArrayList<PlotComment>> comments =
plot.getSettings().getComments(inbox.toString()); plot.getSettings().getComments(inbox.toString());
if (comments.isPresent()) { comments
plot.getSettings().removeComments(comments.get()); .ifPresent(plotComments -> plot.getSettings().removeComments(plotComments));
}
MainUtil.sendMessage(player, C.COMMENT_REMOVED, "*"); MainUtil.sendMessage(player, C.COMMENT_REMOVED, "*");
return true; return true;
default: default:

View File

@ -60,9 +60,9 @@ public class Merge extends SubCommand {
} }
final PlotArea plotArea = plot.getArea(); final PlotArea plotArea = plot.getArea();
Expression<Double> priceExr = Expression<Double> priceExr =
plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; plotArea.PRICES.getOrDefault("merge", Expression.constant(0d));
final int size = plot.getConnectedPlots().size(); final int size = plot.getConnectedPlots().size();
final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); final double price = priceExr.evaluate((double) size);
if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d
&& EconHandler.manager.getMoney(player) < price) { && EconHandler.manager.getMoney(player) < price) {
sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price));

View File

@ -108,9 +108,7 @@ import java.util.UUID;
if (unknown && UUIDHandler.getName(plot.owner) != null) { if (unknown && UUIDHandler.getName(plot.owner) != null) {
continue; continue;
} }
for (Plot current : plot.getConnectedPlots()) { toDelete.addAll(plot.getConnectedPlots());
toDelete.add(current);
}
} }
if (PlotSquared.get().plots_tmp != null) { if (PlotSquared.get().plots_tmp != null) {
for (Entry<String, HashMap<PlotId, Plot>> entry : PlotSquared.get().plots_tmp for (Entry<String, HashMap<PlotId, Plot>> entry : PlotSquared.get().plots_tmp
@ -143,8 +141,7 @@ import java.util.UUID;
} }
String cmd = String cmd =
"/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)";
Runnable run = new Runnable() { Runnable run = () -> {
@Override public void run() {
PlotSquared.debug("Calculating plots to purge, please wait..."); PlotSquared.debug("Calculating plots to purge, please wait...");
HashSet<Integer> ids = new HashSet<>(); HashSet<Integer> ids = new HashSet<>();
for (Plot plot : toDelete) { for (Plot plot : toDelete) {
@ -159,7 +156,6 @@ import java.util.UUID;
} }
DBFunc.purgeIds(ids); DBFunc.purgeIds(ids);
C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size()); C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size());
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, cmd, run); CmdConfirm.addPending(player, cmd, run);

View File

@ -22,8 +22,7 @@ import java.util.Map.Entry;
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "next": { case "next": {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getBasePlots()); ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getBasePlots());
Collections.sort(plots, new Comparator<Plot>() { plots.sort((p1, p2) -> {
@Override public int compare(Plot p1, Plot p2) {
double v1 = 0; double v1 = 0;
if (!p1.getRatings().isEmpty()) { if (!p1.getRatings().isEmpty()) {
for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) { for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
@ -40,7 +39,6 @@ import java.util.Map.Entry;
return -0; return -0;
} }
return v2 > v1 ? 1 : -1; return v2 > v1 ? 1 : -1;
}
}); });
UUID uuid = player.getUUID(); UUID uuid = player.getUUID();
for (Plot p : plots) { for (Plot p : plots) {
@ -123,7 +121,7 @@ import java.util.Map.Entry;
return true; return true;
} }
}; };
inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8")); inventory.setItem(0, new PlotItemStack("minecraft:brown_wool", 0, "0/8"));
inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/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(2, new PlotItemStack(35, (short) 1, 2, "2/8"));
inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8")); inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8"));
@ -137,11 +135,9 @@ import java.util.Map.Entry;
}; };
if (plot.getSettings().ratings == null) { if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) { if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot); plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run(); run.run();
}
}); });
return true; return true;
} }
@ -167,8 +163,7 @@ import java.util.Map.Entry;
return false; return false;
} }
final UUID uuid = player.getUUID(); final UUID uuid = player.getUUID();
final Runnable run = new Runnable() { final Runnable run = () -> {
@Override public void run() {
if (plot.getRatings().containsKey(uuid)) { if (plot.getRatings().containsKey(uuid)) {
sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
return; return;
@ -178,15 +173,12 @@ import java.util.Map.Entry;
plot.addRating(uuid, result); plot.addRating(uuid, result);
sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
} }
}
}; };
if (plot.getSettings().ratings == null) { if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) { if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot); plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run(); run.run();
}
}); });
return true; return true;
} }

View File

@ -143,14 +143,6 @@ public interface AbstractDB {
*/ */
void setFlags(Plot plot, HashMap<Flag<?>, Object> flags); void setFlags(Plot plot, HashMap<Flag<?>, Object> flags);
/**
* Set cluster flags.
*
* @param cluster PlotCluster Object
* @param flags flags to set (flag[])
*/
void setFlags(PlotCluster cluster, HashMap<Flag<?>, Object> flags);
/** /**
* Rename a cluster to the given name. * Rename a cluster to the given name.
* *

View File

@ -13,6 +13,7 @@ import java.util.*;
* Database Functions * Database Functions
* - These functions do not update the local plot objects and only make changes to the DB * - 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. * The "global" uuid.
@ -298,17 +299,6 @@ public class DBFunc {
DBFunc.dbManager.setFlags(plot, flags); DBFunc.dbManager.setFlags(plot, flags);
} }
public static void setFlags(PlotCluster cluster, HashMap<Flag<?>, Object> flags) {
if (dbManager == null) {
return;
}
DBFunc.dbManager.setFlags(cluster, flags);
}
/**
* @param plot
* @param alias
*/
public static void setAlias(Plot plot, String alias) { public static void setAlias(Plot plot, String alias) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -330,10 +320,6 @@ public class DBFunc {
DBFunc.dbManager.purge(area, plotIds); DBFunc.dbManager.purge(area, plotIds);
} }
/**
* @param plot
* @param position
*/
public static void setPosition(Plot plot, String position) { public static void setPosition(Plot plot, String position) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -341,10 +327,6 @@ public class DBFunc {
DBFunc.dbManager.setPosition(plot, position); DBFunc.dbManager.setPosition(plot, position);
} }
/**
* @param plot
* @param comment
*/
public static void removeComment(Plot plot, PlotComment comment) { public static void removeComment(Plot plot, PlotComment comment) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -359,10 +341,6 @@ public class DBFunc {
DBFunc.dbManager.clearInbox(plot, inbox); DBFunc.dbManager.clearInbox(plot, inbox);
} }
/**
* @param plot
* @param comment
*/
public static void setComment(Plot plot, PlotComment comment) { public static void setComment(Plot plot, PlotComment comment) {
if (plot != null && plot.temp == -1 || dbManager == null) { if (plot != null && plot.temp == -1 || dbManager == null) {
return; return;
@ -370,9 +348,6 @@ public class DBFunc {
DBFunc.dbManager.setComment(plot, comment); DBFunc.dbManager.setComment(plot, comment);
} }
/**
* @param plot
*/
public static void getComments(Plot plot, String inbox, public static void getComments(Plot plot, String inbox,
RunnableVal<List<PlotComment>> whenDone) { RunnableVal<List<PlotComment>> whenDone) {
if (plot != null && plot.temp == -1 || dbManager == null) { if (plot != null && plot.temp == -1 || dbManager == null) {
@ -381,10 +356,6 @@ public class DBFunc {
DBFunc.dbManager.getComments(plot, inbox, whenDone); DBFunc.dbManager.getComments(plot, inbox, whenDone);
} }
/**
* @param plot
* @param uuid
*/
public static void removeTrusted(Plot plot, UUID uuid) { public static void removeTrusted(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -392,10 +363,6 @@ public class DBFunc {
DBFunc.dbManager.removeTrusted(plot, uuid); DBFunc.dbManager.removeTrusted(plot, uuid);
} }
/**
* @param cluster
* @param uuid
*/
public static void removeHelper(PlotCluster cluster, UUID uuid) { public static void removeHelper(PlotCluster cluster, UUID uuid) {
if (dbManager == null) { if (dbManager == null) {
return; return;
@ -403,9 +370,6 @@ public class DBFunc {
DBFunc.dbManager.removeHelper(cluster, uuid); DBFunc.dbManager.removeHelper(cluster, uuid);
} }
/**
* @param cluster
*/
public static void createCluster(PlotCluster cluster) { public static void createCluster(PlotCluster cluster) {
if (dbManager == null) { if (dbManager == null) {
return; return;
@ -413,11 +377,6 @@ public class DBFunc {
DBFunc.dbManager.createCluster(cluster); DBFunc.dbManager.createCluster(cluster);
} }
/**
* @param current
* @param min
* @param max
*/
public static void resizeCluster(PlotCluster current, PlotId min, PlotId max) { public static void resizeCluster(PlotCluster current, PlotId min, PlotId max) {
if (dbManager == null) { if (dbManager == null) {
return; return;
@ -425,10 +384,6 @@ public class DBFunc {
DBFunc.dbManager.resizeCluster(current, min, max); DBFunc.dbManager.resizeCluster(current, min, max);
} }
/**
* @param plot
* @param uuid
*/
public static void removeMember(Plot plot, UUID uuid) { public static void removeMember(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -436,10 +391,6 @@ public class DBFunc {
DBFunc.dbManager.removeMember(plot, uuid); DBFunc.dbManager.removeMember(plot, uuid);
} }
/**
* @param cluster
* @param uuid
*/
public static void removeInvited(PlotCluster cluster, UUID uuid) { public static void removeInvited(PlotCluster cluster, UUID uuid) {
if (dbManager == null) { if (dbManager == null) {
return; return;
@ -447,10 +398,6 @@ public class DBFunc {
DBFunc.dbManager.removeInvited(cluster, uuid); DBFunc.dbManager.removeInvited(cluster, uuid);
} }
/**
* @param plot
* @param uuid
*/
public static void setTrusted(Plot plot, UUID uuid) { public static void setTrusted(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -465,10 +412,6 @@ public class DBFunc {
DBFunc.dbManager.setHelper(cluster, uuid); DBFunc.dbManager.setHelper(cluster, uuid);
} }
/**
* @param plot
* @param uuid
*/
public static void setMember(Plot plot, UUID uuid) { public static void setMember(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -483,10 +426,6 @@ public class DBFunc {
DBFunc.dbManager.setInvited(cluster, uuid); DBFunc.dbManager.setInvited(cluster, uuid);
} }
/**
* @param plot
* @param uuid
*/
public static void removeDenied(Plot plot, UUID uuid) { public static void removeDenied(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;
@ -494,10 +433,6 @@ public class DBFunc {
DBFunc.dbManager.removeDenied(plot, uuid); DBFunc.dbManager.removeDenied(plot, uuid);
} }
/**
* @param plot
* @param uuid
*/
public static void setDenied(Plot plot, UUID uuid) { public static void setDenied(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) { if (plot.temp == -1 || dbManager == null) {
return; return;

View File

@ -11,9 +11,9 @@ import java.sql.Statement;
* @author -_Husky_- * @author -_Husky_-
* @author tips48 * @author tips48
*/ */
public abstract class Database { public interface Database {
public abstract Connection forceConnection() throws SQLException, ClassNotFoundException; Connection forceConnection() throws SQLException, ClassNotFoundException;
/** /**
* Opens a connection with the database. * Opens a connection with the database.
@ -22,7 +22,7 @@ public abstract class Database {
* @throws SQLException if the connection can not be opened * @throws SQLException if the connection can not be opened
* @throws ClassNotFoundException if the driver cannot be found * @throws ClassNotFoundException if the driver cannot be found
*/ */
public abstract Connection openConnection() throws SQLException, ClassNotFoundException; Connection openConnection() throws SQLException, ClassNotFoundException;
/** /**
* Checks if a connection is open with the database. * Checks if a connection is open with the database.
@ -30,14 +30,14 @@ public abstract class Database {
* @return true if the connection is open * @return true if the connection is open
* @throws SQLException if the connection cannot be checked * @throws SQLException if the connection cannot be checked
*/ */
public abstract boolean checkConnection() throws SQLException; boolean checkConnection() throws SQLException;
/** /**
* Gets the connection with the database. * Gets the connection with the database.
* *
* @return Connection with the database, null if none * @return Connection with the database, null if none
*/ */
public abstract Connection getConnection(); Connection getConnection();
/** /**
* Closes the connection with the database. * Closes the connection with the database.
@ -45,7 +45,7 @@ public abstract class Database {
* @return true if successful * @return true if successful
* @throws SQLException if the connection cannot be closed * @throws SQLException if the connection cannot be closed
*/ */
public abstract boolean closeConnection() throws SQLException; boolean closeConnection() throws SQLException;
/** /**
* Executes a SQL Query. * Executes a SQL Query.
@ -56,7 +56,7 @@ public abstract class Database {
* @throws SQLException If the query cannot be executed * @throws SQLException If the query cannot be executed
* @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()} * @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()}
*/ */
public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; ResultSet querySQL(String query) throws SQLException, ClassNotFoundException;
/** /**
* Executes an Update SQL Query. * Executes an Update SQL Query.
@ -68,5 +68,5 @@ public abstract class Database {
* @throws SQLException If the query cannot be executed * @throws SQLException If the query cannot be executed
* @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()} * @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()}
*/ */
public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException; int updateSQL(String query) throws SQLException, ClassNotFoundException;
} }

View File

@ -11,7 +11,7 @@ import java.sql.*;
* @author -_Husky_- * @author -_Husky_-
* @author tips48 * @author tips48
*/ */
public class MySQL extends Database { public class MySQL implements Database {
private final String user; private final String user;
private final String database; private final String database;

View File

@ -9,7 +9,7 @@ import java.sql.*;
/** /**
* Connects to and uses a SQLite database. * Connects to and uses a SQLite database.
*/ */
public class SQLite extends Database { public class SQLite implements Database {
private final String dbLocation; private final String dbLocation;
private Connection connection; private Connection connection;

View File

@ -114,6 +114,7 @@ public class FlagManager {
* @param flag * @param flag
* @return * @return
*/ */
@SuppressWarnings("deprecation")
public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) { public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
if (plot.owner == null) { if (plot.owner == null) {
return null; return null;
@ -141,13 +142,6 @@ public class FlagManager {
return true; return true;
} }
public static <V> boolean addClusterFlag(PlotCluster cluster, Flag<V> 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. * Returns a map of the {@link Flag}s and their values for the specified plot.
* *
@ -217,20 +211,6 @@ public class FlagManager {
return true; 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<Flag<?>, Object> flags) { public static void setPlotFlags(Plot origin, HashMap<Flag<?>, Object> flags) {
for (Plot plot : origin.getConnectedPlots()) { for (Plot plot : origin.getConnectedPlots()) {
if (flags != null && !flags.isEmpty()) { if (flags != null && !flags.isEmpty()) {
@ -248,20 +228,6 @@ public class FlagManager {
} }
} }
public static void setClusterFlags(PlotCluster cluster, Set<Flag> 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. * Get a list of registered {@link Flag} objects based on player permissions.
* *

View File

@ -277,11 +277,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
id = rotate(id); id = rotate(id);
} }
int pair = MathMan.pair(x, z); int pair = MathMan.pair(x, z);
BaseBlock[] existing = this.G_SCH.get(pair); BaseBlock[] existing = this.G_SCH.computeIfAbsent(pair, k -> new BaseBlock[height]);
if (existing == null) {
existing = new BaseBlock[height];
this.G_SCH.put(pair, existing);
}
existing[y] = id; existing[y] = id;
} }
} }

View File

@ -1,5 +1,6 @@
package com.github.intellectualsites.plotsquared.plot.logger; package com.github.intellectualsites.plotsquared.plot.logger;
@FunctionalInterface
public interface ILogger { public interface ILogger {
void log(String message); void log(String message);
} }

View File

@ -4,9 +4,12 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.commands.DebugExec; import com.github.intellectualsites.plotsquared.plot.commands.DebugExec;
import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; import com.github.intellectualsites.plotsquared.plot.commands.MainCommand;
import javax.annotation.Nonnull;
import javax.script.ScriptException; import javax.script.ScriptException;
public abstract class Expression<T> { public abstract class Expression<T> {
@Nonnull
public static <U> Expression<U> constant(final U value) { public static <U> Expression<U> constant(final U value) {
return new Expression<U>() { return new Expression<U>() {
@Override public U evaluate(U arg) { @Override public U evaluate(U arg) {

View File

@ -721,6 +721,9 @@ public abstract class PlotArea {
} else { } else {
start = start.getNextId(1); start = start.getNextId(1);
} }
if (start == null) {
PlotSquared.debug("NPE possible in getNextFreePlot");
}
currentId = new PlotId(center.x + start.x, center.y + start.y); currentId = new PlotId(center.x + start.x, center.y + start.y);
Plot plot = getPlotAbs(currentId); Plot plot = getPlotAbs(currentId);
if (plot != null && plot.canClaim(player)) { if (plot != null && plot.canClaim(player)) {

View File

@ -5,19 +5,25 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
import javax.annotation.Nonnull;
import lombok.Getter;
public class PlotCluster { public class PlotCluster {
public PlotArea area; public PlotArea area;
@Nonnull
@Getter
public PlotSettings settings; public PlotSettings settings;
public UUID owner; public UUID owner;
public HashSet<UUID> helpers = new HashSet<>(); public HashSet<UUID> helpers = new HashSet<>();
public HashSet<UUID> invited = new HashSet<>(); public HashSet<UUID> invited = new HashSet<>();
public int temp; public int temp;
@Nonnull
private PlotId pos1; private PlotId pos1;
@Nonnull
private PlotId pos2; private PlotId pos2;
private RegionWrapper region; private RegionWrapper region;
public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner) { public PlotCluster(PlotArea area, @Nonnull PlotId pos1, @Nonnull PlotId pos2, UUID owner) {
this.area = area; this.area = area;
this.pos1 = pos1; this.pos1 = pos1;
this.pos2 = pos2; this.pos2 = pos2;
@ -27,7 +33,7 @@ public class PlotCluster {
setRegion(); setRegion();
} }
public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner, int temp) { public PlotCluster(PlotArea area, @Nonnull PlotId pos1, PlotId pos2, UUID owner, int temp) {
this.area = area; this.area = area;
this.pos1 = pos1; this.pos1 = pos1;
this.pos2 = pos2; this.pos2 = pos2;
@ -82,6 +88,11 @@ public class PlotCluster {
return this.settings.getAlias(); return this.settings.getAlias();
} }
public String getAlias() {
return this.settings.getAlias();
}
public void setName(String name) { this.settings.setAlias(name);}
/** /**
* Get the area (in plots). * Get the area (in plots).
* *

View File

@ -13,6 +13,7 @@ public class PlotMessage {
try { try {
reset(ChatManager.manager); reset(ChatManager.manager);
} catch (Throwable e) { } catch (Throwable e) {
assert PlotSquared.imp() != null;
PlotSquared.debug( PlotSquared.debug(
PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + PlotSquared PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + PlotSquared
.get().IMP.getServerVersion()); .get().IMP.getServerVersion());

View File

@ -48,25 +48,17 @@ 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)<br> * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's
* - Accepts sponge/bukkit Player (online) * already cached)<br> - Accepts sponge/bukkit Player (online) - Accepts player name (online) -
* - Accepts player name (online) * Accepts UUID - Accepts bukkit OfflinePlayer (offline)
* - Accepts UUID
* - Accepts bukkit OfflinePlayer (offline)
*
* @param player
* @return
*/ */
public static PlotPlayer wrap(Object player) { public static PlotPlayer wrap(Object player) {
return PlotSquared.get().IMP.wrapPlayer(player); return PlotSquared.get().IMP.wrapPlayer(player);
} }
/** /**
* Get the cached PlotPlayer from a username<br> * Get the cached PlotPlayer from a username<br> - This will return null if the player has not
* - This will return null if the player has not finished logging in or is not online * finished logging in or is not online
*
* @param name
* @return
*/ */
public static PlotPlayer get(String name) { public static PlotPlayer get(String name) {
return UUIDHandler.getPlayer(name); return UUIDHandler.getPlayer(name);
@ -74,9 +66,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Set some session only metadata for this player. * Set some session only metadata for this player.
*
* @param key
* @param value
*/ */
public void setMeta(String key, Object value) { public void setMeta(String key, Object value) {
if (value == null) { if (value == null) {
@ -112,11 +101,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
/** /**
* Delete the metadata for a key. * Delete the metadata for a key. - metadata is session only - deleting other plugin's metadata
* - metadata is session only * may cause issues
* - deleting other plugin's metadata may cause issues
*
* @param key
*/ */
public Object deleteMeta(String key) { public Object deleteMeta(String key) {
return this.meta == null ? null : this.meta.remove(key); return this.meta == null ? null : this.meta.remove(key);
@ -127,14 +113,16 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
* *
* @return the name of the player * @return the name of the player
*/ */
@Override public String toString() { @Override
public String toString() {
return getName(); return getName();
} }
/** /**
* Get this player's current plot. * 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() { public Plot getCurrentPlot() {
Plot value = getMeta(PlotPlayer.META_LAST_PLOT); Plot value = getMeta(PlotPlayer.META_LAST_PLOT);
@ -145,10 +133,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
/** /**
* Get the total number of allowed plots * Get the total number of allowed plots Possibly relevant: (To increment the player's allowed
* Possibly relevant: (To increment the player's allowed plots, see the example script on the wiki) * 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() { public int getAllowedPlots() {
return Permissions.hasPermissionRange(this, "plots.plot", Settings.Limit.MAX_PLOTS); return Permissions.hasPermissionRange(this, "plots.plot", Settings.Limit.MAX_PLOTS);
@ -157,7 +146,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Get the total number of allowed clusters * 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() { public int getAllowedClusters() {
return Permissions.hasPermissionRange(this, "plots.cluster", Settings.Limit.MAX_PLOTS); return Permissions.hasPermissionRange(this, "plots.cluster", Settings.Limit.MAX_PLOTS);
@ -191,7 +181,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Get the number of plots this player owns. * 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 #getPlotCount(String);
* @see #getPlots() * @see #getPlots()
*/ */
@ -202,7 +193,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final AtomicInteger count = new AtomicInteger(0); final AtomicInteger count = new AtomicInteger(0);
final UUID uuid = getUUID(); final UUID uuid = getUUID();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() { PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) { @Override
public void run(PlotArea value) {
if (!Settings.Done.COUNTS_TOWARDS_LIMIT) { if (!Settings.Done.COUNTS_TOWARDS_LIMIT) {
for (Plot plot : value.getPlotsAbs(uuid)) { for (Plot plot : value.getPlotsAbs(uuid)) {
if (!plot.hasFlag(Flags.DONE)) { if (!plot.hasFlag(Flags.DONE)) {
@ -224,7 +216,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final AtomicInteger count = new AtomicInteger(0); final AtomicInteger count = new AtomicInteger(0);
final UUID uuid = getUUID(); final UUID uuid = getUUID();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() { PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) { @Override
public void run(PlotArea value) {
for (PlotCluster cluster : value.getClusters()) { for (PlotCluster cluster : value.getClusters()) {
if (cluster.isOwner(getUUID())) { if (cluster.isOwner(getUUID())) {
count.incrementAndGet(); count.incrementAndGet();
@ -239,7 +232,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
* Get the number of plots this player owns in the world. * Get the number of plots this player owns in the world.
* *
* @param world the name of the plotworld to check. * @param world the name of the plotworld to check.
* @return
*/ */
public int getPlotCount(String world) { public int getPlotCount(String world) {
UUID uuid = getUUID(); UUID uuid = getUUID();
@ -284,8 +276,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Return the PlotArea this player is currently in, or null. * Return the PlotArea this player is currently in, or null.
*
* @return
*/ */
public PlotArea getPlotAreaAbs() { public PlotArea getPlotAreaAbs() {
return PlotSquared.get().getPlotAreaAbs(getLocation()); return PlotSquared.get().getPlotAreaAbs(getLocation());
@ -295,7 +285,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
return PlotSquared.get().getApplicablePlotArea(getLocation()); return PlotSquared.get().getApplicablePlotArea(getLocation());
} }
@Override public RequiredType getSuperCaller() { @Override
public RequiredType getSuperCaller() {
return RequiredType.PLAYER; return RequiredType.PLAYER;
} }
@ -318,22 +309,20 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Get this player's full location (including yaw/pitch) * Get this player's full location (including yaw/pitch)
*
* @return
*/ */
public abstract Location getLocationFull(); public abstract Location getLocationFull();
//////////////////////////////////////////////// ////////////////////////////////////////////////
/** /**
* Get this player's UUID. * Get this player's UUID. === !IMPORTANT ===<br> The UUID is dependent on the mode chosen in the
* === !IMPORTANT ===<br> * settings.yml and may not be the same as Bukkit has (especially if using an old version of
* The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has * Bukkit that does not support UUIDs)
* (especially if using an old version of Bukkit that does not support UUIDs)
* *
* @return UUID * @return UUID
*/ */
@Override public abstract UUID getUUID(); @Override
public abstract UUID getUUID();
public boolean canTeleport(Location loc) { public boolean canTeleport(Location loc) {
Location current = getLocationFull(); Location current = getLocationFull();
@ -372,20 +361,16 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public abstract void setCompassTarget(Location location); public abstract void setCompassTarget(Location location);
/** /**
* Set player data that will persist restarts. * Set player data that will persist restarts. - Please note that this is not intended to store
* - Please note that this is not intended to store large values * large values - For session only data use meta
* - For session only data use meta
*
* @param key
*/ */
public void setAttribute(String key) { public void setAttribute(String key) {
setPersistentMeta("attrib_" + key, new byte[] {(byte) 1}); setPersistentMeta("attrib_" + key, new byte[]{(byte) 1});
} }
/** /**
* Retrieves the attribute of this player. * Retrieves the attribute of this player.
* *
* @param key
* @return the attribute will be either true or false * @return the attribute will be either true or false
*/ */
public boolean getAttribute(String key) { public boolean getAttribute(String key) {
@ -397,8 +382,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Remove an attribute from a player. * Remove an attribute from a player.
*
* @param key
*/ */
public void removeAttribute(String key) { public void removeAttribute(String key) {
removePersistentMeta("attrib_" + key); removePersistentMeta("attrib_" + key);
@ -492,7 +475,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
owned.deletePlot(null); owned.deletePlot(null);
PlotSquared.debug(String PlotSquared.debug(String
.format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned", .format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned",
plot.getId(), getName())); owned.getId(), getName()));
} }
} }
String name = getName(); String name = getName();
@ -505,9 +488,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Get the amount of clusters this player owns in the specific world. * Get the amount of clusters this player owns in the specific world.
*
* @param world
* @return
*/ */
public int getPlayerClusterCount(String world) { public int getPlayerClusterCount(String world) {
UUID uuid = getUUID(); UUID uuid = getUUID();
@ -528,7 +508,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public int getPlayerClusterCount() { public int getPlayerClusterCount() {
final AtomicInteger count = new AtomicInteger(); final AtomicInteger count = new AtomicInteger();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() { PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) { @Override
public void run(PlotArea value) {
count.addAndGet(value.getClusters().size()); count.addAndGet(value.getClusters().size());
} }
}); });
@ -555,7 +536,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public void populatePersistentMetaMap() { public void populatePersistentMetaMap() {
if (Settings.Enabled_Components.PERSISTENT_META) { if (Settings.Enabled_Components.PERSISTENT_META) {
DBFunc.getPersistentMeta(getUUID(), new RunnableVal<Map<String, byte[]>>() { DBFunc.getPersistentMeta(getUUID(), new RunnableVal<Map<String, byte[]>>() {
@Override public void run(Map<String, byte[]> value) { @Override
public void run(Map<String, byte[]> value) {
try { try {
PlotPlayer.this.metaMap = value; PlotPlayer.this.metaMap = value;
if (!value.isEmpty()) { if (!value.isEmpty()) {
@ -580,22 +562,19 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final Location loc = final Location loc =
new Location(plot.getWorldName(), x, y, z); new Location(plot.getWorldName(), x, y, z);
if (plot.isLoaded()) { if (plot.isLoaded()) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> {
@Override public void run() {
if (getMeta("teleportOnLogin", true)) { if (getMeta("teleportOnLogin", true)) {
teleport(loc); teleport(loc);
sendMessage(C.TELEPORTED_TO_PLOT.f() sendMessage(C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc) (" + plotX + "," + " (quitLoc) (" + plotX + ","
+ plotZ + ")"); + plotZ + ")");
} }
}
}); });
} else if (!PlotSquared.get() } else if (!PlotSquared.get()
.isMainThread(Thread.currentThread())) { .isMainThread(Thread.currentThread())) {
if (getMeta("teleportOnLogin", true)) { if (getMeta("teleportOnLogin", true)) {
if (plot.teleportPlayer(PlotPlayer.this)) { if (plot.teleportPlayer(PlotPlayer.this)) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> {
@Override public void run() {
if (getMeta("teleportOnLogin", if (getMeta("teleportOnLogin",
true)) { true)) {
teleport(loc); teleport(loc);
@ -605,7 +584,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
+ plotX + "," + plotX + ","
+ plotZ + ")"); + plotZ + ")");
} }
}
}); });
} }
} }
@ -653,8 +631,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* The amount of money this Player has. * The amount of money this Player has.
*
* @return
*/ */
public double getMoney() { public double getMoney() {
return EconHandler.manager == null ? 0 : EconHandler.manager.getMoney(this); return EconHandler.manager == null ? 0 : EconHandler.manager.getMoney(this);
@ -673,6 +649,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
public interface PlotPlayerConverter<BaseObject> { public interface PlotPlayerConverter<BaseObject> {
PlotPlayer convert(BaseObject object); PlotPlayer convert(BaseObject object);
} }
} }

View File

@ -42,7 +42,7 @@ public class PlotSettings {
/** /**
* Flags. * Flags.
* *
* @deprecated Raw access * @deprecated Raw access. Not compatible with PlotClusters.
*/ */
@Deprecated public HashMap<Flag<?>, Object> flags = new HashMap<>(); @Deprecated public HashMap<Flag<?>, Object> flags = new HashMap<>();
/** /**
@ -85,7 +85,7 @@ public class PlotSettings {
return this.ratings; return this.ratings;
} }
public boolean setMerged(int direction, boolean merged) { boolean setMerged(int direction, boolean merged) {
if (this.merged[direction] != merged) { if (this.merged[direction] != merged) {
this.merged[direction] = merged; this.merged[direction] = merged;
return true; return true;
@ -142,6 +142,7 @@ public class PlotSettings {
} }
} }
//todo need a plot method
public Optional<ArrayList<PlotComment>> getComments(String inbox) { public Optional<ArrayList<PlotComment>> getComments(String inbox) {
ArrayList<PlotComment> c = new ArrayList<>(); ArrayList<PlotComment> c = new ArrayList<>();
if (this.comments == null) { if (this.comments == null) {
@ -155,22 +156,26 @@ public class PlotSettings {
return Optional.of(c); return Optional.of(c);
} }
//todo need a plot method
public void setComments(List<PlotComment> comments) { public void setComments(List<PlotComment> comments) {
this.comments = comments; this.comments = comments;
} }
//todo need a plot method
public void removeComment(PlotComment comment) { public void removeComment(PlotComment comment) {
if (this.comments.contains(comment)) { if (this.comments.contains(comment)) {
this.comments.remove(comment); this.comments.remove(comment);
} }
} }
//todo need a plot method
public void removeComments(List<PlotComment> comments) { public void removeComments(List<PlotComment> comments) {
for (PlotComment comment : comments) { for (PlotComment comment : comments) {
removeComment(comment); removeComment(comment);
} }
} }
//todo need a plot method
public void addComment(PlotComment comment) { public void addComment(PlotComment comment) {
if (this.comments == null) { if (this.comments == null) {
this.comments = new ArrayList<>(); this.comments = new ArrayList<>();

View File

@ -4,29 +4,30 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
public class AbstractDelegateOutputStream extends OutputStream { public class AbstractDelegateOutputStream extends OutputStream {
private final OutputStream parent; private final OutputStream parent;
public AbstractDelegateOutputStream(OutputStream os) { public AbstractDelegateOutputStream(OutputStream os) {
this.parent = os; this.parent = os;
} }
@Override public void write(int b) throws IOException { @Override
public void write(int b) throws IOException {
parent.write(b); parent.write(b);
} }
@Override public void write(byte[] b) throws IOException { @Override
public void write(byte[] b) throws IOException {
parent.write(b); parent.write(b);
} }
@Override public void write(byte[] b, int off, int len) throws IOException { @Override
parent.write(b, off, len); public void flush() throws IOException {
}
@Override public void flush() throws IOException {
parent.flush(); parent.flush();
} }
@Override public void close() throws IOException { @Override
public void close() throws IOException {
parent.close(); parent.close();
} }
} }

View File

@ -88,9 +88,9 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
HashSet<PlotArea> globalAreas = new HashSet<>(Arrays.asList(plotAreas)); HashSet<PlotArea> globalAreas = new HashSet<>(Arrays.asList(plotAreas));
localAreas.add(plotArea); localAreas.add(plotArea);
globalAreas.add(plotArea); globalAreas.add(plotArea);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); this.plotAreas = globalAreas.toArray(new PlotArea[0]);
this.plotAreaMap this.plotAreaMap
.put(plotArea.worldname, localAreas.toArray(new PlotArea[localAreas.size()])); .put(plotArea.worldname, localAreas.toArray(new PlotArea[0]));
QuadMap<PlotArea> map = this.plotAreaGrid.get(plotArea.worldname); QuadMap<PlotArea> map = this.plotAreaGrid.get(plotArea.worldname);
if (map == null) { if (map == null) {
map = new QuadMap<PlotArea>(Integer.MAX_VALUE, 0, 0) { map = new QuadMap<PlotArea>(Integer.MAX_VALUE, 0, 0) {
@ -104,15 +104,15 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
} }
@Override public void removePlotArea(PlotArea area) { @Override public void removePlotArea(PlotArea area) {
ArrayList<PlotArea> globalAreas = new ArrayList<PlotArea>(Arrays.asList(plotAreas)); ArrayList<PlotArea> globalAreas = new ArrayList<>(Arrays.asList(plotAreas));
globalAreas.remove(area); globalAreas.remove(area);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); this.plotAreas = globalAreas.toArray(new PlotArea[0]);
if (globalAreas.isEmpty()) { if (globalAreas.isEmpty()) {
this.plotAreaMap.remove(area.worldname); this.plotAreaMap.remove(area.worldname);
this.plotAreaGrid.remove(area.worldname); this.plotAreaGrid.remove(area.worldname);
} else { } else {
this.plotAreaMap this.plotAreaMap
.put(area.worldname, globalAreas.toArray(new PlotArea[globalAreas.size()])); .put(area.worldname, globalAreas.toArray(new PlotArea[0]));
this.plotAreaGrid.get(area.worldname).remove(area); this.plotAreaGrid.get(area.worldname).remove(area);
} }
} }
@ -206,7 +206,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
return noPlotAreas; return noPlotAreas;
} else { } else {
Set<PlotArea> found = areas.get(region); Set<PlotArea> found = areas.get(region);
return found.toArray(new PlotArea[found.size()]); return found.toArray(new PlotArea[0]);
} }
} }
@ -217,14 +217,14 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
Set<String> tmp = new LinkedHashSet<>(); Set<String> tmp = new LinkedHashSet<>();
Collections.addAll(tmp, worlds); Collections.addAll(tmp, worlds);
tmp.add(worldName); tmp.add(worldName);
worlds = tmp.toArray(new String[tmp.size()]); worlds = tmp.toArray(new String[0]);
} }
@Override public void removeWorld(String worldName) { @Override public void removeWorld(String worldName) {
Set<String> tmp = new LinkedHashSet<>(); Set<String> tmp = new LinkedHashSet<>();
Collections.addAll(tmp, worlds); Collections.addAll(tmp, worlds);
tmp.remove(worldName); tmp.remove(worldName);
worlds = tmp.toArray(new String[tmp.size()]); worlds = tmp.toArray(new String[0]);
} }
@Override public String[] getAllWorlds() { @Override public String[] getAllWorlds() {

View File

@ -5,24 +5,24 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
public interface PlotAreaManager { public interface PlotAreaManager {
public PlotArea getApplicablePlotArea(Location location); PlotArea getApplicablePlotArea(Location location);
public PlotArea getPlotArea(Location location); PlotArea getPlotArea(Location location);
public PlotArea getPlotArea(String world, String id); PlotArea getPlotArea(String world, String id);
public PlotArea[] getPlotAreas(String world, RegionWrapper region); PlotArea[] getPlotAreas(String world, RegionWrapper region);
public PlotArea[] getAllPlotAreas(); PlotArea[] getAllPlotAreas();
public String[] getAllWorlds(); String[] getAllWorlds();
public void addPlotArea(PlotArea area); void addPlotArea(PlotArea area);
public void removePlotArea(PlotArea area); void removePlotArea(PlotArea area);
public void addWorld(String worldName); void addWorld(String worldName);
public void removeWorld(String worldName); void removeWorld(String worldName);
} }

View File

@ -7,6 +7,7 @@ import com.github.intellectualsites.plotsquared.plot.object.*;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
import javax.annotation.Nonnull;
public class SinglePlot extends Plot { public class SinglePlot extends Plot {
private HashSet<RegionWrapper> regions; private HashSet<RegionWrapper> regions;
@ -40,6 +41,7 @@ public class SinglePlot extends Plot {
return getId().toCommaSeparatedString(); return getId().toCommaSeparatedString();
} }
@Nonnull
@Override public SinglePlotArea getArea() { @Override public SinglePlotArea getArea() {
return (SinglePlotArea) super.getArea(); return (SinglePlotArea) super.getArea();
} }

View File

@ -35,8 +35,7 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager {
if (chars.length == 1 && chars[0] == '*') { if (chars.length == 1 && chars[0] == '*') {
return true; return true;
} }
for (int i = 0; i < chars.length; i++) { for (char c : chars) {
char c = chars[i];
switch (mode) { switch (mode) {
case 0: case 0:
mode = 1; mode = 1;

View File

@ -30,12 +30,10 @@ public class SinglePlotManager extends PlotManager {
SetupUtils.manager.unload(plot.getWorldName(), false); SetupUtils.manager.unload(plot.getWorldName(), false);
final File worldFolder = final File worldFolder =
new File(PlotSquared.get().IMP.getWorldContainer(), plot.getWorldName()); new File(PlotSquared.get().IMP.getWorldContainer(), plot.getWorldName());
TaskManager.IMP.taskAsync(new Runnable() { TaskManager.IMP.taskAsync(() -> {
@Override public void run() {
MainUtil.deleteDirectory(worldFolder); MainUtil.deleteDirectory(worldFolder);
if (whenDone != null) if (whenDone != null)
whenDone.run(); whenDone.run();
}
}); });
return true; return true;
} }

View File

@ -15,6 +15,6 @@ public abstract class AbstractTitle {
} }
} }
public abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, protected abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay,
int out); int out);
} }

View File

@ -71,8 +71,7 @@ public abstract class ChunkManager {
public static void largeRegionTask(final String world, final RegionWrapper region, public static void largeRegionTask(final String world, final RegionWrapper region,
final RunnableVal<ChunkLoc> task, final Runnable whenDone) { final RunnableVal<ChunkLoc> task, final Runnable whenDone) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
HashSet<ChunkLoc> chunks = new HashSet<>(); HashSet<ChunkLoc> chunks = new HashSet<>();
Set<ChunkLoc> mcrs = manager.getChunkChunks(world); Set<ChunkLoc> mcrs = manager.getChunkChunks(world);
for (ChunkLoc mcr : mcrs) { for (ChunkLoc mcr : mcrs) {
@ -105,7 +104,6 @@ public abstract class ChunkManager {
} }
} }
}, whenDone); }, whenDone);
}
}); });
} }
@ -239,8 +237,7 @@ public abstract class ChunkManager {
public void deleteRegionFiles(final String world, final Collection<ChunkLoc> chunks, public void deleteRegionFiles(final String world, final Collection<ChunkLoc> chunks,
final Runnable whenDone) { final Runnable whenDone) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
for (ChunkLoc loc : chunks) { for (ChunkLoc loc : chunks) {
String directory = String directory =
world + File.separator + "region" + File.separator + "r." + loc.x + "." world + File.separator + "region" + File.separator + "r." + loc.x + "."
@ -252,7 +249,6 @@ public abstract class ChunkManager {
} }
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
}
}); });
} }

View File

@ -19,11 +19,9 @@ public class CmdConfirm {
removePending(player); removePending(player);
if (commandStr != null) if (commandStr != null)
MainUtil.sendMessage(player, C.REQUIRES_CONFIRM, commandStr); MainUtil.sendMessage(player, C.REQUIRES_CONFIRM, commandStr);
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(() -> {
@Override public void run() {
CmdInstance cmd = new CmdInstance(runnable); CmdInstance cmd = new CmdInstance(runnable);
player.setMeta("cmdConfirm", cmd); player.setMeta("cmdConfirm", cmd);
}
}, 1); }, 1);
} }
} }

View File

@ -20,8 +20,7 @@ public class CommentManager {
if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) { if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) {
return; return;
} }
TaskManager.runTaskLaterAsync(new Runnable() { TaskManager.runTaskLaterAsync(() -> {
@Override public void run() {
Collection<CommentInbox> boxes = CommentManager.inboxes.values(); Collection<CommentInbox> boxes = CommentManager.inboxes.values();
final AtomicInteger count = new AtomicInteger(0); final AtomicInteger count = new AtomicInteger(0);
final AtomicInteger size = new AtomicInteger(boxes.size()); final AtomicInteger size = new AtomicInteger(boxes.size());
@ -48,7 +47,6 @@ public class CommentManager {
} }
}); });
} }
}
}, 20); }, 20);
} }

View File

@ -43,8 +43,6 @@ public abstract class EventUtil {
public abstract boolean callFlagRemove(Flag<?> flag, Plot plot, Object value); 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 callMerge(Plot plot, int dir, int max);
public abstract boolean callAutoMerge(Plot plot, List<PlotId> plots); public abstract boolean callAutoMerge(Plot plot, List<PlotId> plots);
@ -78,11 +76,7 @@ public abstract class EventUtil {
} }
final Plot plot = player.getCurrentPlot(); final Plot plot = player.getCurrentPlot();
if (Settings.Teleport.ON_LOGIN && plot != null) { if (Settings.Teleport.ON_LOGIN && plot != null) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> plot.teleportPlayer(player));
@Override public void run() {
plot.teleportPlayer(player);
}
});
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
C.TELEPORTED_TO_ROAD.f() + " (on-login) " + "(" + plot.getId().x + ";" + plot C.TELEPORTED_TO_ROAD.f() + " (on-login) " + "(" + plot.getId().x + ";" + plot
.getId().y + ")"); .getId().y + ")");

View File

@ -411,7 +411,7 @@ public class MainUtil {
ArrayList<ArrayList<Plot>> plotList = new ArrayList<>(size); ArrayList<ArrayList<Plot>> plotList = new ArrayList<>(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
plotList.add(new ArrayList<Plot>()); plotList.add(new ArrayList<>());
} }
for (Plot plot : PlotSquared.get().getPlots()) { for (Plot plot : PlotSquared.get().getPlots()) {
@ -430,7 +430,7 @@ public class MainUtil {
count++; count++;
} }
} }
if (area != null && plot.getArea().equals(area)) { if (plot.getArea().equals(area)) {
count++; count++;
} }
if (alias != null && alias.equals(plot.getAlias())) { if (alias != null && alias.equals(plot.getAlias())) {
@ -622,15 +622,13 @@ public class MainUtil {
if (caption.s().isEmpty()) { if (caption.s().isEmpty()) {
return true; return true;
} }
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
String m = C.format(caption, args); String m = C.format(caption, args);
if (player == null) { if (player == null) {
PlotSquared.log(m); PlotSquared.log(m);
} else { } else {
player.sendMessage(m); player.sendMessage(m);
} }
}
}); });
return true; return true;
} }
@ -780,14 +778,13 @@ public class MainUtil {
info = info.replace("%desc%", "No description set."); info = info.replace("%desc%", "No description set.");
if (info.contains("%rating%")) { if (info.contains("%rating%")) {
final String newInfo = info; final String newInfo = info;
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() {
int max = 10; int max = 10;
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES
.isEmpty()) { .isEmpty()) {
max = 8; max = 8;
} }
String info; String info1;
if (full && Settings.Ratings.CATEGORIES != null if (full && Settings.Ratings.CATEGORIES != null
&& Settings.Ratings.CATEGORIES.size() > 1) { && Settings.Ratings.CATEGORIES.size() > 1) {
double[] ratings = MainUtil.getAverageRatings(plot); double[] ratings = MainUtil.getAverageRatings(plot);
@ -798,13 +795,12 @@ public class MainUtil {
.format("%.1f", ratings[i]); .format("%.1f", ratings[i]);
prefix = ","; prefix = ",";
} }
info = newInfo.replaceAll("%rating%", rating); info1 = newInfo.replaceAll("%rating%", rating);
} else { } else {
info = newInfo.replaceAll("%rating%", info1 = newInfo.replaceAll("%rating%",
String.format("%.1f", plot.getAverageRating()) + '/' + max); String.format("%.1f", plot.getAverageRating()) + '/' + max);
} }
whenDone.run(info); whenDone.run(info1);
}
}); });
return; return;
} }
@ -815,10 +811,9 @@ public class MainUtil {
if (directory.exists()) { if (directory.exists()) {
File[] files = directory.listFiles(); File[] files = directory.listFiles();
if (null != files) { if (null != files) {
for (int i = 0; i < files.length; i++) { for (File file : files) {
File file = files[i];
if (file.isDirectory()) { if (file.isDirectory()) {
deleteDirectory(files[i]); deleteDirectory(file);
} else { } else {
PlotSquared.debug("Deleting file: " + file + " | " + file.delete()); PlotSquared.debug("Deleting file: " + file + " | " + file.delete());
} }

View File

@ -87,7 +87,7 @@ public abstract class SchematicHandler {
} else { } else {
MainUtil.sendMessage(null, "&7 - &a success: " + plot.getId()); MainUtil.sendMessage(null, "&7 - &a success: " + plot.getId());
} }
TaskManager.runTask(() -> THIS.run()); TaskManager.runTask(THIS);
}); });
} }
} }

View File

@ -21,14 +21,16 @@ public class GlobalBlockQueue {
private final AtomicBoolean running; private final AtomicBoolean running;
private QueueProvider provider; 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 last;
private long secondLast; private long secondLast;
private long lastSuccess; private long lastSuccess;
private final RunnableVal2<Long, LocalBlockQueue> SET_TASK = private final RunnableVal2<Long, LocalBlockQueue> SET_TASK =
new RunnableVal2<Long, LocalBlockQueue>() { new RunnableVal2<Long, LocalBlockQueue>() {
@Override public void run(Long free, LocalBlockQueue queue) { @Override
public void run(Long free, LocalBlockQueue queue) {
do { do {
boolean more = queue.next(); boolean more = queue.next();
if (!more) { if (!more) {
@ -81,8 +83,7 @@ public class GlobalBlockQueue {
return false; return false;
} }
running.set(true); running.set(true);
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(() -> {
@Override public void run() {
if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) { if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) {
lastSuccess = System.currentTimeMillis(); lastSuccess = System.currentTimeMillis();
tasks(); tasks();
@ -127,7 +128,6 @@ public class GlobalBlockQueue {
// Enable it again (note that we are still on the main thread) // Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true); SET_TASK.value2.endSet(true);
} }
}
}, 1); }, 1);
return true; return true;
} }
@ -168,7 +168,7 @@ public class GlobalBlockQueue {
public List<LocalBlockQueue> getAllQueues() { public List<LocalBlockQueue> getAllQueues() {
ArrayList<LocalBlockQueue> list = ArrayList<LocalBlockQueue> list =
new ArrayList<LocalBlockQueue>(activeQueues.size() + inactiveQueues.size()); new ArrayList<>(activeQueues.size() + inactiveQueues.size());
list.addAll(inactiveQueues); list.addAll(inactiveQueues);
list.addAll(activeQueues); list.addAll(activeQueues);
return list; return list;
@ -197,7 +197,7 @@ public class GlobalBlockQueue {
if (PARALLEL_THREADS <= 1) { if (PARALLEL_THREADS <= 1) {
SET_TASK.run(); SET_TASK.run();
} else { } else {
ArrayList<Thread> threads = new ArrayList<Thread>(); ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < PARALLEL_THREADS; i++) { for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK)); threads.add(new Thread(SET_TASK));
} }
@ -299,6 +299,6 @@ public class GlobalBlockQueue {
} }
public enum QueueStage { public enum QueueStage {
INACTIVE, ACTIVE, NONE; INACTIVE, ACTIVE, NONE
} }
} }

View File

@ -65,7 +65,6 @@ public class ExpireManager {
/** /**
* Gets the account last joined - first joined (or Long.MAX_VALUE) * Gets the account last joined - first joined (or Long.MAX_VALUE)
* *
* @param uuid
* @return result * @return result
*/ */
public long getAccountAge(UUID uuid) { public long getAccountAge(UUID uuid) {
@ -97,8 +96,7 @@ public class ExpireManager {
Iterator<Plot> iter = plotsToDelete.iterator(); Iterator<Plot> iter = plotsToDelete.iterator();
final Plot current = iter.next(); final Plot current = iter.next();
if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) { if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> {
@Override public void run() {
pp.setMeta("ignoreExpireTask", true); pp.setMeta("ignoreExpireTask", true);
pp.teleport(current.getCenter()); pp.teleport(current.getCenter());
pp.deleteMeta("ignoreExpireTask"); pp.deleteMeta("ignoreExpireTask");
@ -118,7 +116,6 @@ public class ExpireManager {
.suggest("/plot toggle clear-confirmation") .suggest("/plot toggle clear-confirmation")
.tooltip("/plot toggle clear-confirmation"); .tooltip("/plot toggle clear-confirmation");
msg.send(pp); msg.send(pp);
}
}); });
return; return;
} else { } else {
@ -140,7 +137,8 @@ public class ExpireManager {
public boolean runAutomatedTask() { public boolean runAutomatedTask() {
return runTask(new RunnableVal3<Plot, Runnable, Boolean>() { return runTask(new RunnableVal3<Plot, Runnable, Boolean>() {
@Override public void run(Plot plot, Runnable runnable, Boolean confirm) { @Override
public void run(Plot plot, Runnable runnable, Boolean confirm) {
if (confirm) { if (confirm) {
if (plotsToDelete == null) { if (plotsToDelete == null) {
plotsToDelete = new HashSet<>(); plotsToDelete = new HashSet<>();
@ -219,12 +217,7 @@ public class ExpireManager {
public ArrayDeque<ExpiryTask> getTasks(PlotArea area) { public ArrayDeque<ExpiryTask> getTasks(PlotArea area) {
ArrayDeque<ExpiryTask> queue = new ArrayDeque<>(tasks); ArrayDeque<ExpiryTask> queue = new ArrayDeque<>(tasks);
Iterator<ExpiryTask> iter = queue.iterator(); queue.removeIf(expiryTask -> !expiryTask.applies(area));
while (iter.hasNext()) {
if (!iter.next().applies(area)) {
iter.remove();
}
}
return queue; return queue;
} }
@ -254,9 +247,10 @@ public class ExpireManager {
} }
this.running = 2; this.running = 2;
final ConcurrentLinkedDeque<Plot> plots = final ConcurrentLinkedDeque<Plot> plots =
new ConcurrentLinkedDeque<Plot>(PlotSquared.get().getPlots()); new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots());
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() { @Override
public void run() {
final Runnable task = this; final Runnable task = this;
if (ExpireManager.this.running != 2) { if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0; ExpireManager.this.running = 0;
@ -278,51 +272,39 @@ public class ExpireManager {
} }
for (ExpiryTask expiryTask : expired) { for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) { if (!expiryTask.needsAnalysis()) {
expiredTask.run(newPlot, new Runnable() { expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1),
@Override public void run() { expiryTask.requiresConfirmation());
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, expiryTask.requiresConfirmation());
return; return;
} }
} }
final RunnableVal<PlotAnalysis> handleAnalysis = final RunnableVal<PlotAnalysis> handleAnalysis =
new RunnableVal<PlotAnalysis>() { new RunnableVal<PlotAnalysis>() {
@Override public void run(final PlotAnalysis changed) { @Override
public void run(final PlotAnalysis changed) {
passesComplexity(changed, expired, new RunnableVal<Boolean>() { passesComplexity(changed, expired, new RunnableVal<Boolean>() {
@Override public void run(Boolean confirmation) { @Override
expiredTask.run(newPlot, new Runnable() { public void run(Boolean confirmation) {
@Override public void run() { expiredTask.run(newPlot,
TaskManager.IMP.taskLaterAsync(task, 1); () -> TaskManager.IMP.taskLaterAsync(task, 1), confirmation);
} }
}, confirmation); }, () -> {
}
}, new Runnable() {
@Override public void run() {
FlagManager FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList()); .addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20); TaskManager.runTaskLaterAsync(task, 20);
}
}); });
} }
}; };
final Runnable doAnalysis = new Runnable() { final Runnable doAnalysis = () -> HybridUtils.manager
@Override public void run() { .analyzePlot(newPlot, handleAnalysis);
HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
}
};
PlotAnalysis analysis = newPlot.getComplexity(null); PlotAnalysis analysis = newPlot.getComplexity(null);
if (analysis != null) { if (analysis != null) {
passesComplexity(analysis, expired, new RunnableVal<Boolean>() { passesComplexity(analysis, expired, new RunnableVal<Boolean>() {
@Override public void run(Boolean value) { @Override
public void run(Boolean value) {
doAnalysis.run(); doAnalysis.run();
} }
}, new Runnable() { }, () -> TaskManager.IMP.taskLaterAsync(task, 1));
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
});
} else { } else {
doAnalysis.run(); doAnalysis.run();
} }
@ -330,13 +312,11 @@ public class ExpireManager {
} }
if (plots.isEmpty()) { if (plots.isEmpty()) {
ExpireManager.this.running = 3; ExpireManager.this.running = 3;
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(() -> {
@Override public void run() {
if (ExpireManager.this.running == 3) { if (ExpireManager.this.running == 3) {
ExpireManager.this.running = 2; ExpireManager.this.running = 2;
runTask(expiredTask); runTask(expiredTask);
} }
}
}, 86400000); }, 86400000);
} else { } else {
TaskManager.runTaskLaterAsync(task, 20 * 10); TaskManager.runTaskLaterAsync(task, 20 * 10);
@ -352,18 +332,19 @@ public class ExpireManager {
long diff = time - existing; long diff = time - existing;
if (diff > 0) { if (diff > 0) {
Long account_age = this.account_age_cache.get(uuid); 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); this.account_age_cache.put(uuid, account_age + diff);
} }
} }
} }
}
public void storeAccountAge(UUID uuid, long time) { public void storeAccountAge(UUID uuid, long time) {
this.account_age_cache.put(uuid, time); this.account_age_cache.put(uuid, time);
} }
public HashSet<Plot> getPendingExpired() { public HashSet<Plot> getPendingExpired() {
return plotsToDelete == null ? new HashSet<Plot>() : plotsToDelete; return plotsToDelete == null ? new HashSet<>() : plotsToDelete;
} }
public void deleteWithMessage(Plot plot, Runnable whenDone) { public void deleteWithMessage(Plot plot, Runnable whenDone) {

View File

@ -5,7 +5,6 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotFilter; import com.github.intellectualsites.plotsquared.plot.object.PlotFilter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;

View File

@ -118,8 +118,7 @@ public class PlotAnalysis {
final AtomicInteger mi = new AtomicInteger(0); final AtomicInteger mi = new AtomicInteger(0);
Thread ratingAnalysis = new Thread(new Runnable() { Thread ratingAnalysis = new Thread(() -> {
@Override public void run() {
for (; mi.intValue() < plots.size(); mi.incrementAndGet()) { for (; mi.intValue() < plots.size(); mi.incrementAndGet()) {
int i = mi.intValue(); int i = mi.intValue();
Plot plot = plots.get(i); Plot plot = plots.get(i);
@ -128,7 +127,6 @@ public class PlotAnalysis {
* 100); * 100);
PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]); PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]);
} }
}
}); });
ratingAnalysis.start(); ratingAnalysis.start();
@ -424,9 +422,6 @@ public class PlotAnalysis {
/** /**
* A simple array squaring algorithm. * A simple array squaring algorithm.
* - Used for calculating the variance * - Used for calculating the variance
*
* @param array
* @return
*/ */
public static int[] square(int[] array) { public static int[] square(int[] array) {
array = array.clone(); array = array.clone();
@ -439,8 +434,6 @@ public class PlotAnalysis {
/** /**
* An optimized lossy standard deviation algorithm. * An optimized lossy standard deviation algorithm.
* *
* @param ranks
* @return
*/ */
public static int[] getSD(int[]... ranks) { public static int[] getSD(int[]... ranks) {
if (ranks.length == 0) { if (ranks.length == 0) {
@ -468,19 +461,13 @@ public class PlotAnalysis {
* - Input is an array of int with a max size of 102400<br> * - Input is an array of int with a max size of 102400<br>
* - A reduced sample space allows for sorting (and ranking in this case) in linear time * - 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) { public static int[] rank(int[] input) {
return rank(input, 102400); 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) { public static int[] rank(int[] input, int size) {
int[] cache = new int[size]; int[] cache = new int[size];

View File

@ -5,17 +5,17 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import java.util.UUID; import java.util.UUID;
public abstract class UUIDWrapper { public interface UUIDWrapper {
public abstract UUID getUUID(PlotPlayer player); UUID getUUID(PlotPlayer player);
public abstract UUID getUUID(OfflinePlotPlayer player); UUID getUUID(OfflinePlotPlayer player);
public abstract UUID getUUID(String name); UUID getUUID(String name);
public abstract OfflinePlotPlayer getOfflinePlayer(UUID uuid); OfflinePlotPlayer getOfflinePlayer(UUID uuid);
public abstract OfflinePlotPlayer getOfflinePlayer(String name); OfflinePlotPlayer getOfflinePlayer(String name);
public abstract OfflinePlotPlayer[] getOfflinePlayers(); OfflinePlotPlayer[] getOfflinePlayers();
} }

View File

@ -84,9 +84,6 @@ public class AbstractDBTest implements AbstractDB {
@Override public void setFlags(Plot plot, HashMap<Flag<?>, Object> flags) { @Override public void setFlags(Plot plot, HashMap<Flag<?>, Object> flags) {
} }
@Override public void setFlags(PlotCluster cluster, HashMap<Flag<?>, Object> flags) {
}
@Override public void setClusterName(PlotCluster cluster, String name) { @Override public void setClusterName(PlotCluster cluster, String name) {
} }

View File

@ -40,10 +40,6 @@ public class EventUtilTest extends EventUtil {
return true; return true;
} }
@Override public boolean callFlagRemove(Flag<?> flag, Object value, PlotCluster cluster) {
return true;
}
@Override public boolean callMerge(Plot plot, int dir, int max){ @Override public boolean callMerge(Plot plot, int dir, int max){
return false; return false;
} }