This commit is contained in:
dordsor21 2019-02-04 15:18:50 +00:00
parent 14e1296e13
commit cf82bc5efb
77 changed files with 2105 additions and 1528 deletions

View File

@ -81,7 +81,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;
private String pluginName; @Getter 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;
@ -112,9 +112,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);
@ -266,10 +266,6 @@ 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");
@ -537,7 +533,6 @@ 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();

View File

@ -5,10 +5,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import org.bukkit.Bukkit; import org.bukkit.*;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.Statistic.Type; import org.bukkit.Statistic.Type;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.ConfigurationSerializable;
@ -323,6 +320,34 @@ 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

@ -0,0 +1,63 @@
package com.github.intellectualsites.plotsquared.bukkit.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.PlotCluster;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when a flag is removed from a plot.
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot.
*
* @param flag Flag that was removed
* @param cluster PlotCluster from which the flag was removed
*/
public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the cluster involved.
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return this.cluster;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override public HandlerList getHandlers() {
return handlers;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -59,7 +59,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
for (World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false); world.setAutoSave(false);
} }
TaskManager.runTaskRepeat(() -> { TaskManager.runTaskRepeat(new Runnable() {
@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()) {
@ -68,9 +69,10 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
continue; continue;
} }
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world); Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); Object chunkMap =
Method methodIsChunkInUse = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class); Method methodIsChunkInUse = chunkMap.getClass()
.getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks(); Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) { for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse if ((boolean) methodIsChunkInUse
@ -99,6 +101,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}, 1); }, 1);
} }
@ -108,7 +111,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
} }
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()) { if ((Boolean) field.get() == true) {
field.set(false); field.set(false);
if (chunk.isLoaded()) { if (chunk.isLoaded()) {
ignoreUnload = true; ignoreUnload = true;
@ -219,11 +222,13 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
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(() -> { Integer task = TaskManager.runTaskRepeat(new Runnable() {
@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);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true); chunk.unload(true, true);
return; return;
} }
@ -231,7 +236,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
if (tiles.length == 0) { if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex); TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true); chunk.unload(true, true);
return; return;
} }
@ -249,6 +255,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
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

@ -42,7 +42,6 @@ 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;
@ -673,9 +672,8 @@ 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);
@ -703,7 +701,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.addPassenger(player); vehicle.setPassenger(player);
} }
return; return;
} }
@ -785,7 +783,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true; this.tmpTeleport = true;
return; return;
} }
int border = area.getBorder(); Integer 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;
@ -848,7 +846,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true; this.tmpTeleport = true;
return; return;
} }
int border = area.getBorder(); Integer 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;
@ -866,9 +864,8 @@ import java.util.regex.Pattern;
} }
@EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { @EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) {
if (event.isCancelled()) { 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();
@ -1085,9 +1082,8 @@ 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);
} }
} }
@ -1454,11 +1450,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 =
((Directional) event.getBlock().getState().getData()).getFacing(); ((org.bukkit.material.Dispenser) event.getBlock().getState().getData())
.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()) {
@ -1579,9 +1575,8 @@ 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;
} }
@ -1597,13 +1592,11 @@ 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;
} }
@ -2571,10 +2564,10 @@ import java.util.regex.Pattern;
} }
} }
@EventHandler(priority = EventPriority.HIGHEST) @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange = EntityDamageByEntityEvent eventChange = null;
new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), eventChange = new EntityDamageByEntityEvent(event.getCombuster(), 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,7 +10,6 @@ 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,7 +36,8 @@ import java.util.UUID;
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, () -> { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@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(); ) {
@ -78,6 +78,7 @@ import java.util.UUID;
} }
} }
} }
}
}, 0L, 20L); }, 0L, 20L);
} }
@ -104,7 +105,7 @@ import java.util.UUID;
if (event.getEntityType() != EntityType.PLAYER) { if (event.getEntityType() != EntityType.PLAYER) {
return; return;
} }
Entity player = event.getEntity(); Player player = (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

@ -33,8 +33,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 (NoSuchFieldException exception) { } catch (Throwable ignore) {
exception.printStackTrace(); ignore.printStackTrace();
} }
Bukkit.getPluginManager().registerEvents(this, plugin); Bukkit.getPluginManager().registerEvents(this, plugin);
} }

View File

@ -135,11 +135,7 @@ 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();
if (horse instanceof ChestedHorse) { this.horse.chest = horse.isCarryingChest();
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();
@ -179,12 +175,10 @@ 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);
@ -430,7 +424,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity; return entity;
} }
if (this.base.passenger != null) { if (this.base.passenger != null) {
entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); try {
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) {
}
} }
if (this.base.fall != 0) { if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall); entity.setFallDistance(this.base.fall);
@ -515,10 +512,7 @@ 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);
if (horse instanceof ChestedHorse && this.horse.chest) { horse.setCarryingChest(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);
@ -565,15 +559,12 @@ 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

@ -14,7 +14,6 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -242,7 +241,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((short) ((Damageable) item.getItemMeta()).getDamage())); data.put("Damage", new ShortTag(item.getDurability()));
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,7 +187,11 @@ public abstract class TitleManager {
throws IllegalArgumentException, ReflectiveOperationException, SecurityException; throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
private Class<?> getPrimitiveType(Class<?> clazz) { private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.getOrDefault(clazz, clazz); if (CORRESPONDING_TYPES.containsKey(clazz)) {
return CORRESPONDING_TYPES.get(clazz);
} else {
return clazz;
}
} }
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) { 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.getOrDefault(clazz, clazz); return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
} }
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) { private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {

View File

@ -101,6 +101,10 @@ 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

@ -148,7 +148,6 @@ public class BukkitHybridUtils extends HybridUtils {
} }
int y = MainUtil.y_loc[i][j]; int y = MainUtil.y_loc[i][j];
oldBlocks[y][x][z] = airBucket; oldBlocks[y][x][z] = airBucket;
} }
continue; continue;
} }

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[0]); lore = itemLore.toArray(new String[itemLore.size()]);
} }
} }
return new PlotItemStack(id.name(), amount, name, lore); return new PlotItemStack(id.name(), amount, name, lore);

View File

@ -26,8 +26,8 @@ import java.util.Map.Entry;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
/** /**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy * An utility that can be used to send chunks, rather than using bukkit code
* NMS). * to do so (uses heavy NMS).
*/ */
public class SendChunk { public class SendChunk {
@ -118,18 +118,21 @@ public class SendChunk {
} }
} }
for (final Chunk chunk : chunks) { for (final Chunk chunk : chunks) {
TaskManager.runTask(() -> { TaskManager.runTask(new Runnable() {
@Override public void run() {
try { try {
chunk.unload(true, false); chunk.unload(true, false);
} catch (Throwable ignored) { } catch (Throwable ignored) {
String worldName = chunk.getWorld().getName(); String worldName = chunk.getWorld().getName();
PlotSquared.debug( PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk "$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";"
.getZ()); + chunk.getZ());
PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); PlotSquared
.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
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,7 +192,8 @@ 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 (String biomeStr : biomes2) { for (int y = 0; y < biomes2.length; y++) {
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

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

View File

@ -47,7 +47,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} else { } else {
world = worlds.get(0).getName(); world = worlds.get(0).getName();
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@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()) {
@ -80,11 +81,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace(); e.printStackTrace();
} }
} }
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>()); HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
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!");
File playerDataFolder = new File(container, world + File.separator + "playerdata"); File playerDataFolder =
new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter()); String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty(); boolean check = all.isEmpty();
if (dat != null) { if (dat != null) {
@ -126,17 +129,18 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} }
return; return;
} else { } else {
PlotSquared.debug( PlotSquared.debug("Failed to cache: " + all.size()
"Failed to cache: " + all.size() + " uuids - slowly processing all files"); + " uuids - slowly processing all files");
} }
} }
HashSet<String> worlds1 = Sets.newHashSet(world, "world"); HashSet<String> worlds = 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 : worlds1) { for (String worldName : worlds) {
// Getting UUIDs // Getting UUIDs
playerDataFolder = new File(container, worldName + File.separator + "playerdata"); playerDataFolder =
new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter()); String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) { if ((dat != null) && (dat.length != 0)) {
for (String current : dat) { for (String current : dat) {
@ -210,7 +214,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} }
if (getUUIDMap().isEmpty()) { if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper
.getOfflinePlayers()) {
long last = op.getLastPlayed(); long last = op.getLastPlayed();
if (last != 0) { if (last != 0) {
String name = op.getName(); String name = op.getName();
@ -229,14 +234,17 @@ 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(() -> { TaskManager.runTaskAsync(new Runnable() {
@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

@ -16,11 +16,10 @@ import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.UUID; import java.util.UUID;
public class OfflineUUIDWrapper implements UUIDWrapper { public class OfflineUUIDWrapper extends UUIDWrapper {
private final Object[] arg = new Object[0]; private final Object[] arg = new Object[0];
private Method getOnline = null; private Method getOnline = null;
@ -60,15 +59,18 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
return new BukkitOfflinePlayer(op); return new BukkitOfflinePlayer(op);
} }
} }
return Arrays.stream(Bukkit.getOfflinePlayers()) for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
.filter(player -> getUUID(player).equals(uuid)).findFirst() if (getUUID(player).equals(uuid)) {
.map(BukkitOfflinePlayer::new).orElse(null); return new BukkitOfflinePlayer(player);
}
}
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[0]); return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
} }
try { try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -77,13 +79,13 @@ public class OfflineUUIDWrapper implements 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[0]); return p.toArray(new Player[p.size()]);
} }
} 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[0]); return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
} }
} }
@ -93,7 +95,11 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() { @Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new); BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
} }
@Override public OfflinePlotPlayer getOfflinePlayer(String name) { @Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -71,14 +71,17 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) { if (!super.startCaching(whenDone)) {
return false; return false;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try { try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>()); HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
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()) {
while (resultSet.next()) { while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username")); StringWrapper username =
new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid")); UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid); toAdd.put(new StringWrapper(username.value), uuid);
} }
@ -97,8 +100,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
return; return;
} }
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); FileUUIDHandler fileHandler =
fileHandler.startCaching(() -> { new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode // 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) {
@ -108,16 +113,22 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
return; return;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
while (!toFetch.isEmpty()) { while (!toFetch.isEmpty()) {
try { try {
for (int i = 0; i < Math.min(500, toFetch.size()); i++) { for (int i = 0;
i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop(); UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL( HttpURLConnection connection =
SQLUUIDHandler.this.PROFILE_URL + uuid.toString() (HttpURLConnection) new URL(
.replace("-", "")).openConnection(); SQLUUIDHandler.this.PROFILE_URL + uuid
try (InputStream con = connection.getInputStream()) { .toString().replace("-", ""))
InputStreamReader reader = new InputStreamReader(con); .openConnection();
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
JSONObject response = JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser (JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader); .parse(reader);
@ -143,11 +154,14 @@ 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;
} }
@ -158,7 +172,8 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (ifFetch == null) { if (ifFetch == null) {
return; return;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@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();
@ -176,7 +191,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 name1 = (String) jsonProfile.get("name"); String name = (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));
@ -184,6 +199,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
}
}); });
} }
@ -199,16 +215,19 @@ 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(() -> { TaskManager.runTaskAsync(new Runnable() {
try (PreparedStatement statement = getConnection() @Override public void run() {
.prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setString(2, name.toString()); statement.setString(2, name.toString());
statement.execute(); statement.execute();
PlotSquared.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); PlotSquared
.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
return true; return true;
} }
@ -220,17 +239,19 @@ 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(() -> { TaskManager.runTaskAsync(new Runnable() {
@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);
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.execute(); statement.execute();
PlotSquared PlotSquared.debug(
.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }

View File

@ -1,6 +1,5 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import javax.annotation.Nonnull;
import java.util.Map; import java.util.Map;
/** /**
@ -21,7 +20,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(@Nonnull String path, Object value); @Override void addDefault(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
*/ */
char pathSeparator() { public 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
*/ */
boolean copyDefaults() { public boolean copyDefaults() {
return copyDefaults; return copyDefaults;
} }

View File

@ -1,6 +1,5 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import javax.annotation.Nonnull;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -53,7 +52,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(@Nonnull String path); boolean contains(String path);
/** /**
* Checks if this {@link ConfigurationSection} has a value set for the * Checks if this {@link ConfigurationSection} has a value set for the
@ -67,7 +66,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(@Nonnull String path); boolean isSet(String path);
/** /**
* Gets the path of this {@link ConfigurationSection} from its root {@link * Gets the path of this {@link ConfigurationSection} from its root {@link
@ -152,7 +151,7 @@ public interface ConfigurationSection {
* @param defaultValue The default value to return if the path is not found. * @param defaultValue The default value to return if the path is not found.
* @return Requested Object. * @return Requested Object.
*/ */
Object getOrDefault(@Nonnull String path, Object defaultValue); Object get(String path, Object defaultValue);
/** /**
* Sets the specified path to the given value. * Sets the specified path to the given value.
@ -645,5 +644,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(@Nonnull String path, Object value); void addDefault(String path, Object value);
} }

View File

@ -1,6 +1,5 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import javax.annotation.Nonnull;
import java.util.Map; import java.util.Map;
/** /**
@ -29,7 +28,7 @@ public class MemoryConfiguration extends MemorySection implements Configuration
this.defaults = defaults; this.defaults = defaults;
} }
@Override public void addDefault(@Nonnull String path, Object value) { @Override public void addDefault(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,5 @@
package com.github.intellectualsites.plotsquared.configuration; package com.github.intellectualsites.plotsquared.configuration;
import javax.annotation.Nonnull;
import java.util.*; import java.util.*;
/** /**
@ -15,12 +14,14 @@ public class MemorySection implements ConfigurationSection {
private final String fullPath; private final String fullPath;
/** /**
* Creates an empty MemorySection for use as a root {@link Configuration} section. * Creates an empty MemorySection for use as a root {@link Configuration}
* section.
* *
* <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 Configuration} root. * @throws IllegalStateException Thrown if this is not a {@link
* Configuration} root.
*/ */
protected MemorySection() { protected MemorySection() {
if (!(this instanceof Configuration)) { if (!(this instanceof Configuration)) {
@ -38,9 +39,10 @@ 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 {@link Configuration}. * @param path Path that you may access this section from via the root
* @throws IllegalArgumentException Thrown is parent or path is null, or if parent contains no * {@link Configuration}.
* root Configuration. * @throws IllegalArgumentException Thrown is parent or path is null, or
* if parent contains no root Configuration.
*/ */
protected MemorySection(ConfigurationSection parent, String path) { protected MemorySection(ConfigurationSection parent, String path) {
this.path = path; this.path = path;
@ -109,8 +111,8 @@ public class MemorySection implements ConfigurationSection {
} }
/** /**
* Creates a full path to the given {@link ConfigurationSection} from its root {@link * Creates a full path to the given {@link ConfigurationSection} from its
* Configuration}. * root {@link 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}.
@ -124,8 +126,8 @@ public class MemorySection implements ConfigurationSection {
} }
/** /**
* Creates a relative path to the given {@link ConfigurationSection} from the given relative * Creates a relative path to the given {@link ConfigurationSection} from
* section. * the given relative 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}.
@ -198,11 +200,11 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
@Override public boolean contains(@Nonnull String path) { @Override public boolean contains(String path) {
return get(path) != null; return get(path) != null;
} }
@Override public boolean isSet(@Nonnull String path) { @Override public boolean isSet(String path) {
Configuration root = getRoot(); Configuration root = getRoot();
if (root == null) { if (root == null) {
return false; return false;
@ -210,7 +212,7 @@ public class MemorySection implements ConfigurationSection {
if (root.options().copyDefaults()) { if (root.options().copyDefaults()) {
return contains(path); return contains(path);
} }
return getOrDefault(path, null) != null; return get(path, null) != null;
} }
@Override public String getCurrentPath() { @Override public String getCurrentPath() {
@ -229,7 +231,7 @@ public class MemorySection implements ConfigurationSection {
return this.parent; return this.parent;
} }
@Override public void addDefault(@Nonnull String path, Object value) { @Override public void addDefault(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");
@ -289,10 +291,14 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public Object get(String path) { @Override public Object get(String path) {
return getOrDefault(path, getDefault(path)); return get(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;
} }
@ -324,7 +330,7 @@ public class MemorySection implements ConfigurationSection {
return result; return result;
} }
} }
return section.getOrDefault(key, defaultValue); return section.get(key, defaultValue);
} }
@Override public ConfigurationSection createSection(String path) { @Override public ConfigurationSection createSection(String path) {
@ -379,7 +385,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public String getString(String path, String def) { @Override public String getString(String path, String def) {
Object val = getOrDefault(path, def); Object val = get(path, def);
if (val != null) { if (val != null) {
return val.toString(); return val.toString();
} else { } else {
@ -398,7 +404,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public int getInt(String path, int def) { @Override public int getInt(String path, int def) {
Object val = getOrDefault(path, def); Object val = get(path, def);
return toInt(val, def); return toInt(val, def);
} }
@ -417,7 +423,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public boolean getBoolean(String path, boolean defaultValue) { @Override public boolean getBoolean(String path, boolean defaultValue) {
Object val = getOrDefault(path, defaultValue); Object val = get(path, defaultValue);
if (val instanceof Boolean) { if (val instanceof Boolean) {
return (Boolean) val; return (Boolean) val;
} else { } else {
@ -436,7 +442,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public double getDouble(String path, double defaultValue) { @Override public double getDouble(String path, double defaultValue) {
Object val = getOrDefault(path, defaultValue); Object val = get(path, defaultValue);
return toDouble(val, defaultValue); return toDouble(val, defaultValue);
} }
@ -451,7 +457,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public long getLong(String path, long def) { @Override public long getLong(String path, long def) {
Object val = getOrDefault(path, def); Object val = get(path, def);
return toLong(val, def); return toLong(val, def);
} }
@ -467,7 +473,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public List<?> getList(String path, List<?> def) { @Override public List<?> getList(String path, List<?> def) {
Object val = getOrDefault(path, def); Object val = get(path, def);
return (List<?>) ((val instanceof List) ? val : def); return (List<?>) ((val instanceof List) ? val : def);
} }
@ -688,12 +694,12 @@ public class MemorySection implements ConfigurationSection {
} }
@Override public ConfigurationSection getConfigurationSection(String path) { @Override public ConfigurationSection getConfigurationSection(String path) {
Object val = getOrDefault(path, null); Object val = get(path, null);
if (val != null) { if (val != null) {
return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
} }
val = getOrDefault(path, getDefault(path)); val = get(path, getDefault(path));
return (val instanceof ConfigurationSection) ? createSection(path) : null; return (val instanceof ConfigurationSection) ? createSection(path) : null;
} }

View File

@ -4,7 +4,6 @@ import com.github.intellectualsites.plotsquared.configuration.Configuration;
import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException; import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException;
import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration; import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration;
import javax.annotation.Nonnull;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -83,7 +82,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(@Nonnull File file) throws IOException, InvalidConfigurationException { public void load(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 = yaml.load(contents); input = (Map<?, ?>) 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
*/ */
int indent() { public 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;
class YamlConstructor extends SafeConstructor { public class YamlConstructor extends SafeConstructor {
YamlConstructor() { YamlConstructor() {
yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); yamlConstructors.put(Tag.MAP, new ConstructCustomObject());

View File

@ -76,9 +76,7 @@ public interface IPlotMain extends ILogger {
* *
* @return * @return
*/ */
default String getPluginName() { 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 Bukkit, Sponge, Spigot, Cauldron
} }

File diff suppressed because one or more lines are too long

View File

@ -104,7 +104,8 @@ 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 = () -> { Runnable run = new Runnable() {
@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);
@ -133,6 +134,7 @@ 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,
@ -226,7 +228,8 @@ 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 = () -> { Runnable run = new Runnable() {
@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);
@ -251,6 +254,7 @@ 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,
@ -418,7 +422,11 @@ 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);
} }
}, () -> player.sendMessage("Regen complete")); }, new Runnable() {
@Override public void run() {
player.sendMessage("Regen complete");
}
});
return true; return true;
} }
case "goto": case "goto":

View File

@ -82,14 +82,22 @@ 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, () -> TaskManager.IMP.sync(new RunnableVal<Object>() { DBFunc.createPlotSafe(plot, new Runnable() {
@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

@ -301,7 +301,6 @@ 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,7 +346,6 @@ 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) {
@ -406,7 +404,6 @@ 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) {
@ -442,6 +439,7 @@ 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();
} }
} }
@ -463,7 +461,6 @@ 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) {
@ -536,7 +533,6 @@ 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) {
@ -584,7 +580,6 @@ 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,7 +65,6 @@ 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);
@ -127,12 +126,14 @@ 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, () -> { result.set(origin.move(possible, new Runnable() {
@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

@ -30,19 +30,26 @@ import java.util.Map.Entry;
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(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try { try {
ArrayList<Plot> ps = new ArrayList<>(plots); ArrayList<Plot> ps = new ArrayList<>();
for (Plot p : plots) {
ps.add(p);
}
MainUtil.sendMessage(player, "&6Starting..."); MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, () -> { manager.createPlotsAndData(ps, new Runnable() {
@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 MainUtil.sendMessage(player,
.sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); "Failed to insert plot objects, see stacktrace for info");
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }
@ -123,13 +130,20 @@ import java.util.Map.Entry;
plots.add(plot); plots.add(plot);
} }
} else { } else {
HashMap<PlotId, Plot> plotmap = PlotSquared.get().plots_tmp HashMap<PlotId, Plot> plotmap =
.computeIfAbsent(areaname, k -> new HashMap<>()); PlotSquared.get().plots_tmp.get(areaname);
if (plotmap == null) {
plotmap = new HashMap<>();
PlotSquared.get().plots_tmp.put(areaname, plotmap);
}
plotmap.putAll(entry.getValue()); plotmap.putAll(entry.getValue());
} }
} }
DBFunc.createPlotsAndData(plots, DBFunc.createPlotsAndData(plots, new Runnable() {
() -> MainUtil.sendMessage(player, "&6Database conversion finished!")); @Override public void run() {
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,7 +57,9 @@ 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,8 +165,9 @@ 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());
comments if (comments.isPresent()) {
.ifPresent(plotComments -> plot.getSettings().removeComments(plotComments)); plot.getSettings().removeComments(comments.get());
}
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.getOrDefault("merge", Expression.constant(0d)); plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null;
final int size = plot.getConnectedPlots().size(); final int size = plot.getConnectedPlots().size();
final double price = priceExr.evaluate((double) size); final double price = priceExr == null ? 0d : priceExr.evaluate((double) size);
if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d 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,7 +108,9 @@ import java.util.UUID;
if (unknown && UUIDHandler.getName(plot.owner) != null) { if (unknown && UUIDHandler.getName(plot.owner) != null) {
continue; continue;
} }
toDelete.addAll(plot.getConnectedPlots()); for (Plot current : 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
@ -141,7 +143,8 @@ 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 = () -> { Runnable run = new Runnable() {
@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) {
@ -156,6 +159,7 @@ 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

@ -10,10 +10,8 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.*;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot", @CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot",
usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO, usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO,
@ -24,7 +22,8 @@ import java.util.UUID;
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());
plots.sort((p1, p2) -> { Collections.sort(plots, new Comparator<Plot>() {
@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()) {
@ -41,6 +40,7 @@ import java.util.UUID;
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 +123,7 @@ import java.util.UUID;
return true; return true;
} }
}; };
inventory.setItem(0, new PlotItemStack("minecraft:brown_wool", 0, "0/8")); inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8"));
inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8")); inventory.setItem(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,9 +137,11 @@ import java.util.UUID;
}; };
if (plot.getSettings().ratings == null) { if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) { if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot); plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run(); run.run();
}
}); });
return true; return true;
} }
@ -165,7 +167,8 @@ import java.util.UUID;
return false; return false;
} }
final UUID uuid = player.getUUID(); final UUID uuid = player.getUUID();
final Runnable run = () -> { final Runnable run = new Runnable() {
@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;
@ -175,12 +178,15 @@ import java.util.UUID;
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(() -> { TaskManager.runTaskAsync(new Runnable() {
@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,6 +143,14 @@ 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,7 +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,6 +298,17 @@ import java.util.*;
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;
@ -319,6 +330,10 @@ import java.util.*;
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;
@ -326,6 +341,10 @@ import java.util.*;
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;
@ -340,6 +359,10 @@ import java.util.*;
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;
@ -347,6 +370,9 @@ import java.util.*;
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) {
@ -355,6 +381,10 @@ import java.util.*;
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;
@ -362,6 +392,10 @@ import java.util.*;
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;
@ -369,6 +403,9 @@ import java.util.*;
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;
@ -376,6 +413,11 @@ import java.util.*;
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;
@ -383,6 +425,10 @@ import java.util.*;
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;
@ -390,6 +436,10 @@ import java.util.*;
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;
@ -397,6 +447,10 @@ import java.util.*;
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;
@ -411,6 +465,10 @@ import java.util.*;
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;
@ -425,6 +483,10 @@ import java.util.*;
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;
@ -432,6 +494,10 @@ import java.util.*;
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 interface Database { public abstract class Database {
Connection forceConnection() throws SQLException, ClassNotFoundException; public abstract Connection forceConnection() throws SQLException, ClassNotFoundException;
/** /**
* Opens a connection with the database. * Opens a connection with the database.
@ -22,7 +22,7 @@ public interface 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
*/ */
Connection openConnection() throws SQLException, ClassNotFoundException; public abstract 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 interface 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
*/ */
boolean checkConnection() throws SQLException; public abstract 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
*/ */
Connection getConnection(); public abstract Connection getConnection();
/** /**
* Closes the connection with the database. * Closes the connection with the database.
@ -45,7 +45,7 @@ public interface 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
*/ */
boolean closeConnection() throws SQLException; public abstract boolean closeConnection() throws SQLException;
/** /**
* Executes a SQL Query. * Executes a SQL Query.
@ -56,7 +56,7 @@ public interface 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()}
*/ */
ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException;
/** /**
* Executes an Update SQL Query. * Executes an Update SQL Query.
@ -68,5 +68,5 @@ public interface 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()}
*/ */
int updateSQL(String query) throws SQLException, ClassNotFoundException; public abstract 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 implements Database { public class MySQL extends Database {
private final String user; private final String user;
private final String database; private final String database;

View File

@ -14,7 +14,6 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import javax.annotation.Nonnull;
import java.sql.*; import java.sql.*;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -49,7 +48,13 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
public volatile Queue<Runnable> notifyTasks; public volatile Queue<Runnable> notifyTasks;
/** /**
* plot plot_denied plot_helpers plot_trusted plot_comments plot_settings plot_rating * plot
* plot_denied
* plot_helpers
* plot_trusted
* plot_comments
* plot_settings
* plot_rating
*/ */
public volatile ConcurrentHashMap<Plot, Queue<UniqueStatement>> plotTasks; public volatile ConcurrentHashMap<Plot, Queue<UniqueStatement>> plotTasks;
/** /**
@ -57,7 +62,10 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
public volatile ConcurrentHashMap<UUID, Queue<UniqueStatement>> playerTasks; public volatile ConcurrentHashMap<UUID, Queue<UniqueStatement>> playerTasks;
/** /**
* cluster cluster_helpers cluster_invited cluster_settings * cluster
* cluster_helpers
* cluster_invited
* cluster_settings
*/ */
public volatile ConcurrentHashMap<PlotCluster, Queue<UniqueStatement>> clusterTasks; public volatile ConcurrentHashMap<PlotCluster, Queue<UniqueStatement>> clusterTasks;
// Private // Private
@ -67,7 +75,10 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Constructor * Constructor
* *
* @param database
* @param p prefix * @param p prefix
* @throws SQLException
* @throws ClassNotFoundException
*/ */
public SQLManager(final Database database, String p, boolean debug) public SQLManager(final Database database, String p, boolean debug)
throws SQLException, ClassNotFoundException { throws SQLException, ClassNotFoundException {
@ -110,7 +121,8 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
long last = System.currentTimeMillis(); long last = System.currentTimeMillis();
while (true) { while (true) {
if (SQLManager.this.closed) { if (SQLManager.this.closed) {
@ -146,6 +158,7 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
} }
}
}); });
} }
@ -183,9 +196,15 @@ import java.util.concurrent.atomic.AtomicInteger;
return this.notifyTasks; return this.notifyTasks;
} }
public synchronized void addPlotTask(@Nonnull Plot plot, UniqueStatement task) { public synchronized void addPlotTask(Plot plot, UniqueStatement task) {
Queue<UniqueStatement> tasks = if (plot == null) {
this.plotTasks.computeIfAbsent(plot, plot1 -> new ConcurrentLinkedQueue<>()); plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE));
}
Queue<UniqueStatement> tasks = this.plotTasks.get(plot);
if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
this.plotTasks.put(plot, tasks);
}
if (task == null) { if (task == null) {
task = new UniqueStatement(String.valueOf(plot.hashCode())) { task = new UniqueStatement(String.valueOf(plot.hashCode())) {
@ -211,8 +230,11 @@ import java.util.concurrent.atomic.AtomicInteger;
if (uuid == null) { if (uuid == null) {
return; return;
} }
Queue<UniqueStatement> tasks = Queue<UniqueStatement> tasks = this.playerTasks.get(uuid);
this.playerTasks.computeIfAbsent(uuid, uuid1 -> new ConcurrentLinkedQueue<>()); if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
this.playerTasks.put(uuid, tasks);
}
if (task == null) { if (task == null) {
task = new UniqueStatement(String.valueOf(uuid.hashCode())) { task = new UniqueStatement(String.valueOf(uuid.hashCode())) {
@ -235,8 +257,11 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
public synchronized void addClusterTask(PlotCluster cluster, UniqueStatement task) { public synchronized void addClusterTask(PlotCluster cluster, UniqueStatement task) {
Queue<UniqueStatement> tasks = this.clusterTasks Queue<UniqueStatement> tasks = this.clusterTasks.get(cluster);
.computeIfAbsent(cluster, plotCluster -> new ConcurrentLinkedQueue<>()); if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
this.clusterTasks.put(cluster, tasks);
}
if (task == null) { if (task == null) {
task = new UniqueStatement(String.valueOf(cluster.hashCode())) { task = new UniqueStatement(String.valueOf(cluster.hashCode())) {
@ -490,10 +515,12 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
@Override public void createPlotsAndData(final List<Plot> myList, final Runnable whenDone) { @Override public void createPlotsAndData(final List<Plot> myList, final Runnable whenDone) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
try { try {
// Create the plots // Create the plots
createPlots(myList, () -> { createPlots(myList, new Runnable() {
@Override public void run() {
try { try {
// Creating datastructures // Creating datastructures
HashMap<PlotId, Plot> plotMap = new HashMap<>(); HashMap<PlotId, Plot> plotMap = new HashMap<>();
@ -529,18 +556,32 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
} }
createSettings(settings, () -> createTiers(helpers, "helpers", createSettings(settings, new Runnable() {
() -> createTiers(trusted, "trusted", @Override public void run() {
() -> createTiers(denied, "denied", () -> { createTiers(helpers, "helpers", new Runnable() {
@Override public void run() {
createTiers(trusted, "trusted", new Runnable() {
@Override public void run() {
createTiers(denied, "denied",
new Runnable() {
@Override public void run() {
try { try {
SQLManager.this.connection.commit(); SQLManager.this.connection
.commit();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }
})))); }
});
}
});
}
});
}
});
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots"); PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
@ -550,6 +591,7 @@ import java.util.concurrent.atomic.AtomicInteger;
e1.printStackTrace(); e1.printStackTrace();
} }
} }
}
}); });
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -560,6 +602,7 @@ import java.util.concurrent.atomic.AtomicInteger;
e1.printStackTrace(); e1.printStackTrace();
} }
} }
}
}); });
} }
@ -886,7 +929,11 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(1, pair.id); stmt.setInt(1, pair.id);
} }
}; };
addGlobalTask(() -> setBulk(myList, mod, whenDone)); addGlobalTask(new Runnable() {
@Override public void run() {
setBulk(myList, mod, whenDone);
}
});
} }
public void createEmptySettings(final ArrayList<Integer> myList, final Runnable whenDone) { public void createEmptySettings(final ArrayList<Integer> myList, final Runnable whenDone) {
@ -930,7 +977,11 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(1, id); stmt.setInt(1, id);
} }
}; };
addGlobalTask(() -> setBulk(myList, mod, whenDone)); addGlobalTask(new Runnable() {
@Override public void run() {
setBulk(myList, mod, whenDone);
}
});
} }
public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) { public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) {
@ -975,17 +1026,15 @@ import java.util.concurrent.atomic.AtomicInteger;
+ "plot_settings`(`plot_plot_id`) VALUES(?)"); + "plot_settings`(`plot_plot_id`) VALUES(?)");
} }
}); });
if (success != null) { if (success != null)
addNotifyTask(success); addNotifyTask(success);
}
return; return;
} }
} }
} }
if (failure != null) { if (failure != null)
failure.run(); failure.run();
} }
}
}); });
} }
@ -1046,6 +1095,8 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Create tables. * Create tables.
*
* @throws SQLException
*/ */
@Override public void createTables() throws SQLException { @Override public void createTables() throws SQLException {
String[] tables = String[] tables =
@ -1294,6 +1345,8 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Delete a plot. * Delete a plot.
*
* @param plot
*/ */
@Override public void delete(final Plot plot) { @Override public void delete(final Plot plot) {
PlotSquared.debug( PlotSquared.debug(
@ -1319,6 +1372,9 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Create plot settings * Create plot settings
*
* @param id
* @param plot
*/ */
@Override public void createPlotSettings(final int id, Plot plot) { @Override public void createPlotSettings(final int id, Plot plot) {
PlotSquared.debug( PlotSquared.debug(
@ -1554,12 +1610,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ConfigurationSection areaSection = ConfigurationSection areaSection =
worldSection.getConfigurationSection(worldKey + ".areas"); worldSection.getConfigurationSection(worldKey + ".areas");
if (areaSection != null) { if (areaSection != null) {
areaSection.getKeys(false).forEach(s -> { for (String areaKey : areaSection.getKeys(false)) {
String[] split = s.split("(?<![;])-"); String[] split = areaKey.split("(?<![;])-");
if (split.length == 3) { if (split.length == 3) {
areas.add(worldKey + ';' + split[0]); areas.add(worldKey + ';' + split[0]);
} }
}); }
} }
} }
} }
@ -1572,7 +1628,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
try (Statement statement = this.connection.createStatement()) { try (Statement statement = this.connection.createStatement()) {
int id; int id;
String owner; String o;
UUID user; UUID user;
try (ResultSet resultSet = statement.executeQuery( try (ResultSet resultSet = statement.executeQuery(
"SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp` FROM `" "SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp` FROM `"
@ -1596,21 +1652,23 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
} }
owner = resultSet.getString("owner"); o = resultSet.getString("owner");
user = uuids.computeIfAbsent(owner, s -> { user = uuids.get(o);
if (user == null) {
try { try {
return UUID.fromString(s); user = UUID.fromString(o);
} catch (IllegalArgumentException ignored) { } catch (IllegalArgumentException e) {
if (Settings.UUID.FORCE_LOWERCASE) { if (Settings.UUID.FORCE_LOWERCASE) {
return UUID.nameUUIDFromBytes( user = UUID.nameUUIDFromBytes(
("OfflinePlayer:" + s.toLowerCase()) ("OfflinePlayer:" + o.toLowerCase())
.getBytes(Charsets.UTF_8)); .getBytes(Charsets.UTF_8));
} else { } else {
return UUID.nameUUIDFromBytes( user = UUID.nameUUIDFromBytes(
("OfflinePlayer:" + s).getBytes(Charsets.UTF_8)); ("OfflinePlayer:" + o).getBytes(Charsets.UTF_8));
} }
} }
}); uuids.put(o, user);
}
long time; long time;
try { try {
Timestamp timestamp = resultSet.getTimestamp("timestamp"); Timestamp timestamp = resultSet.getTimestamp("timestamp");
@ -1627,12 +1685,12 @@ import java.util.concurrent.atomic.AtomicInteger;
time = System.currentTimeMillis() + id; time = System.currentTimeMillis() + id;
} }
} }
Plot plot = new Plot(plot_id, user, new HashSet<>(), new HashSet<>(), Plot p = new Plot(plot_id, user, new HashSet<UUID>(), new HashSet<UUID>(),
new HashSet<>(), "", null, null, null, new HashSet<UUID>(), "", null, null, null,
new boolean[] {false, false, false, false}, time, id); new boolean[] {false, false, false, false}, time, id);
HashMap<PlotId, Plot> map = newPlots.get(areaid); HashMap<PlotId, Plot> map = newPlots.get(areaid);
if (map != null) { if (map != null) {
Plot last = map.put(plot.getId(), plot); Plot last = map.put(p.getId(), p);
if (last != null) { if (last != null) {
if (Settings.Enabled_Components.DATABASE_PURGER) { if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(last.temp); toDelete.add(last.temp);
@ -1645,9 +1703,9 @@ import java.util.concurrent.atomic.AtomicInteger;
} else { } else {
map = new HashMap<>(); map = new HashMap<>();
newPlots.put(areaid, map); newPlots.put(areaid, map);
map.put(plot.getId(), plot); map.put(p.getId(), p);
} }
plots.put(id, plot); plots.put(id, p);
} }
deleteRows(toDelete, this.prefix + "plot", "id"); deleteRows(toDelete, this.prefix + "plot", "id");
} }
@ -1658,8 +1716,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>(); ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) { while (r.next()) {
id = r.getInt("plot_plot_id"); id = r.getInt("plot_plot_id");
owner = r.getString("player"); o = r.getString("player");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id); Plot plot = plots.get(id);
if (plot != null) { if (plot != null) {
plot.getSettings().getRatings().put(user, r.getInt("rating")); plot.getSettings().getRatings().put(user, r.getInt("rating"));
@ -1683,8 +1745,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>(); ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) { while (r.next()) {
id = r.getInt("plot_plot_id"); id = r.getInt("plot_plot_id");
owner = r.getString("user_uuid"); o = r.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id); Plot plot = plots.get(id);
if (plot != null) { if (plot != null) {
plot.getTrusted().add(user); plot.getTrusted().add(user);
@ -1707,8 +1773,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>(); ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) { while (r.next()) {
id = r.getInt("plot_plot_id"); id = r.getInt("plot_plot_id");
owner = r.getString("user_uuid"); o = r.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id); Plot plot = plots.get(id);
if (plot != null) { if (plot != null) {
plot.getMembers().add(user); plot.getMembers().add(user);
@ -1731,8 +1801,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>(); ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) { while (r.next()) {
id = r.getInt("plot_plot_id"); id = r.getInt("plot_plot_id");
owner = r.getString("user_uuid"); o = r.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id); Plot plot = plots.get(id);
if (plot != null) { if (plot != null) {
plot.getDenied().add(user); plot.getDenied().add(user);
@ -1771,7 +1845,7 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
int m = resultSet.getInt("merged"); Integer m = resultSet.getInt("merged");
boolean[] merged = new boolean[4]; boolean[] merged = new boolean[4];
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
merged[3 - i] = (m & 1 << i) != 0; merged[3 - i] = (m & 1 << i) != 0;
@ -1962,10 +2036,11 @@ import java.util.concurrent.atomic.AtomicInteger;
* Purge all plots with the following database IDs * Purge all plots with the following database IDs
*/ */
@Override public void purgeIds(final Set<Integer> uniqueIds) { @Override public void purgeIds(final Set<Integer> uniqueIds) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
if (!uniqueIds.isEmpty()) { if (!uniqueIds.isEmpty()) {
try { try {
ArrayList<Integer> uniqueIdsList = new ArrayList<>(uniqueIds); ArrayList<Integer> uniqueIdsList = new ArrayList<Integer>(uniqueIds);
String stmt_prefix = ""; String stmt_prefix = "";
int size = uniqueIdsList.size(); int size = uniqueIdsList.size();
int packet = 990; int packet = 990;
@ -1979,7 +2054,7 @@ import java.util.concurrent.atomic.AtomicInteger;
if (subList.isEmpty()) { if (subList.isEmpty()) {
break; break;
} }
StringBuilder idstr2 = new StringBuilder(); StringBuilder idstr2 = new StringBuilder("");
stmt_prefix = ""; stmt_prefix = "";
for (Integer id : subList) { for (Integer id : subList) {
idstr2.append(stmt_prefix).append(id); idstr2.append(stmt_prefix).append(id);
@ -2025,11 +2100,13 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!");
}
}); });
} }
@Override public void purge(final PlotArea area, final Set<PlotId> plots) { @Override public void purge(final PlotArea area, final Set<PlotId> plots) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix "SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix
+ "plot` WHERE `world` = ?")) { + "plot` WHERE `world` = ?")) {
@ -2038,7 +2115,8 @@ import java.util.concurrent.atomic.AtomicInteger;
try (ResultSet r = stmt.executeQuery()) { try (ResultSet r = stmt.executeQuery()) {
ids = new HashSet<>(); ids = new HashSet<>();
while (r.next()) { while (r.next()) {
PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); PlotId plot_id =
new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z"));
if (plots.contains(plot_id)) { if (plots.contains(plot_id)) {
ids.add(r.getInt("id")); ids.add(r.getInt("id"));
} }
@ -2055,6 +2133,7 @@ import java.util.concurrent.atomic.AtomicInteger;
PlotId id = new PlotId(plotId.x, plotId.y); PlotId id = new PlotId(plotId.x, plotId.y);
area.removePlot(id); area.removePlot(id);
} }
}
}); });
} }
@ -2444,7 +2523,11 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
resultSet.close(); resultSet.close();
TaskManager.runTaskAsync(() -> result.run(metaMap)); TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
result.run(metaMap);
}
});
} }
}); });
@ -2501,11 +2584,18 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
owner = resultSet.getString("owner"); owner = resultSet.getString("owner");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(owner);
if (user == null) {
user = UUID.fromString(owner);
uuids.put(owner, user);
}
cluster = new PlotCluster(null, pos1, pos2, user, id); cluster = new PlotCluster(null, pos1, pos2, user, id);
clusters.put(id, cluster); clusters.put(id, cluster);
Set<PlotCluster> set = Set<PlotCluster> set = newClusters.get(areaid);
newClusters.computeIfAbsent(areaid, k -> new HashSet<>()); if (set == null) {
set = new HashSet<>();
newClusters.put(areaid, set);
}
set.add(cluster); set.add(cluster);
} }
//Getting helpers //Getting helpers
@ -2514,7 +2604,11 @@ import java.util.concurrent.atomic.AtomicInteger;
while (resultSet.next()) { while (resultSet.next()) {
id = resultSet.getInt("cluster_id"); id = resultSet.getInt("cluster_id");
owner = resultSet.getString("user_uuid"); owner = resultSet.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(owner);
if (user == null) {
user = UUID.fromString(owner);
uuids.put(owner, user);
}
cluster = clusters.get(id); cluster = clusters.get(id);
if (cluster != null) { if (cluster != null) {
cluster.helpers.add(user); cluster.helpers.add(user);
@ -2529,7 +2623,11 @@ import java.util.concurrent.atomic.AtomicInteger;
while (resultSet.next()) { while (resultSet.next()) {
id = resultSet.getInt("cluster_id"); id = resultSet.getInt("cluster_id");
owner = resultSet.getString("user_uuid"); owner = resultSet.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString); user = uuids.get(owner);
if (user == null) {
user = UUID.fromString(owner);
uuids.put(owner, user);
}
cluster = clusters.get(id); cluster = clusters.get(id);
if (cluster != null) { if (cluster != null) {
cluster.invited.add(user); cluster.invited.add(user);
@ -2562,7 +2660,7 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
int m = resultSet.getInt("merged"); Integer m = resultSet.getInt("merged");
boolean[] merged = new boolean[4]; boolean[] merged = new boolean[4];
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
merged[3 - i] = (m & 1 << i) != 0; merged[3 - i] = (m & 1 << i) != 0;
@ -2628,6 +2726,32 @@ import java.util.concurrent.atomic.AtomicInteger;
return newClusters; return newClusters;
} }
@Override public void setFlags(final PlotCluster cluster, HashMap<Flag<?>, Object> flags) {
final StringBuilder flag_string = new StringBuilder();
int i = 0;
for (Entry<Flag<?>, Object> flag : flags.entrySet()) {
if (i != 0) {
flag_string.append(',');
}
flag_string.append(flag.getKey().getName()).append(':').append(
flag.getKey().valueToString(flag.getValue()).replaceAll(":", "\u00AF")
.replaceAll(",", "´"));
i++;
}
addClusterTask(cluster, new UniqueStatement("setFlags") {
@Override public void set(PreparedStatement stmt) throws SQLException {
stmt.setString(1, flag_string.toString());
stmt.setInt(2, getClusterId(cluster));
}
@Override public PreparedStatement get() throws SQLException {
return SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "cluster_settings` SET `flags` = ? WHERE `cluster_id` = ?");
}
});
}
@Override public void setClusterName(final PlotCluster cluster, final String name) { @Override public void setClusterName(final PlotCluster cluster, final String name) {
addClusterTask(cluster, new UniqueStatement("setClusterName") { addClusterTask(cluster, new UniqueStatement("setClusterName") {
@Override public void set(PreparedStatement stmt) throws SQLException { @Override public void set(PreparedStatement stmt) throws SQLException {
@ -2706,7 +2830,7 @@ import java.util.concurrent.atomic.AtomicInteger;
new UniqueStatement("createCluster_settings_" + cluster.hashCode()) { new UniqueStatement("createCluster_settings_" + cluster.hashCode()) {
@Override public void set(PreparedStatement stmt) throws SQLException { @Override public void set(PreparedStatement stmt) throws SQLException {
stmt.setInt(1, getClusterId(cluster)); stmt.setInt(1, getClusterId(cluster));
stmt.setString(2, cluster.getAlias()); stmt.setString(2, cluster.settings.getAlias());
} }
@Override public PreparedStatement get() throws SQLException { @Override public PreparedStatement get() throws SQLException {
@ -2945,7 +3069,8 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override @Override
public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min, public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min,
final PlotId max) { final PlotId max) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
if (min == null) { if (min == null) {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix "UPDATE `" + SQLManager.this.prefix
@ -2993,11 +3118,13 @@ import java.util.concurrent.atomic.AtomicInteger;
e.printStackTrace(); e.printStackTrace();
} }
} }
}
}); });
} }
@Override public void replaceUUID(final UUID old, final UUID now) { @Override public void replaceUUID(final UUID old, final UUID now) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
try (Statement stmt = SQLManager.this.connection.createStatement()) { try (Statement stmt = SQLManager.this.connection.createStatement()) {
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now "UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now
@ -3009,20 +3136,21 @@ import java.util.concurrent.atomic.AtomicInteger;
"UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '" "UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now.toString() "UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now
+ "' WHERE `owner` = '" + old.toString() + '\''); .toString() + "' WHERE `owner` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '" + now "UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '"
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '" + now "UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '"
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '" + now "UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '"
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }

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 implements Database { public class SQLite extends Database {
private final String dbLocation; private final String dbLocation;
private Connection connection; private Connection connection;

View File

@ -2,10 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.flag;
import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotSettings;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -117,7 +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;
} }
@ -144,6 +141,13 @@ 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.
* *
@ -213,6 +217,20 @@ 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()) {
@ -230,6 +248,20 @@ 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,7 +277,11 @@ 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.computeIfAbsent(pair, k -> new BaseBlock[height]); BaseBlock[] existing = this.G_SCH.get(pair);
if (existing == null) {
existing = new BaseBlock[height];
this.G_SCH.put(pair, existing);
}
existing[y] = id; existing[y] = id;
} }
} }

View File

@ -1,5 +1,5 @@
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,12 +4,10 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.commands.DebugExec; import com.github.intellectualsites.plotsquared.plot.commands.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> {
public static <U> Expression<U> constant(final U value) {
@Nonnull 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) {
return value; return value;

View File

@ -20,7 +20,6 @@ import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.awt.geom.Area; import java.awt.geom.Area;
import java.awt.geom.PathIterator; import java.awt.geom.PathIterator;
@ -33,10 +32,12 @@ import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* The plot class<br> [IMPORTANT] - Unclaimed plots will not have persistent information. - Any * The plot class<br>
* information set/modified in an unclaimed object may not be reflected in other instances - Using * [IMPORTANT]
* the `new` operator will create an unclaimed plot instance - Use the methods from the * - Unclaimed plots will not have persistent information.
* PlotArea/PS/Location etc to get existing plots * - Any information set/modified in an unclaimed object may not be reflected in other instances
* - Using the `new` operator will create an unclaimed plot instance
* - Use the methods from the PlotArea/PS/Location etc to get existing plots
*/ */
public class Plot { public class Plot {
@ -50,8 +51,9 @@ public class Plot {
*/ */
private final PlotId id; private final PlotId id;
/** /**
* plot owner (Merged plots can have multiple owners) Direct access is Deprecated: use * plot owner
* getOwners() * (Merged plots can have multiple owners)
* Direct access is Deprecated: use getOwners()
*/ */
@Deprecated public UUID owner; @Deprecated public UUID owner;
/** /**
@ -59,9 +61,9 @@ public class Plot {
*/ */
public boolean countsTowardsMax = true; public boolean countsTowardsMax = true;
/** /**
* Represents whatever the database manager needs it to: <br> - A value of -1 usually indicates * Represents whatever the database manager needs it to: <br>
* the plot will not be stored in the DB<br> - A value of 0 usually indicates that the DB manager * - A value of -1 usually indicates the plot will not be stored in the DB<br>
* hasn't set a value<br> * - A value of 0 usually indicates that the DB manager hasn't set a value<br>
* *
* @deprecated magical * @deprecated magical
*/ */
@ -84,14 +86,15 @@ public class Plot {
*/ */
private HashSet<UUID> denied; private HashSet<UUID> denied;
/** /**
* External settings class. - Please favor the methods over direct access to this class<br> - The * External settings class.
* methods are more likely to be left unchanged from version changes<br> * - Please favor the methods over direct access to this class<br>
* - The methods are more likely to be left unchanged from version changes<br>
*/ */
private PlotSettings settings; private PlotSettings settings;
/** /**
* The {@link PlotArea}. * The {@link PlotArea}.
*/ */
@Nonnull private PlotArea area; private PlotArea area;
/** /**
* Session only plot metadata (session is until the server stops)<br> * Session only plot metadata (session is until the server stops)<br>
* <br> * <br>
@ -101,42 +104,43 @@ public class Plot {
*/ */
private ConcurrentHashMap<String, Object> meta; private ConcurrentHashMap<String, Object> meta;
/** /**
* The cached origin plot. - The origin plot is used for plot grouping and relational data * The cached origin plot.
* - The origin plot is used for plot grouping and relational data
*/ */
private Plot origin; private Plot origin;
/** /**
* Constructor for a new plot. (Only changes after plot.create() will be properly set in the * Constructor for a new plot.
* database) * (Only changes after plot.create() will be properly set in the database)
* *
* @param area the PlotArea where the plot is located * @param area the PlotArea where the plot is located
* @param id the plot id * @param id the plot id
* @param owner the plot owner * @param owner the plot owner
* @see Plot#getPlot(Location) for existing plots * @see Plot#getPlot(Location) for existing plots
*/ */
public Plot(@Nonnull PlotArea area, PlotId id, UUID owner) { public Plot(PlotArea area, PlotId id, UUID owner) {
this.area = area; this.area = area;
this.id = id; this.id = id;
this.owner = owner; this.owner = owner;
} }
/** /**
* Constructor for an unowned plot. (Only changes after plot.create() will be properly set in the * Constructor for an unowned plot.
* database) * (Only changes after plot.create() will be properly set in the database)
* *
* @param area the PlotArea where the plot is located * @param area the PlotArea where the plot is located
* @param id the plot id * @param id the plot id
* @see Plot#getPlot(Location) for existing plots * @see Plot#getPlot(Location) for existing plots
*/ */
public Plot(@Nonnull PlotArea area, PlotId id) { public Plot(PlotArea area, PlotId id) {
this.area = area; this.area = area;
this.id = id; this.id = id;
} }
/** /**
* Constructor for a temporary plot (use -1 for temp)<br> The database will ignore any queries * Constructor for a temporary plot (use -1 for temp)<br>
* regarding temporary plots. Please note that some bulk plot management functions may still * The database will ignore any queries regarding temporary plots.
* affect temporary plots (TODO: fix this) * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this)
* *
* @param area the PlotArea where the plot is located * @param area the PlotArea where the plot is located
* @param id the plot id * @param id the plot id
@ -144,7 +148,7 @@ public class Plot {
* @param temp Represents whatever the database manager needs it to * @param temp Represents whatever the database manager needs it to
* @see Plot#getPlot(Location) for existing plots * @see Plot#getPlot(Location) for existing plots
*/ */
public Plot(@Nonnull PlotArea area, PlotId id, UUID owner, int temp) { public Plot(PlotArea area, PlotId id, UUID owner, int temp) {
this.area = area; this.area = area;
this.id = id; this.id = id;
this.owner = owner; this.owner = owner;
@ -163,7 +167,7 @@ public class Plot {
*/ */
public Plot(PlotId id, UUID owner, HashSet<UUID> trusted, HashSet<UUID> members, public Plot(PlotId id, UUID owner, HashSet<UUID> trusted, HashSet<UUID> members,
HashSet<UUID> denied, String alias, BlockLoc position, Collection<Flag> flags, HashSet<UUID> denied, String alias, BlockLoc position, Collection<Flag> flags,
@Nonnull PlotArea area, boolean[] merged, long timestamp, int temp) { PlotArea area, boolean[] merged, long timestamp, int temp) {
this.id = id; this.id = id;
this.area = area; this.area = area;
this.owner = owner; this.owner = owner;
@ -264,8 +268,9 @@ public class Plot {
} }
/** /**
* Delete the metadata for a key<br> - metadata is session only - deleting other plugin's metadata * Delete the metadata for a key<br>
* may cause issues * - metadata is session only
* - deleting other plugin's metadata may cause issues
* *
* @param key key to delete * @param key key to delete
*/ */
@ -285,9 +290,9 @@ public class Plot {
} }
/** /**
* Efficiently get the players currently inside this plot<br> - Will return an empty list if no * Efficiently get the players currently inside this plot<br>
* players are in the plot<br> - Remember, you can cast a PlotPlayer to it's respective * - Will return an empty list if no players are in the plot<br>
* implementation (BukkitPlayer, SpongePlayer) to obtain the player object * - Remember, you can cast a PlotPlayer to it's respective implementation (BukkitPlayer, SpongePlayer) to obtain the player object
* *
* @return list of PlotPlayer(s) or an empty list * @return list of PlotPlayer(s) or an empty list
*/ */
@ -348,7 +353,7 @@ public class Plot {
} }
if (isMerged()) { if (isMerged()) {
Set<Plot> plots = getConnectedPlots(); Set<Plot> plots = getConnectedPlots();
Plot[] array = plots.toArray(new Plot[0]); Plot[] array = plots.toArray(new Plot[plots.size()]);
ImmutableSet.Builder<UUID> owners = ImmutableSet.builder(); ImmutableSet.Builder<UUID> owners = ImmutableSet.builder();
UUID last = this.owner; UUID last = this.owner;
owners.add(this.owner); owners.add(this.owner);
@ -403,38 +408,41 @@ public class Plot {
/** /**
* Get the {@link PlotId}. * Get the {@link PlotId}.
*/ */
@Nonnull public PlotId getId() { public PlotId getId() {
return this.id; return this.id;
} }
/** /**
* Get the plot world object for this plot<br> - The generic PlotArea object can be casted to its * Get the plot world object for this plot<br>
* respective class for more control (e.g. HybridPlotWorld) * - The generic PlotArea object can be casted to its respective class for more control (e.g. HybridPlotWorld)
* *
* @return PlotArea * @return PlotArea
*/ */
@Nonnull public PlotArea getArea() { public PlotArea getArea() {
return this.area; return this.area;
} }
/** /**
* Assign this plot to a plot area.<br> (Mostly used during startup when worlds are being * Assign this plot to a plot area.<br>
* created)<br> Note: Using this when it doesn't make sense will result in strange behavior * (Mostly used during startup when worlds are being created)<br>
* Note: Using this when it doesn't make sense will result in strange behavior
* *
* @param area area to assign to * @param area area to assign to
*/ */
public void setArea(@Nonnull PlotArea area) { public void setArea(PlotArea area) {
if (this.getArea() == area) { if (this.getArea() == area) {
return; return;
} }
if (this.getArea() != null) {
this.area.removePlot(this.id); this.area.removePlot(this.id);
}
this.area = area; this.area = area;
area.addPlot(this); area.addPlot(this);
} }
/** /**
* Get the plot manager object for this plot<br> - The generic PlotManager object can be casted to * Get the plot manager object for this plot<br>
* its respective class for more control (e.g. HybridPlotManager) * - The generic PlotManager object can be casted to its respective class for more control (e.g. HybridPlotManager)
* *
* @return PlotManager * @return PlotManager
*/ */
@ -448,7 +456,7 @@ public class Plot {
* @return PlotSettings * @return PlotSettings
* @deprecated use equivalent plot method; * @deprecated use equivalent plot method;
*/ */
@Deprecated @Nonnull public PlotSettings getSettings() { @Deprecated public PlotSettings getSettings() {
if (this.settings == null) { if (this.settings == null) {
this.settings = new PlotSettings(); this.settings = new PlotSettings();
} }
@ -456,7 +464,8 @@ public class Plot {
} }
/** /**
* Returns true if the plot is not merged, or it is the base plot of multiple merged plots. * Returns true if the plot is not merged, or it is the base
* plot of multiple merged plots.
* *
* @return Boolean * @return Boolean
*/ */
@ -466,9 +475,10 @@ public class Plot {
/** /**
* The base plot is an arbitrary but specific connected plot. It is useful for the following:<br> * The base plot is an arbitrary but specific connected plot. It is useful for the following:<br>
* - Merged plots need to be treated as a single plot for most purposes<br> - Some data such as * - Merged plots need to be treated as a single plot for most purposes<br>
* home location needs to be associated with the group rather than each plot<br> - If the plot is * - Some data such as home location needs to be associated with the group rather than each plot<br>
* not merged it will return itself.<br> - The result is cached locally * - If the plot is not merged it will return itself.<br>
* - The result is cached locally
* *
* @return base Plot * @return base Plot
*/ */
@ -508,8 +518,9 @@ public class Plot {
} }
/** /**
* Get the timestamp of when the plot was created (unreliable)<br> - not accurate if the plot was * Get the timestamp of when the plot was created (unreliable)<br>
* created before this was implemented<br> - Milliseconds since the epoch<br> * - not accurate if the plot was created before this was implemented<br>
* - Milliseconds since the epoch<br>
* *
* @return the creation date of the plot * @return the creation date of the plot
*/ */
@ -521,11 +532,19 @@ public class Plot {
} }
/** /**
* Get if the plot is merged in a direction<br> ------- Actual -------<br> 0 = north<br> 1 = * Get if the plot is merged in a direction<br>
* east<br> 2 = south<br> 3 = west<br> ----- Artificial -----<br> 4 = north-east<br> 5 = * ------- Actual -------<br>
* south-east<br> 6 = south-west<br> 7 = north-west<br> ----------<br> Note: A plot that is merged * 0 = north<br>
* north and east will not be merged northeast if the northeast plot is not part of the same * 1 = east<br>
* group<br> * 2 = south<br>
* 3 = west<br>
* ----- Artificial -----<br>
* 4 = north-east<br>
* 5 = south-east<br>
* 6 = south-west<br>
* 7 = north-west<br>
* ----------<br>
* Note: A plot that is merged north and east will not be merged northeast if the northeast plot is not part of the same group<br>
* *
* @param direction direction to check for merged plot * @param direction direction to check for merged plot
* @return true if merged in that direction * @return true if merged in that direction
@ -737,9 +756,8 @@ public class Plot {
public boolean setOwner(UUID owner, PlotPlayer initiator) { public boolean setOwner(UUID owner, PlotPlayer initiator) {
boolean result = EventUtil.manager boolean result = EventUtil.manager
.callOwnerChange(initiator, this, owner, hasOwner() ? this.owner : null, hasOwner()); .callOwnerChange(initiator, this, owner, hasOwner() ? this.owner : null, hasOwner());
if (!result) { if (!result)
return false; return false;
}
if (!hasOwner()) { if (!hasOwner()) {
this.owner = owner; this.owner = owner;
create(); create();
@ -934,9 +952,8 @@ public class Plot {
* @param name name * @param name name
*/ */
public void setSign(final String name) { public void setSign(final String name) {
if (!isLoaded()) { if (!isLoaded())
return; return;
}
if (!PlotSquared.get().isMainThread(Thread.currentThread())) { if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
TaskManager.runTask(() -> Plot.this.setSign(name)); TaskManager.runTask(() -> Plot.this.setSign(name));
return; return;
@ -1045,8 +1062,13 @@ public class Plot {
* Count the entities in a plot * Count the entities in a plot
* *
* @return array of entity counts * @return array of entity counts
* @see ChunkManager#countEntities(Plot) 0 = Entity 1 = Animal 2 = Monster 3 = Mob 4 = Boat 5 = * @see ChunkManager#countEntities(Plot)
* Misc * 0 = Entity
* 1 = Animal
* 2 = Monster
* 3 = Mob
* 4 = Boat
* 5 = Misc
*/ */
public int[] countEntities() { public int[] countEntities() {
int[] count = new int[6]; int[] count = new int[6];
@ -1076,8 +1098,8 @@ public class Plot {
} }
/** /**
* Decrement the number of tracked tasks this plot is running<br> - Used to track/limit the number * Decrement the number of tracked tasks this plot is running<br>
* of things a player can do on the plot at once * - Used to track/limit the number of things a player can do on the plot at once
* *
* @return previous number of tasks (int) * @return previous number of tasks (int)
*/ */
@ -1096,8 +1118,8 @@ public class Plot {
} }
/** /**
* Get the number of tracked running tasks for this plot<br> - Used to track/limit the number of * Get the number of tracked running tasks for this plot<br>
* things a player can do on the plot at once * - Used to track/limit the number of things a player can do on the plot at once
* *
* @return number of tasks (int) * @return number of tasks (int)
*/ */
@ -1107,8 +1129,7 @@ public class Plot {
} }
/** /**
* Unclaim the plot (does not modify terrain). Changes made to this plot will not be reflected in * Unclaim the plot (does not modify terrain). Changes made to this plot will not be reflected in unclaimed plot objects.
* unclaimed plot objects.
* *
* @return false if the Plot has no owner, otherwise true. * @return false if the Plot has no owner, otherwise true.
*/ */
@ -1148,9 +1169,8 @@ public class Plot {
Location bot = corners[1]; Location bot = corners[1];
Location loc = new Location(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), Location loc = new Location(this.getWorldName(), MathMan.average(bot.getX(), top.getX()),
MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ()));
if (!isLoaded()) { if (!isLoaded())
return loc; return loc;
}
int y = int y =
isLoaded() ? WorldUtil.IMP.getHighestBlock(getWorldName(), loc.getX(), loc.getZ()) : 62; isLoaded() ? WorldUtil.IMP.getHighestBlock(getWorldName(), loc.getX(), loc.getZ()) : 62;
if (area.ALLOW_SIGNS) { if (area.ALLOW_SIGNS) {
@ -1185,9 +1205,8 @@ public class Plot {
Location bot = this.getBottomAbs(); Location bot = this.getBottomAbs();
Location loc = new Location(bot.getWorld(), bot.getX() + home.x, bot.getY() + home.y, Location loc = new Location(bot.getWorld(), bot.getX() + home.x, bot.getY() + home.y,
bot.getZ() + home.z, home.yaw, home.pitch); bot.getZ() + home.z, home.yaw, home.pitch);
if (!isLoaded()) { if (!isLoaded())
return loc; return loc;
}
if (!WorldUtil.IMP.getBlock(loc).isAir()) { if (!WorldUtil.IMP.getBlock(loc).isAir()) {
loc.setY(Math.max( loc.setY(Math.max(
1 + WorldUtil.IMP.getHighestBlock(this.getWorldName(), loc.getX(), loc.getZ()), 1 + WorldUtil.IMP.getHighestBlock(this.getWorldName(), loc.getX(), loc.getZ()),
@ -1216,8 +1235,8 @@ public class Plot {
} }
/** /**
* Get the default home location for a plot<br> - Ignores any home location set for that specific * Get the default home location for a plot<br>
* plot * - Ignores any home location set for that specific plot
* *
* @return Location * @return Location
*/ */
@ -1277,7 +1296,8 @@ public class Plot {
} }
/** /**
* Set a rating for a user<br> - If the user has already rated, the following will return false * Set a rating for a user<br>
* - If the user has already rated, the following will return false
* *
* @param uuid uuid of rater * @param uuid uuid of rater
* @param rating rating * @param rating rating
@ -1308,7 +1328,8 @@ public class Plot {
} }
/** /**
* Get the ratings associated with a plot<br> - The rating object may contain multiple categories * Get the ratings associated with a plot<br>
* - The rating object may contain multiple categories
* *
* @return Map of user who rated to the rating * @return Map of user who rated to the rating
*/ */
@ -1330,7 +1351,8 @@ public class Plot {
} }
/** /**
* Resend all chunks inside the plot to nearby players<br> This should not need to be called * Resend all chunks inside the plot to nearby players<br>
* This should not need to be called
*/ */
public void refreshChunks() { public void refreshChunks() {
LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(getWorldName(), false); LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(getWorldName(), false);
@ -1372,9 +1394,10 @@ public class Plot {
} }
/** /**
* Register a plot and create it in the database<br> - The plot will not be created if the owner * Register a plot and create it in the database<br>
* is null<br> - Any setting from before plot creation will not be saved until the server is * - The plot will not be created if the owner is null<br>
* stopped properly. i.e. Set any values/options after plot creation. * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot
* creation.
* *
* @return true if plot was created successfully * @return true if plot was created successfully
*/ */
@ -1436,9 +1459,10 @@ public class Plot {
} }
/** /**
* Register a plot and create it in the database<br> - The plot will not be created if the owner * Register a plot and create it in the database<br>
* is null<br> - Any setting from before plot creation will not be saved until the server is * - The plot will not be created if the owner is null<br>
* stopped properly. i.e. Set any values/options after plot creation. * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot
* creation.
* *
* @param uuid the uuid of the plot owner * @param uuid the uuid of the plot owner
* @param notify notify * @param notify notify
@ -1478,7 +1502,8 @@ public class Plot {
} }
/** /**
* Set components such as border, wall, floor. (components are generator specific) * Set components such as border, wall, floor.
* (components are generator specific)
*/ */
public boolean setComponent(String component, String blocks) { public boolean setComponent(String component, String blocks) {
BlockBucket parsed = Configuration.BLOCK_BUCKET.parseString(blocks); BlockBucket parsed = Configuration.BLOCK_BUCKET.parseString(blocks);
@ -1497,6 +1522,8 @@ public class Plot {
/** /**
* Return the top location for the plot. * Return the top location for the plot.
*
* @return
*/ */
public Location getTopAbs() { public Location getTopAbs() {
Location top = this.area.getPlotManager().getPlotTopLocAbs(this.area, this.id); Location top = this.area.getPlotManager().getPlotTopLocAbs(this.area, this.id);
@ -1506,6 +1533,8 @@ public class Plot {
/** /**
* Return the bottom location for the plot. * Return the bottom location for the plot.
*
* @return
*/ */
public Location getBottomAbs() { public Location getBottomAbs() {
Location loc = this.area.getPlotManager().getPlotBottomLocAbs(this.area, this.id); Location loc = this.area.getPlotManager().getPlotBottomLocAbs(this.area, this.id);
@ -1518,6 +1547,7 @@ public class Plot {
* *
* @param plot the plot to swap data with * @param plot the plot to swap data with
* @param whenDone the task to run at the end of this method. * @param whenDone the task to run at the end of this method.
* @return
*/ */
public boolean swapData(Plot plot, Runnable whenDone) { public boolean swapData(Plot plot, Runnable whenDone) {
if (this.owner == null) { if (this.owner == null) {
@ -1553,6 +1583,8 @@ public class Plot {
* Move the settings for a plot. * Move the settings for a plot.
* *
* @param plot the plot to move * @param plot the plot to move
* @param whenDone
* @return
*/ */
public boolean moveData(Plot plot, Runnable whenDone) { public boolean moveData(Plot plot, Runnable whenDone) {
if (this.owner == null) { if (this.owner == null) {
@ -1576,8 +1608,8 @@ public class Plot {
} }
/** /**
* Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like * Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like each plot treated as
* each plot treated as a small plot use getPlotTopLocAbs(...) * a small plot use getPlotTopLocAbs(...)
* *
* @return Location top of mega plot * @return Location top of mega plot
*/ */
@ -1596,8 +1628,9 @@ public class Plot {
} }
/** /**
* Gets the bottom location for a plot.<br> - Does not respect mega plots<br> - Merged plots, only * Gets the bottom location for a plot.<br>
* the road will be considered part of the plot<br> * - Does not respect mega plots<br>
* - Merged plots, only the road will be considered part of the plot<br>
* *
* @return Location bottom of mega plot * @return Location bottom of mega plot
*/ */
@ -1616,9 +1649,9 @@ public class Plot {
} }
/** /**
* Returns the top and bottom location.<br> - If the plot is not connected, it will return its own * Returns the top and bottom location.<br>
* corners<br> - the returned locations will not necessarily correspond to claimed plots if the * - If the plot is not connected, it will return its own corners<br>
* connected plots do not form a rectangular shape * - the returned locations will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape
* *
* @return new Location[] { bottom, top } * @return new Location[] { bottom, top }
* @deprecated as merged plots no longer need to be rectangular * @deprecated as merged plots no longer need to be rectangular
@ -1631,7 +1664,8 @@ public class Plot {
} }
/** /**
* Remove the east road section of a plot<br> - Used when a plot is merged<br> * Remove the east road section of a plot<br>
* - Used when a plot is merged<br>
*/ */
public void removeRoadEast() { public void removeRoadEast() {
if (this.area.TYPE != 0 && this.area.TERRAIN > 1) { if (this.area.TYPE != 0 && this.area.TERRAIN > 1) {
@ -1650,6 +1684,7 @@ public class Plot {
} }
/** /**
* @return
* @deprecated in favor of getCorners()[0];<br> * @deprecated in favor of getCorners()[0];<br>
*/ */
// Won't remove as suggestion also points to deprecated method // Won't remove as suggestion also points to deprecated method
@ -1667,8 +1702,8 @@ public class Plot {
} }
/** /**
* Swap the plot contents and settings with another location<br> - The destination must correspond * Swap the plot contents and settings with another location<br>
* to a valid plot of equal dimensions * - The destination must correspond to a valid plot of equal dimensions
* *
* @param destination The other plot to swap with * @param destination The other plot to swap with
* @param whenDone A task to run when finished, or null * @param whenDone A task to run when finished, or null
@ -1682,7 +1717,8 @@ public class Plot {
} }
/** /**
* Move the plot to an empty location<br> - The location must be empty * Move the plot to an empty location<br>
* - The location must be empty
* *
* @param destination Where to move the plot * @param destination Where to move the plot
* @param whenDone A task to run when done, or null * @param whenDone A task to run when done, or null
@ -1706,7 +1742,10 @@ public class Plot {
/** /**
* Remove a denied player (use DBFunc as well)<br> Using the * uuid will remove all users * Remove a denied player (use DBFunc as well)<br>
* Using the * uuid will remove all users
*
* @param uuid
*/ */
public boolean removeDenied(UUID uuid) { public boolean removeDenied(UUID uuid) {
if (uuid == DBFunc.EVERYONE && !denied.contains(uuid)) { if (uuid == DBFunc.EVERYONE && !denied.contains(uuid)) {
@ -1731,7 +1770,10 @@ public class Plot {
} }
/** /**
* Remove a helper (use DBFunc as well)<br> Using the * uuid will remove all users * Remove a helper (use DBFunc as well)<br>
* Using the * uuid will remove all users
*
* @param uuid
*/ */
public boolean removeTrusted(UUID uuid) { public boolean removeTrusted(UUID uuid) {
if (uuid == DBFunc.EVERYONE && !trusted.contains(uuid)) { if (uuid == DBFunc.EVERYONE && !trusted.contains(uuid)) {
@ -1756,7 +1798,10 @@ public class Plot {
} }
/** /**
* Remove a trusted user (use DBFunc as well)<br> Using the * uuid will remove all users * Remove a trusted user (use DBFunc as well)<br>
* Using the * uuid will remove all users
*
* @param uuid
*/ */
public boolean removeMember(UUID uuid) { public boolean removeMember(UUID uuid) {
if (this.members == null) { if (this.members == null) {
@ -1785,6 +1830,8 @@ public class Plot {
/** /**
* Export the plot as a schematic to the configured output directory. * Export the plot as a schematic to the configured output directory.
*
* @return
*/ */
public void export(final RunnableVal<Boolean> whenDone) { public void export(final RunnableVal<Boolean> whenDone) {
SchematicHandler.manager.getCompoundTag(this, new RunnableVal<CompoundTag>() { SchematicHandler.manager.getCompoundTag(this, new RunnableVal<CompoundTag>() {
@ -1824,10 +1871,11 @@ public class Plot {
} }
/** /**
* Upload this plot as a world file<br> - The mca files are each 512x512, so depending on the plot * Upload this plot as a world file<br>
* size it may also download adjacent plots<br> - Works best when (plot width + road width) % 512 * - The mca files are each 512x512, so depending on the plot size it may also download adjacent plots<br>
* == 0<br> * - Works best when (plot width + road width) % 512 == 0<br>
* *
* @param whenDone
* @see WorldUtil * @see WorldUtil
*/ */
public void uploadWorld(RunnableVal<URL> whenDone) { public void uploadWorld(RunnableVal<URL> whenDone) {
@ -1850,8 +1898,10 @@ public class Plot {
} }
/** /**
* Get the plot hashcode<br> Note: The hashcode is unique if:<br> - Plots are in the same * Get the plot hashcode<br>
* world<br> - The x,z coordinates are between Short.MIN_VALUE and Short.MAX_VALUE<br> * Note: The hashcode is unique if:<br>
* - Plots are in the same world<br>
* - The x,z coordinates are between Short.MIN_VALUE and Short.MAX_VALUE<br>
* *
* @return integer. * @return integer.
*/ */
@ -1860,7 +1910,10 @@ public class Plot {
} }
/** /**
* Get the flags specific to this plot<br> - Does not take default flags into account<br> * Get the flags specific to this plot<br>
* - Does not take default flags into account<br>
*
* @return
*/ */
public HashMap<Flag<?>, Object> getFlags() { public HashMap<Flag<?>, Object> getFlags() {
return this.getSettings().flags; return this.getSettings().flags;
@ -1868,13 +1921,16 @@ public class Plot {
/** /**
* Set a flag for this plot. * Set a flag for this plot.
*
* @param flags
*/ */
public void setFlags(HashMap<Flag<?>, Object> flags) { public void setFlags(HashMap<Flag<?>, Object> flags) {
FlagManager.setPlotFlags(this, flags); FlagManager.setPlotFlags(this, flags);
} }
/** /**
* Get the plot alias. - Returns an empty string if no alias is set * Get the plot alias.
* - Returns an empty string if no alias is set
* *
* @return The plot alias * @return The plot alias
*/ */
@ -1905,10 +1961,20 @@ public class Plot {
} }
/** /**
* Set the raw merge data<br> - Updates DB<br> - Does not modify terrain<br> ----------<br> 0 = * Set the raw merge data<br>
* north<br> 1 = east<br> 2 = south<br> 3 = west<br> ----------<br> * - Updates DB<br>
* - Does not modify terrain<br>
* ----------<br>
* 0 = north<br>
* 1 = east<br>
* 2 = south<br>
* 3 = west<br>
* ----------<br>
*
* @param direction
* @param value
*/ */
private void setMerged(int direction, boolean value) { public void setMerged(int direction, boolean value) {
if (this.getSettings().setMerged(direction, value)) { if (this.getSettings().setMerged(direction, value)) {
if (value) { if (value) {
Plot other = this.getRelative(direction).getBasePlot(false); Plot other = this.getRelative(direction).getBasePlot(false);
@ -1942,9 +2008,19 @@ public class Plot {
} }
/** /**
* Set the raw merge data<br> - Updates DB<br> - Does not modify terrain<br> Get if the plot is * Set the raw merge data<br>
* merged in a direction<br> ----------<br> 0 = north<br> 1 = east<br> 2 = south<br> 3 = west<br> * - Updates DB<br>
* ----------<br> Note: Diagonal merging (4-7) must be done by merging the corresponding plots. * - Does not modify terrain<br>
* Get if the plot is merged in a direction<br>
* ----------<br>
* 0 = north<br>
* 1 = east<br>
* 2 = south<br>
* 3 = west<br>
* ----------<br>
* Note: Diagonal merging (4-7) must be done by merging the corresponding plots.
*
* @param merged
*/ */
public void setMerged(boolean[] merged) { public void setMerged(boolean[] merged) {
this.getSettings().setMerged(merged); this.getSettings().setMerged(merged);
@ -1952,7 +2028,7 @@ public class Plot {
clearCache(); clearCache();
} }
private void clearCache() { public void clearCache() {
connected_cache = null; connected_cache = null;
regions_cache = null; regions_cache = null;
if (this.origin != null) { if (this.origin != null) {
@ -1962,9 +2038,10 @@ public class Plot {
} }
/** /**
* Get the set home location or 0,0,0 if no location is set<br> - Does not take the default home * Get the set home location or 0,0,0 if no location is set<br>
* location into account * - Does not take the default home location into account
* *
* @return
* @see #getHome() * @see #getHome()
*/ */
public BlockLoc getPosition() { public BlockLoc getPosition() {
@ -1975,6 +2052,7 @@ public class Plot {
* Check if a plot can be claimed by the provided player. * Check if a plot can be claimed by the provided player.
* *
* @param player the claiming player * @param player the claiming player
* @return
*/ */
public boolean canClaim(@Nullable PlotPlayer player) { public boolean canClaim(@Nullable PlotPlayer player) {
PlotCluster cluster = this.getCluster(); PlotCluster cluster = this.getCluster();
@ -1988,8 +2066,8 @@ public class Plot {
} }
/** /**
* Guess the owner of a plot either by the value in memory, or the sign data<br> Note: Recovering * Guess the owner of a plot either by the value in memory, or the sign data<br>
* from sign information is useful if e.g. PlotMe conversion wasn't successful * Note: Recovering from sign information is useful if e.g. PlotMe conversion wasn't successful
* *
* @return UUID * @return UUID
*/ */
@ -2055,7 +2133,8 @@ public class Plot {
} }
/** /**
* Remove the south road section of a plot<br> - Used when a plot is merged<br> * Remove the south road section of a plot<br>
* - Used when a plot is merged<br>
*/ */
public void removeRoadSouth() { public void removeRoadSouth() {
if (this.area.TYPE != 0 && this.area.TERRAIN > 1) { if (this.area.TYPE != 0 && this.area.TERRAIN > 1) {
@ -2076,8 +2155,12 @@ public class Plot {
/** /**
* Auto merge a plot in a specific direction<br> * Auto merge a plot in a specific direction<br>
* *
* @param dir The direction to merge<br> -1 = All directions<br> 0 = north<br> 1 = east<br> 2 = * @param dir The direction to merge<br>
* south<br> 3 = west<br> * -1 = All directions<br>
* 0 = north<br>
* 1 = east<br>
* 2 = south<br>
* 3 = west<br>
* @param max The max number of merges to do * @param max The max number of merges to do
* @param uuid The UUID it is allowed to merge with * @param uuid The UUID it is allowed to merge with
* @param removeRoads Whether to remove roads * @param removeRoads Whether to remove roads
@ -2162,7 +2245,10 @@ public class Plot {
} }
/** /**
* Merge the plot settings<br> - Used when a plot is merged<br> * Merge the plot settings<br>
* - Used when a plot is merged<br>
*
* @param b
*/ */
public void mergeData(Plot b) { public void mergeData(Plot b) {
HashMap<Flag<?>, Object> flags1 = this.getFlags(); HashMap<Flag<?>, Object> flags1 = this.getFlags();
@ -2224,9 +2310,11 @@ public class Plot {
} }
/** /**
* Get the plot in a relative location<br> Note: May be null if the partial plot area does not * Get the plot in a relative location<br>
* include the relative location * Note: May be null if the partial plot area does not include the relative location
* *
* @param x
* @param y
* @return Plot * @return Plot
*/ */
public Plot getRelative(int x, int y) { public Plot getRelative(int x, int y) {
@ -2238,18 +2326,28 @@ public class Plot {
} }
/** /**
* Get the plot in a relative direction<br> 0 = north<br> 1 = east<br> 2 = south<br> 3 = west<br> * Get the plot in a relative direction<br>
* 0 = north<br>
* 1 = east<br>
* 2 = south<br>
* 3 = west<br>
* Note: May be null if the partial plot area does not include the relative location * Note: May be null if the partial plot area does not include the relative location
*
* @param direction
* @return
*/ */
public Plot getRelative(int direction) { public Plot getRelative(int direction) {
return this.area.getPlotAbs(this.id.getRelative(direction)); return this.area.getPlotAbs(this.id.getRelative(direction));
} }
/** /**
* Get a set of plots connected (and including) this plot<br> - This result is cached globally * Get a set of plots connected (and including) this plot<br>
* - This result is cached globally
*
* @return
*/ */
public Set<Plot> getConnectedPlots() { public Set<Plot> getConnectedPlots() {
if (this.settings == null || !this.isMerged()) { if (this.settings == null) {
return Collections.singleton(this); return Collections.singleton(this);
} }
boolean[] merged = this.getMerged(); boolean[] merged = this.getMerged();
@ -2377,8 +2475,11 @@ public class Plot {
} }
/** /**
* This will combine each plot into effective rectangular regions<br> - This result is cached * This will combine each plot into effective rectangular regions<br>
* globally<br> - Useful for handling non rectangular shapes * - This result is cached globally<br>
* - Useful for handling non rectangular shapes
*
* @return
*/ */
public HashSet<RegionWrapper> getRegions() { public HashSet<RegionWrapper> getRegions() {
if (regions_cache != null && connected_cache != null && connected_cache.contains(this)) { if (regions_cache != null && connected_cache != null && connected_cache.contains(this)) {
@ -2461,7 +2562,9 @@ public class Plot {
} }
Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gtopabs = this.area.getPlotAbs(top).getTopAbs();
Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs();
visited.addAll(MainUtil.getPlotSelectionIds(bot, top)); for (PlotId id : MainUtil.getPlotSelectionIds(bot, top)) {
visited.add(id);
}
for (int x = bot.x; x <= top.x; x++) { for (int x = bot.x; x <= top.x; x++) {
Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); Plot plot = this.area.getPlotAbs(new PlotId(x, top.y));
if (plot.getMerged(2)) { if (plot.getMerged(2)) {
@ -2504,8 +2607,9 @@ public class Plot {
} }
/** /**
* Attempt to find the largest rectangular region in a plot (as plots can form non rectangular * Attempt to find the largest rectangular region in a plot (as plots can form non rectangular shapes)
* shapes) *
* @return
*/ */
public RegionWrapper getLargestRegion() { public RegionWrapper getLargestRegion() {
HashSet<RegionWrapper> regions = this.getRegions(); HashSet<RegionWrapper> regions = this.getRegions();
@ -2523,8 +2627,8 @@ public class Plot {
} }
/** /**
* Do the plot entry tasks for each player in the plot<br> - Usually called when the plot state * Do the plot entry tasks for each player in the plot<br>
* changes (unclaimed/claimed/flag change etc) * - Usually called when the plot state changes (unclaimed/claimed/flag change etc)
*/ */
public void reEnter() { public void reEnter() {
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(() -> {
@ -2618,8 +2722,13 @@ public class Plot {
} }
/** /**
* Set a component for a plot to the provided blocks<br> - E.g. floor, wall, border etc.<br> - The * Set a component for a plot to the provided blocks<br>
* available components depend on the generator being used<br> * - E.g. floor, wall, border etc.<br>
* - The available components depend on the generator being used<br>
*
* @param component
* @param blocks
* @return
*/ */
public boolean setComponent(String component, BlockBucket blocks) { public boolean setComponent(String component, BlockBucket blocks) {
if (StringMan if (StringMan
@ -2654,8 +2763,10 @@ public class Plot {
} }
/** /**
* Merges 2 plots Removes the road in-between <br>- Assumes plots are directly next to each other * Merges 2 plots Removes the road in-between <br>- Assumes plots are directly next to each other <br> - saves to DB
* <br> - saves to DB *
* @param lesserPlot
* @param removeRoads
*/ */
public void mergePlot(Plot lesserPlot, boolean removeRoads) { public void mergePlot(Plot lesserPlot, boolean removeRoads) {
Plot greaterPlot = this; Plot greaterPlot = this;
@ -2805,6 +2916,10 @@ public class Plot {
/** /**
* Copy a plot to a location, both physically and the settings * Copy a plot to a location, both physically and the settings
*
* @param destination
* @param whenDone
* @return
*/ */
public boolean copy(final Plot destination, final Runnable whenDone) { public boolean copy(final Plot destination, final Runnable whenDone) {
PlotId offset = new PlotId(destination.getId().x - this.getId().x, PlotId offset = new PlotId(destination.getId().x - this.getId().x,

View File

@ -721,9 +721,6 @@ 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

@ -2,24 +2,22 @@ package com.github.intellectualsites.plotsquared.plot.object;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import lombok.Getter;
import javax.annotation.Nonnull;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
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, @Nonnull PlotId pos1, @Nonnull PlotId pos2, UUID owner) { public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner) {
this.area = area; this.area = area;
this.pos1 = pos1; this.pos1 = pos1;
this.pos2 = pos2; this.pos2 = pos2;
@ -29,7 +27,7 @@ public class PlotCluster {
setRegion(); setRegion();
} }
public PlotCluster(PlotArea area, @Nonnull PlotId pos1, PlotId pos2, UUID owner, int temp) { public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner, int temp) {
this.area = area; this.area = area;
this.pos1 = pos1; this.pos1 = pos1;
this.pos2 = pos2; this.pos2 = pos2;
@ -84,14 +82,6 @@ public class PlotCluster {
return this.settings.getAlias(); return this.settings.getAlias();
} }
public void setName(String name) {
this.settings.setAlias(name);
}
public String getAlias() {
return this.settings.getAlias();
}
/** /**
* Get the area (in plots). * Get the area (in plots).
* *

View File

@ -13,7 +13,6 @@ 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,17 +48,25 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
/** /**
* Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)<br>
* already cached)<br> - Accepts sponge/bukkit Player (online) - Accepts player name (online) - * - Accepts sponge/bukkit Player (online)
* Accepts UUID - Accepts bukkit OfflinePlayer (offline) * - Accepts player name (online)
* - 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> - This will return null if the player has not * Get the cached PlotPlayer from a username<br>
* finished logging in or is not online * - This will return null if the player has not finished logging in or is not online
*
* @param name
* @return
*/ */
public static PlotPlayer get(String name) { public static PlotPlayer get(String name) {
return UUIDHandler.getPlayer(name); return UUIDHandler.getPlayer(name);
@ -66,6 +74,9 @@ 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) {
@ -101,8 +112,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
/** /**
* Delete the metadata for a key. - metadata is session only - deleting other plugin's metadata * Delete the metadata for a key.
* may cause issues * - metadata is session only
* - 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);
@ -120,8 +134,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* 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 * @return the plot the player is standing on or null if standing on a road or not in a {@link PlotArea}
* PlotArea}
*/ */
public Plot getCurrentPlot() { public Plot getCurrentPlot() {
Plot value = getMeta(PlotPlayer.META_LAST_PLOT); Plot value = getMeta(PlotPlayer.META_LAST_PLOT);
@ -132,11 +145,10 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
/** /**
* Get the total number of allowed plots Possibly relevant: (To increment the player's allowed * Get the total number of allowed plots
* plots, see the example script on the wiki) * Possibly relevant: (To increment the player's allowed plots, see the example script on the wiki)
* *
* @return number of allowed plots within the scope (globally, or in the player's current world as * @return number of allowed plots within the scope (globally, or in the player's current world as defined in the settings.yml)
* 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);
@ -145,8 +157,7 @@ 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 * @return number of allowed clusters within the scope (globally, or in the player's current world as defined in the settings.yml)
* 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);
@ -180,8 +191,7 @@ 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 * @return number of plots within the scope (globally, or in the player's current world as defined in the settings.yml)
* in the settings.yml)
* @see #getPlotCount(String); * @see #getPlotCount(String);
* @see #getPlots() * @see #getPlots()
*/ */
@ -229,6 +239,7 @@ 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();
@ -273,6 +284,8 @@ 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());
@ -305,15 +318,18 @@ 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. === !IMPORTANT ===<br> The UUID is dependent on the mode chosen in the * Get this player's UUID.
* settings.yml and may not be the same as Bukkit has (especially if using an old version of * === !IMPORTANT ===<br>
* Bukkit that does not support UUIDs) * The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has
* (especially if using an old version of Bukkit that does not support UUIDs)
* *
* @return UUID * @return UUID
*/ */
@ -356,8 +372,11 @@ 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. - Please note that this is not intended to store * Set player data that will persist restarts.
* large values - For session only data use meta * - Please note that this is not intended to store large values
* - 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});
@ -366,6 +385,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* 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) {
@ -377,6 +397,8 @@ 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);
@ -470,7 +492,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",
owned.getId(), getName())); plot.getId(), getName()));
} }
} }
String name = getName(); String name = getName();
@ -483,6 +505,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/** /**
* Get the amount of clusters this player owns in the specific world. * 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();
@ -555,27 +580,31 @@ 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(() -> { TaskManager.runTask(new Runnable() {
@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(() -> { TaskManager.runTask(new Runnable() {
@Override public void run() {
if (getMeta("teleportOnLogin", if (getMeta("teleportOnLogin",
true)) { true)) {
teleport(loc); teleport(loc);
sendMessage( sendMessage(
C.TELEPORTED_TO_PLOT.f() C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc-unloaded) (" + " (quitLoc-unloaded) ("
+ plotX + "," + plotZ + plotX + ","
+ ")"); + plotZ + ")");
}
} }
}); });
} }
@ -624,6 +653,8 @@ 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);
@ -642,7 +673,6 @@ 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. Not compatible with PlotClusters. * @deprecated Raw access
*/ */
@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;
} }
boolean setMerged(int direction, boolean merged) { public 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,7 +142,6 @@ 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) {
@ -156,26 +155,22 @@ 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,7 +4,6 @@ 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) {
@ -19,6 +18,10 @@ public class AbstractDelegateOutputStream extends OutputStream {
parent.write(b); parent.write(b);
} }
@Override public void write(byte[] b, int off, int len) throws IOException {
parent.write(b, off, len);
}
@Override public void flush() throws IOException { @Override public void flush() throws IOException {
parent.flush(); parent.flush();
} }

View File

@ -88,8 +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[0]); this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]);
this.plotAreaMap.put(plotArea.worldname, localAreas.toArray(new PlotArea[0])); this.plotAreaMap
.put(plotArea.worldname, localAreas.toArray(new PlotArea[localAreas.size()]));
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) {
@ -103,14 +104,15 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
} }
@Override public void removePlotArea(PlotArea area) { @Override public void removePlotArea(PlotArea area) {
ArrayList<PlotArea> globalAreas = new ArrayList<>(Arrays.asList(plotAreas)); ArrayList<PlotArea> globalAreas = new ArrayList<PlotArea>(Arrays.asList(plotAreas));
globalAreas.remove(area); globalAreas.remove(area);
this.plotAreas = globalAreas.toArray(new PlotArea[0]); this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]);
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.put(area.worldname, globalAreas.toArray(new PlotArea[0])); this.plotAreaMap
.put(area.worldname, globalAreas.toArray(new PlotArea[globalAreas.size()]));
this.plotAreaGrid.get(area.worldname).remove(area); this.plotAreaGrid.get(area.worldname).remove(area);
} }
} }
@ -204,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[0]); return found.toArray(new PlotArea[found.size()]);
} }
} }
@ -215,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[0]); worlds = tmp.toArray(new String[tmp.size()]);
} }
@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[0]); worlds = tmp.toArray(new String[tmp.size()]);
} }
@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 {
PlotArea getApplicablePlotArea(Location location); public PlotArea getApplicablePlotArea(Location location);
PlotArea getPlotArea(Location location); public PlotArea getPlotArea(Location location);
PlotArea getPlotArea(String world, String id); public PlotArea getPlotArea(String world, String id);
PlotArea[] getPlotAreas(String world, RegionWrapper region); public PlotArea[] getPlotAreas(String world, RegionWrapper region);
PlotArea[] getAllPlotAreas(); public PlotArea[] getAllPlotAreas();
String[] getAllWorlds(); public String[] getAllWorlds();
void addPlotArea(PlotArea area); public void addPlotArea(PlotArea area);
void removePlotArea(PlotArea area); public void removePlotArea(PlotArea area);
void addWorld(String worldName); public void addWorld(String worldName);
void removeWorld(String worldName); public void removeWorld(String worldName);
} }

View File

@ -4,7 +4,6 @@ import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.object.*;
import javax.annotation.Nonnull;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
@ -41,7 +40,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,7 +35,8 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager {
if (chars.length == 1 && chars[0] == '*') { if (chars.length == 1 && chars[0] == '*') {
return true; return true;
} }
for (char c : chars) { for (int i = 0; i < chars.length; i++) {
char c = chars[i];
switch (mode) { switch (mode) {
case 0: case 0:
mode = 1; mode = 1;

View File

@ -30,10 +30,12 @@ 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(() -> { TaskManager.IMP.taskAsync(new Runnable() {
@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 {
} }
} }
protected abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, public abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay,
int out); int out);
} }

View File

@ -71,7 +71,8 @@ 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(() -> { TaskManager.runTaskAsync(new Runnable() {
@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) {
@ -104,6 +105,7 @@ public abstract class ChunkManager {
} }
} }
}, whenDone); }, whenDone);
}
}); });
} }
@ -237,11 +239,12 @@ 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(() -> { TaskManager.runTaskAsync(new Runnable() {
@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 + "." + loc.z world + File.separator + "region" + File.separator + "r." + loc.x + "."
+ ".mca"; + loc.z + ".mca";
File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory); File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)"); PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)");
if (file.exists()) { if (file.exists()) {
@ -249,6 +252,7 @@ public abstract class ChunkManager {
} }
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
}
}); });
} }

View File

@ -19,9 +19,11 @@ 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(() -> { TaskManager.runTaskLater(new Runnable() {
@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,7 +20,8 @@ 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(() -> { TaskManager.runTaskLaterAsync(new Runnable() {
@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());
@ -31,7 +32,8 @@ public class CommentManager {
if (value != null) { if (value != null) {
int num = 0; int num = 0;
for (PlotComment comment : value) { for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) { if (comment.timestamp > getTimestamp(player,
inbox.toString())) {
num++; num++;
} }
} }
@ -46,6 +48,7 @@ public class CommentManager {
} }
}); });
} }
}
}, 20); }, 20);
} }

View File

@ -43,6 +43,8 @@ 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);
@ -76,7 +78,11 @@ 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(() -> plot.teleportPlayer(player)); TaskManager.runTask(new Runnable() {
@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<>()); plotList.add(new ArrayList<Plot>());
} }
for (Plot plot : PlotSquared.get().getPlots()) { for (Plot plot : PlotSquared.get().getPlots()) {
@ -430,7 +430,7 @@ public class MainUtil {
count++; count++;
} }
} }
if (plot.getArea().equals(area)) { if (area != null && plot.getArea().equals(area)) {
count++; count++;
} }
if (alias != null && alias.equals(plot.getAlias())) { if (alias != null && alias.equals(plot.getAlias())) {
@ -622,13 +622,15 @@ public class MainUtil {
if (caption.s().isEmpty()) { if (caption.s().isEmpty()) {
return true; return true;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@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;
} }
@ -778,12 +780,14 @@ 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(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
int max = 10; int max = 10;
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES
.isEmpty()) {
max = 8; max = 8;
} }
String info1; String info;
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);
@ -794,12 +798,13 @@ public class MainUtil {
.format("%.1f", ratings[i]); .format("%.1f", ratings[i]);
prefix = ","; prefix = ",";
} }
info1 = newInfo.replaceAll("%rating%", rating); info = newInfo.replaceAll("%rating%", rating);
} else { } else {
info1 = newInfo.replaceAll("%rating%", info = newInfo.replaceAll("%rating%",
String.format("%.1f", plot.getAverageRating()) + '/' + max); String.format("%.1f", plot.getAverageRating()) + '/' + max);
} }
whenDone.run(info1); whenDone.run(info);
}
}); });
return; return;
} }
@ -810,9 +815,10 @@ public class MainUtil {
if (directory.exists()) { if (directory.exists()) {
File[] files = directory.listFiles(); File[] files = directory.listFiles();
if (null != files) { if (null != files) {
for (File file : files) { for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) { if (file.isDirectory()) {
deleteDirectory(file); deleteDirectory(files[i]);
} 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); TaskManager.runTask(() -> THIS.run());
}); });
} }
} }

View File

@ -21,8 +21,7 @@ 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 * Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the server
* server
*/ */
private long last; private long last;
private long secondLast; private long secondLast;
@ -82,7 +81,8 @@ public class GlobalBlockQueue {
return false; return false;
} }
running.set(true); running.set(true);
TaskManager.runTaskRepeat(() -> { TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) { if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) {
lastSuccess = System.currentTimeMillis(); lastSuccess = System.currentTimeMillis();
tasks(); tasks();
@ -127,6 +127,7 @@ 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;
} }
@ -167,7 +168,7 @@ public class GlobalBlockQueue {
public List<LocalBlockQueue> getAllQueues() { public List<LocalBlockQueue> getAllQueues() {
ArrayList<LocalBlockQueue> list = ArrayList<LocalBlockQueue> list =
new ArrayList<>(activeQueues.size() + inactiveQueues.size()); new ArrayList<LocalBlockQueue>(activeQueues.size() + inactiveQueues.size());
list.addAll(inactiveQueues); list.addAll(inactiveQueues);
list.addAll(activeQueues); list.addAll(activeQueues);
return list; return list;
@ -196,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<>(); ArrayList<Thread> threads = new ArrayList<Thread>();
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));
} }
@ -298,6 +299,6 @@ public class GlobalBlockQueue {
} }
public enum QueueStage { public enum QueueStage {
INACTIVE, ACTIVE, NONE INACTIVE, ACTIVE, NONE;
} }
} }

View File

@ -65,6 +65,7 @@ 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) {
@ -96,26 +97,28 @@ 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(() -> { TaskManager.runTask(new Runnable() {
@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");
PlotMessage msg = new PlotMessage() PlotMessage msg = new PlotMessage().text(
.text(num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ") num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ")
.color("$1").text(current.toString()).color("$2") .color("$1").text(current.toString()).color("$2")
.suggest("/plot list expired").tooltip("/plot list expired") .suggest("/plot list expired").tooltip("/plot list expired")
//.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired") //.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired")
.text("\n - ").color("$3").text("Delete this (/plot delete)") .text("\n - ").color("$3").text("Delete this (/plot delete)")
.color("$2").suggest("/plot delete").tooltip("/plot delete") .color("$2").suggest("/plot delete").tooltip("/plot delete")
.text("\n - ").color("$3").text("Remind later (/plot set keep 1d)") .text("\n - ").color("$3").text("Remind later (/plot set keep 1d)")
.color("$2").suggest("/plot set keep 1d").tooltip("/plot set keep 1d") .color("$2").suggest("/plot set keep 1d")
.text("\n - ").color("$3").text("Keep this (/plot set keep true)") .tooltip("/plot set keep 1d").text("\n - ").color("$3")
.color("$2").suggest("/plot set keep true") .text("Keep this (/plot set keep true)").color("$2")
.tooltip("/plot set keep true").text("\n - ").color("$3") .suggest("/plot set keep true").tooltip("/plot set keep true")
.text("Don't show me this").color("$2") .text("\n - ").color("$3").text("Don't show me this").color("$2")
.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 {
@ -216,7 +219,12 @@ 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);
queue.removeIf(expiryTask -> !expiryTask.applies(area)); Iterator<ExpiryTask> iter = queue.iterator();
while (iter.hasNext()) {
if (!iter.next().applies(area)) {
iter.remove();
}
}
return queue; return queue;
} }
@ -246,7 +254,7 @@ public class ExpireManager {
} }
this.running = 2; this.running = 2;
final ConcurrentLinkedDeque<Plot> plots = final ConcurrentLinkedDeque<Plot> plots =
new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots()); new ConcurrentLinkedDeque<Plot>(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;
@ -270,8 +278,11 @@ public class ExpireManager {
} }
for (ExpiryTask expiryTask : expired) { for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) { if (!expiryTask.needsAnalysis()) {
expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1), expiredTask.run(newPlot, new Runnable() {
expiryTask.requiresConfirmation()); @Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, expiryTask.requiresConfirmation());
return; return;
} }
} }
@ -280,19 +291,26 @@ public class ExpireManager {
@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 public void run(Boolean confirmation) {
expiredTask.run(newPlot, expiredTask.run(newPlot, new Runnable() {
() -> TaskManager.IMP.taskLaterAsync(task, 1), @Override public void run() {
confirmation); TaskManager.IMP.taskLaterAsync(task, 1);
} }
}, () -> { }, 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 = final Runnable doAnalysis = new Runnable() {
() -> HybridUtils.manager.analyzePlot(newPlot, handleAnalysis); @Override public void run() {
HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
}
};
PlotAnalysis analysis = newPlot.getComplexity(null); PlotAnalysis analysis = newPlot.getComplexity(null);
if (analysis != null) { if (analysis != null) {
@ -300,7 +318,11 @@ public class ExpireManager {
@Override public void run(Boolean value) { @Override public void run(Boolean value) {
doAnalysis.run(); doAnalysis.run();
} }
}, () -> TaskManager.IMP.taskLaterAsync(task, 1)); }, new Runnable() {
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
});
} else { } else {
doAnalysis.run(); doAnalysis.run();
} }
@ -308,11 +330,13 @@ public class ExpireManager {
} }
if (plots.isEmpty()) { if (plots.isEmpty()) {
ExpireManager.this.running = 3; ExpireManager.this.running = 3;
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(new Runnable() {
@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);
@ -328,19 +352,18 @@ 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<>() : plotsToDelete; return plotsToDelete == null ? new HashSet<Plot>() : plotsToDelete;
} }
public void deleteWithMessage(Plot plot, Runnable whenDone) { public void deleteWithMessage(Plot plot, Runnable whenDone) {

View File

@ -118,7 +118,8 @@ public class PlotAnalysis {
final AtomicInteger mi = new AtomicInteger(0); final AtomicInteger mi = new AtomicInteger(0);
Thread ratingAnalysis = new Thread(() -> { Thread ratingAnalysis = new Thread(new Runnable() {
@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);
@ -127,6 +128,7 @@ public class PlotAnalysis {
* 100); * 100);
PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]); PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]);
} }
}
}); });
ratingAnalysis.start(); ratingAnalysis.start();
@ -422,6 +424,9 @@ 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();
@ -433,6 +438,9 @@ 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) {
@ -459,13 +467,20 @@ public class PlotAnalysis {
* An optimized algorithm for ranking a very specific set of inputs<br> * An optimized algorithm for ranking a very specific set of inputs<br>
* - 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 interface UUIDWrapper { public abstract class UUIDWrapper {
UUID getUUID(PlotPlayer player); public abstract UUID getUUID(PlotPlayer player);
UUID getUUID(OfflinePlotPlayer player); public abstract UUID getUUID(OfflinePlotPlayer player);
UUID getUUID(String name); public abstract UUID getUUID(String name);
OfflinePlotPlayer getOfflinePlayer(UUID uuid); public abstract OfflinePlotPlayer getOfflinePlayer(UUID uuid);
OfflinePlotPlayer getOfflinePlayer(String name); public abstract OfflinePlotPlayer getOfflinePlayer(String name);
OfflinePlotPlayer[] getOfflinePlayers(); public abstract OfflinePlotPlayer[] getOfflinePlayers();
} }

View File

@ -84,6 +84,9 @@ 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,6 +40,10 @@ 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;
} }