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 =
new BukkitBlockRegistry(Material.values());
private int[] version;
private String pluginName;
@Getter private String pluginName;
@Getter private SingleWorldListener singleWorldListener;
private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false;
@ -112,9 +112,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return Bukkit.getVersion();
}
@Override public void onEnable() {
this.pluginName = getDescription().getName();
getServer().getName();
PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer);
@ -266,10 +266,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return getDescription().getVersion();
}
@Override public String getPluginName() {
return pluginName;
}
@Override public void registerCommands() {
final BukkitCommand bukkitCommand = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots");
@ -537,7 +533,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override @Nullable
public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
PlotSquared.log("DEFAULT WORLD GENERATOR RUN");
final IndependentPlotGenerator result;
if (id != null && id.equalsIgnoreCase("single")) {
result = new SingleWorldGenerator();

View File

@ -5,10 +5,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.*;
import org.bukkit.Statistic.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
@ -323,6 +320,34 @@ public class FancyMessage
return this;
}
/**
* Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
* <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.
* <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,45 +59,48 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false);
}
TaskManager.runTaskRepeat(() -> {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
continue;
}
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse =
chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse
.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
continue;
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap =
w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse = chunkMap.getClass()
.getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse
.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
continue;
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
}
toUnload.add(chunk);
}
toUnload.add(chunk);
}
}
if (toUnload.isEmpty()) {
return;
}
long start = System.currentTimeMillis();
for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
if (toUnload.isEmpty()) {
return;
}
chunk.unload(true, false);
long start = System.currentTimeMillis();
for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
return;
}
chunk.unload(true, false);
}
} catch (Throwable e) {
e.printStackTrace();
}
} catch (Throwable e) {
e.printStackTrace();
}
}, 1);
}
@ -108,7 +111,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
}
Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get()) {
if ((Boolean) field.get() == true) {
field.set(false);
if (chunk.isLoaded()) {
ignoreUnload = true;
@ -219,26 +222,9 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
private void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get();
Integer task = TaskManager.runTaskRepeat(() -> {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
long start = System.currentTimeMillis();
int i = 0;
while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) {
Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
@ -246,8 +232,29 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
chunk.unload(true, true);
return;
}
tiles[i].getBlock().setType(Material.AIR, false);
i++;
BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
long start = System.currentTimeMillis();
int i = 0;
while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
tiles[i].getBlock().setType(Material.AIR, false);
i++;
}
}
}, 5);
TaskManager.tasks.put(currentIndex, task);

View File

@ -42,7 +42,6 @@ import org.bukkit.help.HelpTopic;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.Directional;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
@ -673,9 +672,8 @@ import java.util.regex.Pattern;
if (passenger instanceof Player) {
final Player player = (Player) passenger;
// reset
if (moveTmp == null) {
if (moveTmp == null)
moveTmp = new PlayerMoveEvent(null, from, to);
}
moveTmp.setFrom(from);
moveTmp.setTo(to);
moveTmp.setCancelled(false);
@ -703,7 +701,7 @@ import java.util.regex.Pattern;
vehicle.eject();
vehicle.setVelocity(new Vector(0d, 0d, 0d));
vehicle.teleport(dest);
vehicle.addPassenger(player);
vehicle.setPassenger(player);
}
return;
}
@ -785,7 +783,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true;
return;
}
int border = area.getBorder();
Integer border = area.getBorder();
if (x2 > border && this.tmpTeleport) {
to.setX(x2 - 1);
this.tmpTeleport = false;
@ -848,7 +846,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true;
return;
}
int border = area.getBorder();
Integer border = area.getBorder();
if (z2 > border && this.tmpTeleport) {
to.setZ(z2 - 1);
this.tmpTeleport = false;
@ -866,9 +864,8 @@ import java.util.regex.Pattern;
}
@EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) {
if (event.isCancelled()) {
if (event.isCancelled())
return;
}
PlotPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer());
Location location = plotPlayer.getLocation();
@ -1085,9 +1082,8 @@ import java.util.regex.Pattern;
PlotArea area = location.getPlotArea();
if (area != null) {
Plot plot = area.getOwnedPlot(location);
if (plot != null && Flags.MOB_BREAK.isTrue(plot)) {
if (plot != null && Flags.MOB_BREAK.isTrue(plot))
return;
}
event.setCancelled(true);
}
}
@ -1454,11 +1450,11 @@ import java.util.regex.Pattern;
switch (type) {
case WATER_BUCKET:
case LAVA_BUCKET: {
if (event.getBlock().getType() == Material.DROPPER) {
if (event.getBlock().getType() == Material.DROPPER)
return;
}
BlockFace targetFace =
((Directional) event.getBlock().getState().getData()).getFacing();
((org.bukkit.material.Dispenser) event.getBlock().getState().getData())
.getFacing();
Location location =
BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation());
if (location.isPlotRoad()) {
@ -1579,9 +1575,8 @@ import java.util.regex.Pattern;
switch (newItem.getType()) {
case LEGACY_BANNER:
case PLAYER_HEAD:
if (newMeta != null) {
if (newMeta != null)
break;
}
default:
return;
}
@ -1597,13 +1592,11 @@ import java.util.regex.Pattern;
switch (stateType) {
case LEGACY_STANDING_BANNER:
case LEGACY_WALL_BANNER:
if (itemType == Material.LEGACY_BANNER) {
if (itemType == Material.LEGACY_BANNER)
break;
}
case LEGACY_SKULL:
if (itemType == Material.LEGACY_SKULL_ITEM) {
if (itemType == Material.LEGACY_SKULL_ITEM)
break;
}
default:
return;
}
@ -2571,11 +2564,11 @@ import java.util.regex.Pattern;
}
}
@EventHandler(priority = EventPriority.HIGHEST)
@SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange =
new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
EntityDamageByEntityEvent eventChange = null;
eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
onEntityDamageByEntityEvent(eventChange);
if (eventChange.isCancelled()) {
event.setCancelled(true);

View File

@ -10,7 +10,6 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
@ -37,43 +36,45 @@ import java.util.UUID;
private static final HashMap<UUID, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override public void run() {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
}
}
}
}
}
if (!feedRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
if (!feedRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
}
}
}
}
@ -104,7 +105,7 @@ import java.util.UUID;
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Entity player = event.getEntity();
Player player = (Player) event.getEntity();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;

View File

@ -33,8 +33,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
this.done = classChunk.getField("done").getRealField();
this.lit = classChunk.getField("lit").getRealField();
this.s = classChunk.getField("s").getRealField();
} catch (NoSuchFieldException exception) {
exception.printStackTrace();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
Bukkit.getPluginManager().registerEvents(this, plugin);
}

View File

@ -135,11 +135,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
Horse horse = (Horse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
if (horse instanceof ChestedHorse) {
this.horse.chest = ((ChestedHorse) horse).isCarryingChest();
} else {
this.horse.chest = false;
}
this.horse.chest = horse.isCarryingChest();
this.horse.variant = horse.getVariant();
this.horse.style = horse.getStyle();
this.horse.color = horse.getColor();
@ -179,12 +175,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return;
// END AGEABLE //
case GUARDIAN:
//todo no longer works (possible exception thrown)
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity);
return;
case SKELETON:
//todo no longer works (possible exception thrown)
this.dataByte = getOrdinal(Skeleton.SkeletonType.values(),
((Skeleton) entity).getSkeletonType());
storeLiving((LivingEntity) entity);
@ -430,7 +424,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity;
}
if (this.base.passenger != null) {
entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
try {
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) {
}
}
if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall);
@ -515,10 +512,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case HORSE:
Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump);
if (horse instanceof ChestedHorse && this.horse.chest) {
((ChestedHorse) horse).setCarryingChest(true);
}
//todo broken in 1.13 possible exception thrown
horse.setCarryingChest(this.horse.chest);
horse.setVariant(this.horse.variant);
horse.setStyle(this.horse.style);
horse.setColor(this.horse.color);
@ -565,15 +559,12 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity;
case GUARDIAN:
if (this.dataByte != 0) {
//todo broken in 1.13 possible exception thrown
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity);
return entity;
case SKELETON:
if (this.dataByte != 0) {
//todo broken in 1.13 possible exception thrown
((Skeleton) entity)
.setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]);
}

View File

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

View File

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

View File

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

View File

@ -101,6 +101,10 @@ public final class BukkitEventUtil extends EventUtil {
new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner));
}
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);

View File

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

View File

@ -83,7 +83,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
// int id = item.getTypeId();
Material id = item.getType();
//short data = item.getDurability();
short data = item.getDurability();
int amount = item.getAmount();
String name = null;
String[] lore = null;
@ -94,7 +94,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
if (meta.hasLore()) {
List<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);

View File

@ -26,8 +26,8 @@ import java.util.Map.Entry;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
/**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy
* NMS).
* An utility that can be used to send chunks, rather than using bukkit code
* to do so (uses heavy NMS).
*/
public class SendChunk {
@ -118,17 +118,20 @@ public class SendChunk {
}
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(() -> {
try {
chunk.unload(true, false);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk
.getZ());
PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
TaskManager.runTask(new Runnable() {
@Override public void run() {
try {
chunk.unload(true, false);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";"
+ chunk.getZ());
PlotSquared
.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
}
});
}

View File

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

View File

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

View File

@ -47,196 +47,204 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} else {
world = worlds.get(0).getName();
}
TaskManager.runTaskAsync(() -> {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
List<String> lines =
Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
if (line.isEmpty()) {
continue;
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
List<String> lines =
Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
if (line.isEmpty()) {
continue;
}
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.isEmpty() || (name.length() > 16) || !StringMan
.isAlphanumericUnd(name)) {
continue;
}
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
if (uuid == null) {
continue;
}
UUIDHandler.add(new StringWrapper(name), uuid);
} catch (Exception e2) {
e2.printStackTrace();
}
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.isEmpty() || (name.length() > 16) || !StringMan
.isAlphanumericUnd(name)) {
continue;
}
} catch (IOException e) {
e.printStackTrace();
}
}
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!");
File playerDataFolder =
new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerDataFolder, current);
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
}
toAdd.put(new StringWrapper(name), uuid);
}
}
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current);
}
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
if (uuid == null) {
continue;
}
UUIDHandler.add(new StringWrapper(name), uuid);
} catch (Exception e2) {
e2.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
add(toAdd);
if (all.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
} else {
PlotSquared.debug("Failed to cache: " + all.size()
+ " uuids - slowly processing all files");
}
}
}
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!");
File playerDataFolder = new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerDataFolder, current);
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
HashSet<String> worlds = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
File playerDataFolder = null;
for (String worldName : worlds) {
// Getting UUIDs
playerDataFolder =
new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception ignored) {
PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current);
}
}
break;
}
// Getting names
File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", ""));
}
break;
}
}
for (UUID uuid : uuids) {
try {
File file =
new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
if (!file.exists()) {
continue;
}
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase()
.equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
}
toAdd.put(new StringWrapper(name), uuid);
}
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
}
toAdd.put(wrap, uuid);
}
}
} catch (Exception ignored) {
PlotSquared
.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid);
}
if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper
.getOfflinePlayers()) {
long last = op.getLastPlayed();
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
}
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current);
}
}
}
add(toAdd);
if (all.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
} else {
PlotSquared.debug(
"Failed to cache: " + all.size() + " uuids - slowly processing all files");
if (whenDone != null) {
whenDone.run();
}
}
HashSet<String> worlds1 = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
File playerDataFolder = null;
for (String worldName : worlds1) {
// Getting UUIDs
playerDataFolder = new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception ignored) {
PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current);
}
}
break;
}
// Getting names
File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", ""));
}
break;
}
}
for (UUID uuid : uuids) {
try {
File file =
new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
if (!file.exists()) {
continue;
}
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase()
.equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
}
}
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
}
toAdd.put(wrap, uuid);
}
}
} catch (Exception ignored) {
PlotSquared
.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid);
}
if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) {
long last = op.getLastPlayed();
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
}
}
}
}
add(toAdd);
if (whenDone != null) {
whenDone.run();
}
});
return true;
}
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(() -> {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}
});
}
}

View File

@ -16,11 +16,10 @@ import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
public class OfflineUUIDWrapper implements UUIDWrapper {
public class OfflineUUIDWrapper extends UUIDWrapper {
private final Object[] arg = new Object[0];
private Method getOnline = null;
@ -60,15 +59,18 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
return new BukkitOfflinePlayer(op);
}
}
return Arrays.stream(Bukkit.getOfflinePlayers())
.filter(player -> getUUID(player).equals(uuid)).findFirst()
.map(BukkitOfflinePlayer::new).orElse(null);
for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player);
}
}
return null;
}
public Player[] getOnlinePlayers() {
if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[0]);
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
}
try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -77,13 +79,13 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
} else {
@SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players;
return p.toArray(new Player[0]);
return p.toArray(new Player[p.size()]);
}
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
PlotSquared.debug("Failed to resolve online players");
this.getOnline = null;
Collection<? 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() {
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) {

View File

@ -71,82 +71,96 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(() -> {
try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try {
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username =
new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
}
}
}
add(toAdd);
// This should be called as long as there are some unknown plots
final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) {
toFetch.add(u);
add(toAdd);
// This should be called as long as there are some unknown plots
final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) {
toFetch.add(u);
}
}
}
if (toFetch.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
}
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(() -> {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
if (toFetch.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
}
FileUUIDHandler fileHandler =
new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
if (whenDone != null) {
whenDone.run();
}
return;
}
TaskManager.runTaskAsync(() -> {
while (!toFetch.isEmpty()) {
try {
for (int i = 0; i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid.toString()
.replace("-", "")).openConnection();
try (InputStream con = connection.getInputStream()) {
InputStreamReader reader = new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
String name = (String) response.get("name");
if (name != null) {
add(new StringWrapper(name), uuid);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
while (!toFetch.isEmpty()) {
try {
for (int i = 0;
i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection =
(HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid
.toString().replace("-", ""))
.openConnection();
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
String name = (String) response.get("name");
if (name != null) {
add(new StringWrapper(name), uuid);
}
}
connection.disconnect();
}
} catch (IOException | ParseException e) {
PlotSquared.debug(
"Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)");
}
try {
Thread.sleep(INTERVAL * 50);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
connection.disconnect();
if (whenDone != null) {
whenDone.run();
}
return;
}
} catch (IOException | ParseException e) {
PlotSquared.debug(
"Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)");
}
try {
Thread.sleep(INTERVAL * 50);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
});
}
if (whenDone != null) {
whenDone.run();
}
return;
});
});
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
@ -158,32 +172,34 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (ifFetch == null) {
return;
}
TaskManager.runTaskAsync(() -> {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String body = JSONArray.toJSONString(Collections.singletonList(name));
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name1 = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
} catch (IOException | ParseException e) {
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String body = JSONArray.toJSONString(Collections.singletonList(name));
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
TaskManager.runTask(ifFetch);
}
TaskManager.runTask(ifFetch);
});
}
@ -199,15 +215,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PlotSquared.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PlotSquared
.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
e.printStackTrace();
}
}
});
return true;
@ -220,16 +239,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
*/
@Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name);
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PlotSquared
.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) {
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PlotSquared.debug(
C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}

View File

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

View File

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

View File

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

View File

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

View File

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

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.MemoryConfiguration;
import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.StandardCharsets;
@ -83,7 +82,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void load(@Nonnull File file) throws IOException, InvalidConfigurationException {
public void load(File file) throws IOException, InvalidConfigurationException {
FileInputStream stream = new FileInputStream(file);

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because one or more lines are too long

View File

@ -104,34 +104,36 @@ import java.util.Set;
final String path =
"worlds." + area.worldname + ".areas." + area.id + '-'
+ object.min + '-' + object.max;
Runnable run = () -> {
if (offsetX != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX);
}
if (offsetZ != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.z", offsetZ);
}
final String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
PlotSquared.get().loadWorld(world, null);
C.SETUP_FINISHED.send(player);
player.teleport(WorldUtil.IMP.getSpawn(world));
if (area.TERRAIN != 3) {
ChunkManager.largeRegionTask(world, region,
new RunnableVal<ChunkLoc>() {
@Override public void run(ChunkLoc value) {
AugmentedUtils
.generate(world, value.x, value.z,
null);
}
}, null);
Runnable run = new Runnable() {
@Override public void run() {
if (offsetX != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX);
}
if (offsetZ != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.z", offsetZ);
}
final String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
PlotSquared.get().loadWorld(world, null);
C.SETUP_FINISHED.send(player);
player.teleport(WorldUtil.IMP.getSpawn(world));
if (area.TERRAIN != 3) {
ChunkManager.largeRegionTask(world, region,
new RunnableVal<ChunkLoc>() {
@Override public void run(ChunkLoc value) {
AugmentedUtils
.generate(world, value.x, value.z,
null);
}
}, null);
}
} else {
MainUtil.sendMessage(player,
"An error occurred while creating the world: "
+ area.worldname);
}
} else {
MainUtil.sendMessage(player,
"An error occurred while creating the world: "
+ area.worldname);
}
};
if (hasConfirmation(player)) {
@ -226,30 +228,32 @@ import java.util.Set;
C.SETUP_WORLD_TAKEN.send(player, pa.worldname);
return false;
}
Runnable run = () -> {
String path = "worlds." + pa.worldname;
if (!PlotSquared.get().worlds.contains(path)) {
PlotSquared.get().worlds.createSection(path);
}
ConfigurationSection section =
PlotSquared.get().worlds.getConfigurationSection(path);
pa.saveConfiguration(section);
pa.loadConfiguration(section);
object.plotManager = PlotSquared.imp().getPluginName();
object.setupGenerator = PlotSquared.imp().getPluginName();
String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
C.SETUP_FINISHED.send(player);
player.teleport(WorldUtil.IMP.getSpawn(world));
} else {
MainUtil.sendMessage(player,
"An error occurred while creating the world: "
+ pa.worldname);
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
Runnable run = new Runnable() {
@Override public void run() {
String path = "worlds." + pa.worldname;
if (!PlotSquared.get().worlds.contains(path)) {
PlotSquared.get().worlds.createSection(path);
}
ConfigurationSection section =
PlotSquared.get().worlds.getConfigurationSection(path);
pa.saveConfiguration(section);
pa.loadConfiguration(section);
object.plotManager = PlotSquared.imp().getPluginName();
object.setupGenerator = PlotSquared.imp().getPluginName();
String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
C.SETUP_FINISHED.send(player);
player.teleport(WorldUtil.IMP.getSpawn(world));
} else {
MainUtil.sendMessage(player,
"An error occurred while creating the world: "
+ pa.worldname);
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
}
}
};
if (hasConfirmation(player)) {
@ -418,7 +422,11 @@ import java.util.Set;
@Override public void run(ChunkLoc value) {
AugmentedUtils.generate(area.worldname, value.x, value.z, null);
}
}, () -> player.sendMessage("Regen complete"));
}, new Runnable() {
@Override public void run() {
player.sendMessage("Regen complete");
}
});
return true;
}
case "goto":

View File

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

View File

@ -301,7 +301,6 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
@ -347,7 +346,6 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
@ -406,7 +404,6 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster;
if (args.length == 2) {
@ -442,6 +439,7 @@ import java.util.UUID;
PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) {
PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) {
player.getLocation().getWorld();
plot.unclaim();
}
}
@ -463,7 +461,6 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
@ -536,7 +533,6 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster;
if (args.length == 2) {
@ -584,7 +580,6 @@ import java.util.UUID;
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {

View File

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

View File

@ -30,18 +30,25 @@ import java.util.Map.Entry;
public static void insertPlots(final SQLManager manager, final List<Plot> plots,
final PlotPlayer player) {
TaskManager.runTaskAsync(() -> {
try {
ArrayList<Plot> ps = new ArrayList<>(plots);
MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, () -> {
MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close();
});
} catch (Exception e) {
MainUtil
.sendMessage(player, "Failed to insert plot objects, see stacktrace for info");
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try {
ArrayList<Plot> ps = new ArrayList<>();
for (Plot p : plots) {
ps.add(p);
}
MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close();
}
});
} catch (Exception e) {
MainUtil.sendMessage(player,
"Failed to insert plot objects, see stacktrace for info");
e.printStackTrace();
}
}
});
}
@ -123,13 +130,20 @@ import java.util.Map.Entry;
plots.add(plot);
}
} else {
HashMap<PlotId, Plot> plotmap = PlotSquared.get().plots_tmp
.computeIfAbsent(areaname, k -> new HashMap<>());
HashMap<PlotId, Plot> plotmap =
PlotSquared.get().plots_tmp.get(areaname);
if (plotmap == null) {
plotmap = new HashMap<>();
PlotSquared.get().plots_tmp.put(areaname, plotmap);
}
plotmap.putAll(entry.getValue());
}
}
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&6Database conversion finished!"));
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Database conversion finished!");
}
});
return true;
case "mysql":
if (args.length < 6) {

View File

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

View File

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

View File

@ -60,9 +60,9 @@ public class Merge extends SubCommand {
}
final PlotArea plotArea = plot.getArea();
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 double price = priceExr.evaluate((double) size);
final double price = priceExr == null ? 0d : priceExr.evaluate((double) size);
if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d
&& EconHandler.manager.getMoney(player) < price) {
sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price));

View File

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

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.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot",
usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO,
@ -24,23 +22,25 @@ import java.util.UUID;
switch (args[0].toLowerCase()) {
case "next": {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getBasePlots());
plots.sort((p1, p2) -> {
double v1 = 0;
if (!p1.getRatings().isEmpty()) {
for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
v1 -= 11 - entry.getValue().getAverageRating();
Collections.sort(plots, new Comparator<Plot>() {
@Override public int compare(Plot p1, Plot p2) {
double v1 = 0;
if (!p1.getRatings().isEmpty()) {
for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
v1 -= 11 - entry.getValue().getAverageRating();
}
}
}
double v2 = 0;
if (!p2.getRatings().isEmpty()) {
for (Entry<UUID, Rating> entry : p2.getRatings().entrySet()) {
v2 -= 11 - entry.getValue().getAverageRating();
double v2 = 0;
if (!p2.getRatings().isEmpty()) {
for (Entry<UUID, Rating> entry : p2.getRatings().entrySet()) {
v2 -= 11 - entry.getValue().getAverageRating();
}
}
if (v1 == v2) {
return -0;
}
return v2 > v1 ? 1 : -1;
}
if (v1 == v2) {
return -0;
}
return v2 > v1 ? 1 : -1;
});
UUID uuid = player.getUUID();
for (Plot p : plots) {
@ -123,7 +123,7 @@ import java.util.UUID;
return true;
}
};
inventory.setItem(0, new PlotItemStack("minecraft:brown_wool", 0, "0/8"));
inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8"));
inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8"));
inventory.setItem(2, new PlotItemStack(35, (short) 1, 2, "2/8"));
inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8"));
@ -137,9 +137,11 @@ import java.util.UUID;
};
if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(() -> {
plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run();
}
});
return true;
}
@ -165,22 +167,26 @@ import java.util.UUID;
return false;
}
final UUID uuid = player.getUUID();
final Runnable run = () -> {
if (plot.getRatings().containsKey(uuid)) {
sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
return;
}
Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating));
if (result != null) {
plot.addRating(uuid, result);
sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
final Runnable run = new Runnable() {
@Override public void run() {
if (plot.getRatings().containsKey(uuid)) {
sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
return;
}
Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating));
if (result != null) {
plot.addRating(uuid, result);
sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
}
}
};
if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(() -> {
plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run();
}
});
return true;
}

View File

@ -143,6 +143,14 @@ public interface AbstractDB {
*/
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.
*

View File

@ -13,7 +13,7 @@ import java.util.*;
* Database Functions
* - These functions do not update the local plot objects and only make changes to the DB
*/
@SuppressWarnings("deprecation") public class DBFunc {
public class DBFunc {
/**
* The "global" uuid.
*/
@ -298,6 +298,17 @@ import java.util.*;
DBFunc.dbManager.setFlags(plot, flags);
}
public static void setFlags(PlotCluster cluster, HashMap<Flag<?>, Object> flags) {
if (dbManager == null) {
return;
}
DBFunc.dbManager.setFlags(cluster, flags);
}
/**
* @param plot
* @param alias
*/
public static void setAlias(Plot plot, String alias) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -319,6 +330,10 @@ import java.util.*;
DBFunc.dbManager.purge(area, plotIds);
}
/**
* @param plot
* @param position
*/
public static void setPosition(Plot plot, String position) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -326,6 +341,10 @@ import java.util.*;
DBFunc.dbManager.setPosition(plot, position);
}
/**
* @param plot
* @param comment
*/
public static void removeComment(Plot plot, PlotComment comment) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -340,6 +359,10 @@ import java.util.*;
DBFunc.dbManager.clearInbox(plot, inbox);
}
/**
* @param plot
* @param comment
*/
public static void setComment(Plot plot, PlotComment comment) {
if (plot != null && plot.temp == -1 || dbManager == null) {
return;
@ -347,6 +370,9 @@ import java.util.*;
DBFunc.dbManager.setComment(plot, comment);
}
/**
* @param plot
*/
public static void getComments(Plot plot, String inbox,
RunnableVal<List<PlotComment>> whenDone) {
if (plot != null && plot.temp == -1 || dbManager == null) {
@ -355,6 +381,10 @@ import java.util.*;
DBFunc.dbManager.getComments(plot, inbox, whenDone);
}
/**
* @param plot
* @param uuid
*/
public static void removeTrusted(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -362,6 +392,10 @@ import java.util.*;
DBFunc.dbManager.removeTrusted(plot, uuid);
}
/**
* @param cluster
* @param uuid
*/
public static void removeHelper(PlotCluster cluster, UUID uuid) {
if (dbManager == null) {
return;
@ -369,6 +403,9 @@ import java.util.*;
DBFunc.dbManager.removeHelper(cluster, uuid);
}
/**
* @param cluster
*/
public static void createCluster(PlotCluster cluster) {
if (dbManager == null) {
return;
@ -376,6 +413,11 @@ import java.util.*;
DBFunc.dbManager.createCluster(cluster);
}
/**
* @param current
* @param min
* @param max
*/
public static void resizeCluster(PlotCluster current, PlotId min, PlotId max) {
if (dbManager == null) {
return;
@ -383,6 +425,10 @@ import java.util.*;
DBFunc.dbManager.resizeCluster(current, min, max);
}
/**
* @param plot
* @param uuid
*/
public static void removeMember(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -390,6 +436,10 @@ import java.util.*;
DBFunc.dbManager.removeMember(plot, uuid);
}
/**
* @param cluster
* @param uuid
*/
public static void removeInvited(PlotCluster cluster, UUID uuid) {
if (dbManager == null) {
return;
@ -397,6 +447,10 @@ import java.util.*;
DBFunc.dbManager.removeInvited(cluster, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void setTrusted(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -411,6 +465,10 @@ import java.util.*;
DBFunc.dbManager.setHelper(cluster, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void setMember(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -425,6 +483,10 @@ import java.util.*;
DBFunc.dbManager.setInvited(cluster, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void removeDenied(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -432,6 +494,10 @@ import java.util.*;
DBFunc.dbManager.removeDenied(plot, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void setDenied(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;

View File

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

View File

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

View File

@ -14,7 +14,6 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.google.common.base.Charsets;
import javax.annotation.Nonnull;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ -49,7 +48,13 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
public volatile Queue<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;
/**
@ -57,7 +62,10 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
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;
// Private
@ -67,7 +75,10 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* Constructor
*
* @param p prefix
* @param database
* @param p prefix
* @throws SQLException
* @throws ClassNotFoundException
*/
public SQLManager(final Database database, String p, boolean debug)
throws SQLException, ClassNotFoundException {
@ -110,40 +121,42 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (SQLException e) {
e.printStackTrace();
}
TaskManager.runTaskAsync(() -> {
long last = System.currentTimeMillis();
while (true) {
if (SQLManager.this.closed) {
break;
}
boolean hasTask =
!globalTasks.isEmpty() || !playerTasks.isEmpty() || !plotTasks.isEmpty()
|| !clusterTasks.isEmpty();
if (hasTask) {
if (SQLManager.this.mySQL && System.currentTimeMillis() - last > 550000
|| !isValid()) {
last = System.currentTimeMillis();
reconnect();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
long last = System.currentTimeMillis();
while (true) {
if (SQLManager.this.closed) {
break;
}
if (!sendBatch()) {
try {
if (!getNotifyTasks().isEmpty()) {
for (Runnable task : getNotifyTasks()) {
TaskManager.runTask(task);
boolean hasTask =
!globalTasks.isEmpty() || !playerTasks.isEmpty() || !plotTasks.isEmpty()
|| !clusterTasks.isEmpty();
if (hasTask) {
if (SQLManager.this.mySQL && System.currentTimeMillis() - last > 550000
|| !isValid()) {
last = System.currentTimeMillis();
reconnect();
}
if (!sendBatch()) {
try {
if (!getNotifyTasks().isEmpty()) {
for (Runnable task : getNotifyTasks()) {
TaskManager.runTask(task);
}
getNotifyTasks().clear();
}
getNotifyTasks().clear();
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.sleep(50);
}
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
@ -183,9 +196,15 @@ import java.util.concurrent.atomic.AtomicInteger;
return this.notifyTasks;
}
public synchronized void addPlotTask(@Nonnull Plot plot, UniqueStatement task) {
Queue<UniqueStatement> tasks =
this.plotTasks.computeIfAbsent(plot, plot1 -> new ConcurrentLinkedQueue<>());
public synchronized void addPlotTask(Plot plot, UniqueStatement task) {
if (plot == null) {
plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE));
}
Queue<UniqueStatement> tasks = this.plotTasks.get(plot);
if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
this.plotTasks.put(plot, tasks);
}
if (task == null) {
task = new UniqueStatement(String.valueOf(plot.hashCode())) {
@ -211,8 +230,11 @@ import java.util.concurrent.atomic.AtomicInteger;
if (uuid == null) {
return;
}
Queue<UniqueStatement> tasks =
this.playerTasks.computeIfAbsent(uuid, uuid1 -> new ConcurrentLinkedQueue<>());
Queue<UniqueStatement> tasks = this.playerTasks.get(uuid);
if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
this.playerTasks.put(uuid, tasks);
}
if (task == null) {
task = new UniqueStatement(String.valueOf(uuid.hashCode())) {
@ -235,8 +257,11 @@ import java.util.concurrent.atomic.AtomicInteger;
}
public synchronized void addClusterTask(PlotCluster cluster, UniqueStatement task) {
Queue<UniqueStatement> tasks = this.clusterTasks
.computeIfAbsent(cluster, plotCluster -> new ConcurrentLinkedQueue<>());
Queue<UniqueStatement> tasks = this.clusterTasks.get(cluster);
if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
this.clusterTasks.put(cluster, tasks);
}
if (task == null) {
task = new UniqueStatement(String.valueOf(cluster.hashCode())) {
@ -490,74 +515,92 @@ import java.util.concurrent.atomic.AtomicInteger;
}
@Override public void createPlotsAndData(final List<Plot> myList, final Runnable whenDone) {
addGlobalTask(() -> {
try {
// Create the plots
createPlots(myList, () -> {
try {
// Creating datastructures
HashMap<PlotId, Plot> plotMap = new HashMap<>();
for (Plot plot : myList) {
plotMap.put(plot.getId(), plot);
}
ArrayList<SettingsPair> settings = new ArrayList<>();
final ArrayList<UUIDPair> helpers = new ArrayList<>();
final ArrayList<UUIDPair> trusted = new ArrayList<>();
final ArrayList<UUIDPair> denied = new ArrayList<>();
addGlobalTask(new Runnable() {
@Override public void run() {
try {
// Create the plots
createPlots(myList, new Runnable() {
@Override public void run() {
try {
// Creating datastructures
HashMap<PlotId, Plot> plotMap = new HashMap<>();
for (Plot plot : myList) {
plotMap.put(plot.getId(), plot);
}
ArrayList<SettingsPair> settings = new ArrayList<>();
final ArrayList<UUIDPair> helpers = new ArrayList<>();
final ArrayList<UUIDPair> trusted = new ArrayList<>();
final ArrayList<UUIDPair> denied = new ArrayList<>();
// Populating structures
try (PreparedStatement stmt = SQLManager.this.connection
.prepareStatement(SQLManager.this.GET_ALL_PLOTS);
ResultSet result = stmt.executeQuery()) {
while (result.next()) {
int id = result.getInt("id");
int x = result.getInt("plot_id_x");
int y = result.getInt("plot_id_z");
PlotId plotId = new PlotId(x, y);
Plot plot = plotMap.get(plotId);
if (plot != null) {
settings.add(new SettingsPair(id, plot.getSettings()));
for (UUID uuid : plot.getDenied()) {
denied.add(new UUIDPair(id, uuid));
// Populating structures
try (PreparedStatement stmt = SQLManager.this.connection
.prepareStatement(SQLManager.this.GET_ALL_PLOTS);
ResultSet result = stmt.executeQuery()) {
while (result.next()) {
int id = result.getInt("id");
int x = result.getInt("plot_id_x");
int y = result.getInt("plot_id_z");
PlotId plotId = new PlotId(x, y);
Plot plot = plotMap.get(plotId);
if (plot != null) {
settings.add(new SettingsPair(id, plot.getSettings()));
for (UUID uuid : plot.getDenied()) {
denied.add(new UUIDPair(id, uuid));
}
for (UUID uuid : plot.getMembers()) {
trusted.add(new UUIDPair(id, uuid));
}
for (UUID uuid : plot.getTrusted()) {
helpers.add(new UUIDPair(id, uuid));
}
}
}
for (UUID uuid : plot.getMembers()) {
trusted.add(new UUIDPair(id, uuid));
}
for (UUID uuid : plot.getTrusted()) {
helpers.add(new UUIDPair(id, uuid));
}
createSettings(settings, new Runnable() {
@Override public void run() {
createTiers(helpers, "helpers", new Runnable() {
@Override public void run() {
createTiers(trusted, "trusted", new Runnable() {
@Override public void run() {
createTiers(denied, "denied",
new Runnable() {
@Override public void run() {
try {
SQLManager.this.connection
.commit();
} catch (SQLException e) {
e.printStackTrace();
}
if (whenDone != null) {
whenDone.run();
}
}
});
}
});
}
});
}
});
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
try {
SQLManager.this.connection.commit();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
createSettings(settings, () -> createTiers(helpers, "helpers",
() -> createTiers(trusted, "trusted",
() -> createTiers(denied, "denied", () -> {
try {
SQLManager.this.connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
if (whenDone != null) {
whenDone.run();
}
}))));
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
try {
SQLManager.this.connection.commit();
} catch (SQLException e1) {
e1.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
try {
SQLManager.this.connection.commit();
} catch (SQLException e1) {
e1.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
try {
SQLManager.this.connection.commit();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
@ -886,7 +929,11 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(1, pair.id);
}
};
addGlobalTask(() -> setBulk(myList, mod, whenDone));
addGlobalTask(new Runnable() {
@Override public void run() {
setBulk(myList, mod, whenDone);
}
});
}
public void createEmptySettings(final ArrayList<Integer> myList, final Runnable whenDone) {
@ -930,7 +977,11 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(1, id);
}
};
addGlobalTask(() -> setBulk(myList, mod, whenDone));
addGlobalTask(new Runnable() {
@Override public void run() {
setBulk(myList, mod, whenDone);
}
});
}
public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) {
@ -975,16 +1026,14 @@ import java.util.concurrent.atomic.AtomicInteger;
+ "plot_settings`(`plot_plot_id`) VALUES(?)");
}
});
if (success != null) {
if (success != null)
addNotifyTask(success);
}
return;
}
}
}
if (failure != null) {
if (failure != null)
failure.run();
}
}
});
}
@ -1046,6 +1095,8 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* Create tables.
*
* @throws SQLException
*/
@Override public void createTables() throws SQLException {
String[] tables =
@ -1294,6 +1345,8 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* Delete a plot.
*
* @param plot
*/
@Override public void delete(final Plot plot) {
PlotSquared.debug(
@ -1319,6 +1372,9 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* Create plot settings
*
* @param id
* @param plot
*/
@Override public void createPlotSettings(final int id, Plot plot) {
PlotSquared.debug(
@ -1554,12 +1610,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ConfigurationSection areaSection =
worldSection.getConfigurationSection(worldKey + ".areas");
if (areaSection != null) {
areaSection.getKeys(false).forEach(s -> {
String[] split = s.split("(?<![;])-");
for (String areaKey : areaSection.getKeys(false)) {
String[] split = areaKey.split("(?<![;])-");
if (split.length == 3) {
areas.add(worldKey + ';' + split[0]);
}
});
}
}
}
}
@ -1572,7 +1628,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
try (Statement statement = this.connection.createStatement()) {
int id;
String owner;
String o;
UUID user;
try (ResultSet resultSet = statement.executeQuery(
"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");
user = uuids.computeIfAbsent(owner, s -> {
o = resultSet.getString("owner");
user = uuids.get(o);
if (user == null) {
try {
return UUID.fromString(s);
} catch (IllegalArgumentException ignored) {
user = UUID.fromString(o);
} catch (IllegalArgumentException e) {
if (Settings.UUID.FORCE_LOWERCASE) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + s.toLowerCase())
user = UUID.nameUUIDFromBytes(
("OfflinePlayer:" + o.toLowerCase())
.getBytes(Charsets.UTF_8));
} else {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + s).getBytes(Charsets.UTF_8));
user = UUID.nameUUIDFromBytes(
("OfflinePlayer:" + o).getBytes(Charsets.UTF_8));
}
}
});
uuids.put(o, user);
}
long time;
try {
Timestamp timestamp = resultSet.getTimestamp("timestamp");
@ -1627,12 +1685,12 @@ import java.util.concurrent.atomic.AtomicInteger;
time = System.currentTimeMillis() + id;
}
}
Plot plot = new Plot(plot_id, user, new HashSet<>(), new HashSet<>(),
new HashSet<>(), "", null, null, null,
Plot p = new Plot(plot_id, user, new HashSet<UUID>(), new HashSet<UUID>(),
new HashSet<UUID>(), "", null, null, null,
new boolean[] {false, false, false, false}, time, id);
HashMap<PlotId, Plot> map = newPlots.get(areaid);
if (map != null) {
Plot last = map.put(plot.getId(), plot);
Plot last = map.put(p.getId(), p);
if (last != null) {
if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(last.temp);
@ -1645,9 +1703,9 @@ import java.util.concurrent.atomic.AtomicInteger;
} else {
map = new HashMap<>();
newPlots.put(areaid, map);
map.put(plot.getId(), plot);
map.put(p.getId(), p);
}
plots.put(id, plot);
plots.put(id, p);
}
deleteRows(toDelete, this.prefix + "plot", "id");
}
@ -1658,8 +1716,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) {
id = r.getInt("plot_plot_id");
owner = r.getString("player");
user = uuids.computeIfAbsent(owner, UUID::fromString);
o = r.getString("player");
user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id);
if (plot != null) {
plot.getSettings().getRatings().put(user, r.getInt("rating"));
@ -1683,8 +1745,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) {
id = r.getInt("plot_plot_id");
owner = r.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString);
o = r.getString("user_uuid");
user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id);
if (plot != null) {
plot.getTrusted().add(user);
@ -1707,8 +1773,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) {
id = r.getInt("plot_plot_id");
owner = r.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString);
o = r.getString("user_uuid");
user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id);
if (plot != null) {
plot.getMembers().add(user);
@ -1731,8 +1801,12 @@ import java.util.concurrent.atomic.AtomicInteger;
ArrayList<Integer> toDelete = new ArrayList<>();
while (r.next()) {
id = r.getInt("plot_plot_id");
owner = r.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString);
o = r.getString("user_uuid");
user = uuids.get(o);
if (user == null) {
user = UUID.fromString(o);
uuids.put(o, user);
}
Plot plot = plots.get(id);
if (plot != null) {
plot.getDenied().add(user);
@ -1771,7 +1845,7 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (Exception ignored) {
}
}
int m = resultSet.getInt("merged");
Integer m = resultSet.getInt("merged");
boolean[] merged = new boolean[4];
for (int i = 0; i < 4; i++) {
merged[3 - i] = (m & 1 << i) != 0;
@ -1962,98 +2036,103 @@ import java.util.concurrent.atomic.AtomicInteger;
* Purge all plots with the following database IDs
*/
@Override public void purgeIds(final Set<Integer> uniqueIds) {
addGlobalTask(() -> {
if (!uniqueIds.isEmpty()) {
try {
ArrayList<Integer> uniqueIdsList = new ArrayList<>(uniqueIds);
String stmt_prefix = "";
int size = uniqueIdsList.size();
int packet = 990;
int amount = size / packet;
int count = 0;
int last = -1;
for (int j = 0; j <= amount; j++) {
PlotSquared.debug("Purging " + (j * packet) + " / " + size);
List<Integer> subList =
uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet));
if (subList.isEmpty()) {
break;
addGlobalTask(new Runnable() {
@Override public void run() {
if (!uniqueIds.isEmpty()) {
try {
ArrayList<Integer> uniqueIdsList = new ArrayList<Integer>(uniqueIds);
String stmt_prefix = "";
int size = uniqueIdsList.size();
int packet = 990;
int amount = size / packet;
int count = 0;
int last = -1;
for (int j = 0; j <= amount; j++) {
PlotSquared.debug("Purging " + (j * packet) + " / " + size);
List<Integer> subList =
uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet));
if (subList.isEmpty()) {
break;
}
StringBuilder idstr2 = new StringBuilder("");
stmt_prefix = "";
for (Integer id : subList) {
idstr2.append(stmt_prefix).append(id);
stmt_prefix = " OR `id` = ";
}
stmt_prefix = "";
StringBuilder idstr = new StringBuilder();
for (Integer id : subList) {
idstr.append(stmt_prefix).append(id);
stmt_prefix = " OR `plot_plot_id` = ";
}
PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_helpers` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_denied` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_settings` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_trusted` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix + "plot` WHERE `id` = "
+ idstr2);
stmt.executeUpdate();
stmt.close();
commit();
}
StringBuilder idstr2 = new StringBuilder();
stmt_prefix = "";
for (Integer id : subList) {
idstr2.append(stmt_prefix).append(id);
stmt_prefix = " OR `id` = ";
}
stmt_prefix = "";
StringBuilder idstr = new StringBuilder();
for (Integer id : subList) {
idstr.append(stmt_prefix).append(id);
stmt_prefix = " OR `plot_plot_id` = ";
}
PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_helpers` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_denied` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_settings` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix
+ "plot_trusted` WHERE `plot_plot_id` = " + idstr);
stmt.executeUpdate();
stmt.close();
stmt = SQLManager.this.connection.prepareStatement(
"DELETE FROM `" + SQLManager.this.prefix + "plot` WHERE `id` = "
+ idstr2);
stmt.executeUpdate();
stmt.close();
commit();
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE PLOTS!");
return;
}
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE PLOTS!");
return;
}
PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!");
}
PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!");
});
}
@Override public void purge(final PlotArea area, final Set<PlotId> plots) {
addGlobalTask(() -> {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix
+ "plot` WHERE `world` = ?")) {
stmt.setString(1, area.toString());
Set<Integer> ids;
try (ResultSet r = stmt.executeQuery()) {
ids = new HashSet<>();
while (r.next()) {
PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z"));
if (plots.contains(plot_id)) {
ids.add(r.getInt("id"));
addGlobalTask(new Runnable() {
@Override public void run() {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix
+ "plot` WHERE `world` = ?")) {
stmt.setString(1, area.toString());
Set<Integer> ids;
try (ResultSet r = stmt.executeQuery()) {
ids = new HashSet<>();
while (r.next()) {
PlotId plot_id =
new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z"));
if (plots.contains(plot_id)) {
ids.add(r.getInt("id"));
}
}
}
purgeIds(ids);
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE AREA '" + area + "'!");
}
for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) {
PlotId plotId = iterator.next();
iterator.remove();
PlotId id = new PlotId(plotId.x, plotId.y);
area.removePlot(id);
}
purgeIds(ids);
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE AREA '" + area + "'!");
}
for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) {
PlotId plotId = iterator.next();
iterator.remove();
PlotId id = new PlotId(plotId.x, plotId.y);
area.removePlot(id);
}
});
}
@ -2444,7 +2523,11 @@ import java.util.concurrent.atomic.AtomicInteger;
}
resultSet.close();
TaskManager.runTaskAsync(() -> result.run(metaMap));
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
result.run(metaMap);
}
});
}
});
@ -2501,11 +2584,18 @@ import java.util.concurrent.atomic.AtomicInteger;
}
}
owner = resultSet.getString("owner");
user = uuids.computeIfAbsent(owner, UUID::fromString);
user = uuids.get(owner);
if (user == null) {
user = UUID.fromString(owner);
uuids.put(owner, user);
}
cluster = new PlotCluster(null, pos1, pos2, user, id);
clusters.put(id, cluster);
Set<PlotCluster> set =
newClusters.computeIfAbsent(areaid, k -> new HashSet<>());
Set<PlotCluster> set = newClusters.get(areaid);
if (set == null) {
set = new HashSet<>();
newClusters.put(areaid, set);
}
set.add(cluster);
}
//Getting helpers
@ -2514,7 +2604,11 @@ import java.util.concurrent.atomic.AtomicInteger;
while (resultSet.next()) {
id = resultSet.getInt("cluster_id");
owner = resultSet.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString);
user = uuids.get(owner);
if (user == null) {
user = UUID.fromString(owner);
uuids.put(owner, user);
}
cluster = clusters.get(id);
if (cluster != null) {
cluster.helpers.add(user);
@ -2529,7 +2623,11 @@ import java.util.concurrent.atomic.AtomicInteger;
while (resultSet.next()) {
id = resultSet.getInt("cluster_id");
owner = resultSet.getString("user_uuid");
user = uuids.computeIfAbsent(owner, UUID::fromString);
user = uuids.get(owner);
if (user == null) {
user = UUID.fromString(owner);
uuids.put(owner, user);
}
cluster = clusters.get(id);
if (cluster != null) {
cluster.invited.add(user);
@ -2562,7 +2660,7 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (Exception ignored) {
}
}
int m = resultSet.getInt("merged");
Integer m = resultSet.getInt("merged");
boolean[] merged = new boolean[4];
for (int i = 0; i < 4; i++) {
merged[3 - i] = (m & 1 << i) != 0;
@ -2628,6 +2726,32 @@ import java.util.concurrent.atomic.AtomicInteger;
return newClusters;
}
@Override public void setFlags(final PlotCluster cluster, HashMap<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) {
addClusterTask(cluster, new UniqueStatement("setClusterName") {
@Override public void set(PreparedStatement stmt) throws SQLException {
@ -2706,7 +2830,7 @@ import java.util.concurrent.atomic.AtomicInteger;
new UniqueStatement("createCluster_settings_" + cluster.hashCode()) {
@Override public void set(PreparedStatement stmt) throws SQLException {
stmt.setInt(1, getClusterId(cluster));
stmt.setString(2, cluster.getAlias());
stmt.setString(2, cluster.settings.getAlias());
}
@Override public PreparedStatement get() throws SQLException {
@ -2945,83 +3069,87 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override
public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min,
final PlotId max) {
addGlobalTask(() -> {
if (min == null) {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "plot` SET `world` = ? WHERE `world` = ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "cluster` SET `world` = ? WHERE `world` = ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.setInt(3, min.x);
stmt.setInt(4, max.x);
stmt.setInt(5, min.y);
stmt.setInt(6, max.y);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.setInt(3, max.x);
stmt.setInt(4, max.y);
stmt.setInt(5, min.x);
stmt.setInt(6, min.y);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
addGlobalTask(new Runnable() {
@Override public void run() {
if (min == null) {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "plot` SET `world` = ? WHERE `world` = ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "cluster` SET `world` = ? WHERE `world` = ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.setInt(3, min.x);
stmt.setInt(4, max.x);
stmt.setInt(5, min.y);
stmt.setInt(6, max.y);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix
+ "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) {
stmt.setString(1, newWorld);
stmt.setString(2, oldWorld);
stmt.setInt(3, max.x);
stmt.setInt(4, max.y);
stmt.setInt(5, min.x);
stmt.setInt(6, min.y);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
}
@Override public void replaceUUID(final UUID old, final UUID now) {
addGlobalTask(() -> {
try (Statement stmt = SQLManager.this.connection.createStatement()) {
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now
.toString() + "' WHERE `owner` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster_helpers` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now.toString()
+ "' WHERE `owner` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '" + now
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '" + now
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '" + now
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
} catch (SQLException e) {
e.printStackTrace();
addGlobalTask(new Runnable() {
@Override public void run() {
try (Statement stmt = SQLManager.this.connection.createStatement()) {
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now
.toString() + "' WHERE `owner` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster_helpers` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now
.toString() + "' WHERE `owner` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}

View File

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

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.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotSettings;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.google.common.collect.ImmutableSet;
@ -117,7 +114,7 @@ public class FlagManager {
* @param flag
* @return
*/
@SuppressWarnings("deprecation") public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
if (plot.owner == null) {
return null;
}
@ -144,6 +141,13 @@ public class FlagManager {
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.
*
@ -213,6 +217,20 @@ public class FlagManager {
return true;
}
public static boolean removeClusterFlag(PlotCluster cluster, Flag id) {
Object object = cluster.settings.flags.remove(id);
if (object == null) {
return false;
}
boolean result = EventUtil.manager.callFlagRemove(id, object, cluster);
if (!result) {
cluster.settings.flags.put(id, object);
return false;
}
DBFunc.setFlags(cluster, cluster.settings.flags);
return true;
}
public static void setPlotFlags(Plot origin, HashMap<Flag<?>, Object> flags) {
for (Plot plot : origin.getConnectedPlots()) {
if (flags != null && !flags.isEmpty()) {
@ -230,6 +248,20 @@ public class FlagManager {
}
}
public static void setClusterFlags(PlotCluster cluster, Set<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.
*

View File

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

View File

@ -1,5 +1,5 @@
package com.github.intellectualsites.plotsquared.plot.logger;
@FunctionalInterface public interface ILogger {
public interface ILogger {
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.MainCommand;
import javax.annotation.Nonnull;
import javax.script.ScriptException;
public abstract class Expression<T> {
@Nonnull public static <U> Expression<U> constant(final U value) {
public static <U> Expression<U> constant(final U value) {
return new Expression<U>() {
@Override public U evaluate(U arg) {
return value;

View File

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

View File

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

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.util.MainUtil;
import lombok.Getter;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.UUID;
public class PlotCluster {
public PlotArea area;
@Nonnull @Getter public PlotSettings settings;
public PlotSettings settings;
public UUID owner;
public HashSet<UUID> helpers = new HashSet<>();
public HashSet<UUID> invited = new HashSet<>();
public int temp;
@Nonnull private PlotId pos1;
@Nonnull private PlotId pos2;
private PlotId pos1;
private PlotId pos2;
private RegionWrapper region;
public PlotCluster(PlotArea area, @Nonnull PlotId pos1, @Nonnull PlotId pos2, UUID owner) {
public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner) {
this.area = area;
this.pos1 = pos1;
this.pos2 = pos2;
@ -29,7 +27,7 @@ public class PlotCluster {
setRegion();
}
public PlotCluster(PlotArea area, @Nonnull PlotId pos1, PlotId pos2, UUID owner, int temp) {
public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner, int temp) {
this.area = area;
this.pos1 = pos1;
this.pos2 = pos2;
@ -84,14 +82,6 @@ public class PlotCluster {
return this.settings.getAlias();
}
public void setName(String name) {
this.settings.setAlias(name);
}
public String getAlias() {
return this.settings.getAlias();
}
/**
* Get the area (in plots).
*

View File

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

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
* already cached)<br> - Accepts sponge/bukkit Player (online) - Accepts player name (online) -
* Accepts UUID - Accepts bukkit OfflinePlayer (offline)
* Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)<br>
* - Accepts sponge/bukkit Player (online)
* - Accepts player name (online)
* - Accepts UUID
* - Accepts bukkit OfflinePlayer (offline)
*
* @param player
* @return
*/
public static PlotPlayer wrap(Object player) {
return PlotSquared.get().IMP.wrapPlayer(player);
}
/**
* Get the cached PlotPlayer from a username<br> - This will return null if the player has not
* finished logging in or is not online
* Get the cached PlotPlayer from a username<br>
* - This will return null if the player has not finished logging in or is not online
*
* @param name
* @return
*/
public static PlotPlayer get(String name) {
return UUIDHandler.getPlayer(name);
@ -66,6 +74,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Set some session only metadata for this player.
*
* @param key
* @param value
*/
public void setMeta(String key, Object value) {
if (value == null) {
@ -101,8 +112,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Delete the metadata for a key. - metadata is session only - deleting other plugin's metadata
* may cause issues
* Delete the metadata for a key.
* - metadata is session only
* - deleting other plugin's metadata may cause issues
*
* @param key
*/
public Object deleteMeta(String key) {
return this.meta == null ? null : this.meta.remove(key);
@ -120,8 +134,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Get this player's current plot.
*
* @return the plot the player is standing on or null if standing on a road or not in a {@link
* PlotArea}
* @return the plot the player is standing on or null if standing on a road or not in a {@link PlotArea}
*/
public Plot getCurrentPlot() {
Plot value = getMeta(PlotPlayer.META_LAST_PLOT);
@ -132,11 +145,10 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the total number of allowed plots Possibly relevant: (To increment the player's allowed
* plots, see the example script on the wiki)
* Get the total number of allowed plots
* Possibly relevant: (To increment the player's allowed plots, see the example script on the wiki)
*
* @return number of allowed plots within the scope (globally, or in the player's current world as
* defined in the settings.yml)
* @return number of allowed plots within the scope (globally, or in the player's current world as defined in the settings.yml)
*/
public int getAllowedPlots() {
return Permissions.hasPermissionRange(this, "plots.plot", Settings.Limit.MAX_PLOTS);
@ -145,8 +157,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Get the total number of allowed clusters
*
* @return number of allowed clusters within the scope (globally, or in the player's current world
* as defined in the settings.yml)
* @return number of allowed clusters within the scope (globally, or in the player's current world as defined in the settings.yml)
*/
public int getAllowedClusters() {
return Permissions.hasPermissionRange(this, "plots.cluster", Settings.Limit.MAX_PLOTS);
@ -180,8 +191,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Get the number of plots this player owns.
*
* @return number of plots within the scope (globally, or in the player's current world as defined
* in the settings.yml)
* @return number of plots within the scope (globally, or in the player's current world as defined in the settings.yml)
* @see #getPlotCount(String);
* @see #getPlots()
*/
@ -229,6 +239,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
* Get the number of plots this player owns in the world.
*
* @param world the name of the plotworld to check.
* @return
*/
public int getPlotCount(String world) {
UUID uuid = getUUID();
@ -273,6 +284,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Return the PlotArea this player is currently in, or null.
*
* @return
*/
public PlotArea getPlotAreaAbs() {
return PlotSquared.get().getPlotAreaAbs(getLocation());
@ -305,15 +318,18 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Get this player's full location (including yaw/pitch)
*
* @return
*/
public abstract Location getLocationFull();
////////////////////////////////////////////////
/**
* Get this player's UUID. === !IMPORTANT ===<br> The UUID is dependent on the mode chosen in the
* settings.yml and may not be the same as Bukkit has (especially if using an old version of
* Bukkit that does not support UUIDs)
* Get this player's UUID.
* === !IMPORTANT ===<br>
* The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has
* (especially if using an old version of Bukkit that does not support UUIDs)
*
* @return UUID
*/
@ -356,8 +372,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public abstract void setCompassTarget(Location location);
/**
* Set player data that will persist restarts. - Please note that this is not intended to store
* large values - For session only data use meta
* Set player data that will persist restarts.
* - Please note that this is not intended to store large values
* - For session only data use meta
*
* @param key
*/
public void setAttribute(String key) {
setPersistentMeta("attrib_" + key, new byte[] {(byte) 1});
@ -366,6 +385,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Retrieves the attribute of this player.
*
* @param key
* @return the attribute will be either true or false
*/
public boolean getAttribute(String key) {
@ -377,6 +397,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Remove an attribute from a player.
*
* @param key
*/
public void removeAttribute(String key) {
removePersistentMeta("attrib_" + key);
@ -470,7 +492,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
owned.deletePlot(null);
PlotSquared.debug(String
.format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned",
owned.getId(), getName()));
plot.getId(), getName()));
}
}
String name = getName();
@ -483,6 +505,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Get the amount of clusters this player owns in the specific world.
*
* @param world
* @return
*/
public int getPlayerClusterCount(String world) {
UUID uuid = getUUID();
@ -555,27 +580,31 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final Location loc =
new Location(plot.getWorldName(), x, y, z);
if (plot.isLoaded()) {
TaskManager.runTask(() -> {
if (getMeta("teleportOnLogin", true)) {
teleport(loc);
sendMessage(C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc) (" + plotX + ","
+ plotZ + ")");
TaskManager.runTask(new Runnable() {
@Override public void run() {
if (getMeta("teleportOnLogin", true)) {
teleport(loc);
sendMessage(C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc) (" + plotX + ","
+ plotZ + ")");
}
}
});
} else if (!PlotSquared.get()
.isMainThread(Thread.currentThread())) {
if (getMeta("teleportOnLogin", true)) {
if (plot.teleportPlayer(PlotPlayer.this)) {
TaskManager.runTask(() -> {
if (getMeta("teleportOnLogin",
true)) {
teleport(loc);
sendMessage(
C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc-unloaded) ("
+ plotX + "," + plotZ
+ ")");
TaskManager.runTask(new Runnable() {
@Override public void run() {
if (getMeta("teleportOnLogin",
true)) {
teleport(loc);
sendMessage(
C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc-unloaded) ("
+ plotX + ","
+ plotZ + ")");
}
}
});
}
@ -624,6 +653,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* The amount of money this Player has.
*
* @return
*/
public double getMoney() {
return EconHandler.manager == null ? 0 : EconHandler.manager.getMoney(this);
@ -642,7 +673,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
public interface PlotPlayerConverter<BaseObject> {
PlotPlayer convert(BaseObject object);
}
}

View File

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

View File

@ -4,7 +4,6 @@ import java.io.IOException;
import java.io.OutputStream;
public class AbstractDelegateOutputStream extends OutputStream {
private final OutputStream parent;
public AbstractDelegateOutputStream(OutputStream os) {
@ -19,6 +18,10 @@ public class AbstractDelegateOutputStream extends OutputStream {
parent.write(b);
}
@Override public void write(byte[] b, int off, int len) throws IOException {
parent.write(b, off, len);
}
@Override public void flush() throws IOException {
parent.flush();
}

View File

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

View File

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

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.object.*;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.HashSet;
import java.util.UUID;
@ -41,7 +40,7 @@ public class SinglePlot extends Plot {
return getId().toCommaSeparatedString();
}
@Nonnull @Override public SinglePlotArea getArea() {
@Override public SinglePlotArea getArea() {
return (SinglePlotArea) super.getArea();
}

View File

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

View File

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

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);
}

View File

@ -71,39 +71,41 @@ public abstract class ChunkManager {
public static void largeRegionTask(final String world, final RegionWrapper region,
final RunnableVal<ChunkLoc> task, final Runnable whenDone) {
TaskManager.runTaskAsync(() -> {
HashSet<ChunkLoc> chunks = new HashSet<>();
Set<ChunkLoc> mcrs = manager.getChunkChunks(world);
for (ChunkLoc mcr : mcrs) {
int bx = mcr.x << 9;
int bz = mcr.z << 9;
int tx = bx + 511;
int tz = bz + 511;
if (bx <= region.maxX && tx >= region.minX && bz <= region.maxZ
&& tz >= region.minZ) {
for (int x = bx >> 4; x <= (tx >> 4); x++) {
int cbx = x << 4;
int ctx = cbx + 15;
if (cbx <= region.maxX && ctx >= region.minX) {
for (int z = bz >> 4; z <= (tz >> 4); z++) {
int cbz = z << 4;
int ctz = cbz + 15;
if (cbz <= region.maxZ && ctz >= region.minZ) {
chunks.add(new ChunkLoc(x, z));
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
HashSet<ChunkLoc> chunks = new HashSet<>();
Set<ChunkLoc> mcrs = manager.getChunkChunks(world);
for (ChunkLoc mcr : mcrs) {
int bx = mcr.x << 9;
int bz = mcr.z << 9;
int tx = bx + 511;
int tz = bz + 511;
if (bx <= region.maxX && tx >= region.minX && bz <= region.maxZ
&& tz >= region.minZ) {
for (int x = bx >> 4; x <= (tx >> 4); x++) {
int cbx = x << 4;
int ctx = cbx + 15;
if (cbx <= region.maxX && ctx >= region.minX) {
for (int z = bz >> 4; z <= (tz >> 4); z++) {
int cbz = z << 4;
int ctz = cbz + 15;
if (cbz <= region.maxZ && ctz >= region.minZ) {
chunks.add(new ChunkLoc(x, z));
}
}
}
}
}
}
}
TaskManager.objectTask(chunks, new RunnableVal<ChunkLoc>() {
TaskManager.objectTask(chunks, new RunnableVal<ChunkLoc>() {
@Override public void run(ChunkLoc value) {
if (manager.loadChunk(world, value, false)) {
task.run(value);
@Override public void run(ChunkLoc value) {
if (manager.loadChunk(world, value, false)) {
task.run(value);
}
}
}
}, whenDone);
}, whenDone);
}
});
}
@ -237,18 +239,20 @@ public abstract class ChunkManager {
public void deleteRegionFiles(final String world, final Collection<ChunkLoc> chunks,
final Runnable whenDone) {
TaskManager.runTaskAsync(() -> {
for (ChunkLoc loc : chunks) {
String directory =
world + File.separator + "region" + File.separator + "r." + loc.x + "." + loc.z
+ ".mca";
File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)");
if (file.exists()) {
file.delete();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
for (ChunkLoc loc : chunks) {
String directory =
world + File.separator + "region" + File.separator + "r." + loc.x + "."
+ loc.z + ".mca";
File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)");
if (file.exists()) {
file.delete();
}
}
TaskManager.runTask(whenDone);
}
TaskManager.runTask(whenDone);
});
}

View File

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

View File

@ -20,31 +20,34 @@ public class CommentManager {
if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) {
return;
}
TaskManager.runTaskLaterAsync(() -> {
Collection<CommentInbox> boxes = CommentManager.inboxes.values();
final AtomicInteger count = new AtomicInteger(0);
final AtomicInteger size = new AtomicInteger(boxes.size());
for (final CommentInbox inbox : inboxes.values()) {
inbox.getComments(plot, new RunnableVal<List<PlotComment>>() {
@Override public void run(List<PlotComment> value) {
int total;
if (value != null) {
int num = 0;
for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) {
num++;
TaskManager.runTaskLaterAsync(new Runnable() {
@Override public void run() {
Collection<CommentInbox> boxes = CommentManager.inboxes.values();
final AtomicInteger count = new AtomicInteger(0);
final AtomicInteger size = new AtomicInteger(boxes.size());
for (final CommentInbox inbox : inboxes.values()) {
inbox.getComments(plot, new RunnableVal<List<PlotComment>>() {
@Override public void run(List<PlotComment> value) {
int total;
if (value != null) {
int num = 0;
for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player,
inbox.toString())) {
num++;
}
}
total = count.addAndGet(num);
} else {
total = count.get();
}
if ((size.decrementAndGet() == 0) && (total > 0)) {
AbstractTitle.sendTitle(player, "",
C.INBOX_NOTIFICATION.s().replaceAll("%s", "" + total));
}
total = count.addAndGet(num);
} else {
total = count.get();
}
if ((size.decrementAndGet() == 0) && (total > 0)) {
AbstractTitle.sendTitle(player, "",
C.INBOX_NOTIFICATION.s().replaceAll("%s", "" + total));
}
}
});
});
}
}
}, 20);
}

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

View File

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

View File

@ -87,7 +87,7 @@ public abstract class SchematicHandler {
} else {
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 QueueProvider provider;
/**
* Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the
* server
* Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the server
*/
private long last;
private long secondLast;
@ -82,50 +81,52 @@ public class GlobalBlockQueue {
return false;
}
running.set(true);
TaskManager.runTaskRepeat(() -> {
if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) {
lastSuccess = System.currentTimeMillis();
tasks();
return;
}
SET_TASK.value1 = 50 + Math.min(
(50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last =
System.currentTimeMillis()),
GlobalBlockQueue.this.secondLast - System.currentTimeMillis());
SET_TASK.value2 = getNextQueue();
if (SET_TASK.value2 == null) {
return;
}
if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException(
"This shouldn't be possible for placement to occur off the main thread");
}
// Disable the async catcher as it can't discern async vs parallel
SET_TASK.value2.startSet(true);
try {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) {
lastSuccess = System.currentTimeMillis();
tasks();
return;
}
SET_TASK.value1 = 50 + Math.min(
(50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last =
System.currentTimeMillis()),
GlobalBlockQueue.this.secondLast - System.currentTimeMillis());
SET_TASK.value2 = getNextQueue();
if (SET_TASK.value2 == null) {
return;
}
if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException(
"This shouldn't be possible for placement to occur off the main thread");
}
// Disable the async catcher as it can't discern async vs parallel
SET_TASK.value2.startSet(true);
try {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true);
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true);
}
}, 1);
return true;
@ -167,7 +168,7 @@ public class GlobalBlockQueue {
public List<LocalBlockQueue> getAllQueues() {
ArrayList<LocalBlockQueue> list =
new ArrayList<>(activeQueues.size() + inactiveQueues.size());
new ArrayList<LocalBlockQueue>(activeQueues.size() + inactiveQueues.size());
list.addAll(inactiveQueues);
list.addAll(activeQueues);
return list;
@ -196,7 +197,7 @@ public class GlobalBlockQueue {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<>();
ArrayList<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
@ -298,6 +299,6 @@ public class GlobalBlockQueue {
}
public enum QueueStage {
INACTIVE, ACTIVE, NONE
INACTIVE, ACTIVE, NONE;
}
}

View File

@ -65,6 +65,7 @@ public class ExpireManager {
/**
* Gets the account last joined - first joined (or Long.MAX_VALUE)
*
* @param uuid
* @return result
*/
public long getAccountAge(UUID uuid) {
@ -96,26 +97,28 @@ public class ExpireManager {
Iterator<Plot> iter = plotsToDelete.iterator();
final Plot current = iter.next();
if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) {
TaskManager.runTask(() -> {
pp.setMeta("ignoreExpireTask", true);
pp.teleport(current.getCenter());
pp.deleteMeta("ignoreExpireTask");
PlotMessage msg = new PlotMessage()
.text(num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ")
.color("$1").text(current.toString()).color("$2")
.suggest("/plot list expired").tooltip("/plot list expired")
//.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired")
.text("\n - ").color("$3").text("Delete this (/plot delete)")
.color("$2").suggest("/plot delete").tooltip("/plot delete")
.text("\n - ").color("$3").text("Remind later (/plot set keep 1d)")
.color("$2").suggest("/plot set keep 1d").tooltip("/plot set keep 1d")
.text("\n - ").color("$3").text("Keep this (/plot set keep true)")
.color("$2").suggest("/plot set keep true")
.tooltip("/plot set keep true").text("\n - ").color("$3")
.text("Don't show me this").color("$2")
.suggest("/plot toggle clear-confirmation")
.tooltip("/plot toggle clear-confirmation");
msg.send(pp);
TaskManager.runTask(new Runnable() {
@Override public void run() {
pp.setMeta("ignoreExpireTask", true);
pp.teleport(current.getCenter());
pp.deleteMeta("ignoreExpireTask");
PlotMessage msg = new PlotMessage().text(
num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ")
.color("$1").text(current.toString()).color("$2")
.suggest("/plot list expired").tooltip("/plot list expired")
//.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired")
.text("\n - ").color("$3").text("Delete this (/plot delete)")
.color("$2").suggest("/plot delete").tooltip("/plot delete")
.text("\n - ").color("$3").text("Remind later (/plot set keep 1d)")
.color("$2").suggest("/plot set keep 1d")
.tooltip("/plot set keep 1d").text("\n - ").color("$3")
.text("Keep this (/plot set keep true)").color("$2")
.suggest("/plot set keep true").tooltip("/plot set keep true")
.text("\n - ").color("$3").text("Don't show me this").color("$2")
.suggest("/plot toggle clear-confirmation")
.tooltip("/plot toggle clear-confirmation");
msg.send(pp);
}
});
return;
} else {
@ -216,7 +219,12 @@ public class ExpireManager {
public ArrayDeque<ExpiryTask> getTasks(PlotArea area) {
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;
}
@ -246,7 +254,7 @@ public class ExpireManager {
}
this.running = 2;
final ConcurrentLinkedDeque<Plot> plots =
new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots());
new ConcurrentLinkedDeque<Plot>(PlotSquared.get().getPlots());
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
final Runnable task = this;
@ -270,8 +278,11 @@ public class ExpireManager {
}
for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) {
expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1),
expiryTask.requiresConfirmation());
expiredTask.run(newPlot, new Runnable() {
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, expiryTask.requiresConfirmation());
return;
}
}
@ -280,19 +291,26 @@ public class ExpireManager {
@Override public void run(final PlotAnalysis changed) {
passesComplexity(changed, expired, new RunnableVal<Boolean>() {
@Override public void run(Boolean confirmation) {
expiredTask.run(newPlot,
() -> TaskManager.IMP.taskLaterAsync(task, 1),
confirmation);
expiredTask.run(newPlot, new Runnable() {
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, confirmation);
}
}, new Runnable() {
@Override public void run() {
FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20);
}
}, () -> {
FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20);
});
}
};
final Runnable doAnalysis =
() -> HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
final Runnable doAnalysis = new Runnable() {
@Override public void run() {
HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
}
};
PlotAnalysis analysis = newPlot.getComplexity(null);
if (analysis != null) {
@ -300,7 +318,11 @@ public class ExpireManager {
@Override public void run(Boolean value) {
doAnalysis.run();
}
}, () -> TaskManager.IMP.taskLaterAsync(task, 1));
}, new Runnable() {
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
});
} else {
doAnalysis.run();
}
@ -308,10 +330,12 @@ public class ExpireManager {
}
if (plots.isEmpty()) {
ExpireManager.this.running = 3;
TaskManager.runTaskLater(() -> {
if (ExpireManager.this.running == 3) {
ExpireManager.this.running = 2;
runTask(expiredTask);
TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
if (ExpireManager.this.running == 3) {
ExpireManager.this.running = 2;
runTask(expiredTask);
}
}
}, 86400000);
} else {
@ -328,9 +352,8 @@ public class ExpireManager {
long diff = time - existing;
if (diff > 0) {
Long account_age = this.account_age_cache.get(uuid);
if (account_age != null) {
if (account_age != null)
this.account_age_cache.put(uuid, account_age + diff);
}
}
}
}
@ -340,7 +363,7 @@ public class ExpireManager {
}
public HashSet<Plot> getPendingExpired() {
return plotsToDelete == null ? new HashSet<>() : plotsToDelete;
return plotsToDelete == null ? new HashSet<Plot>() : plotsToDelete;
}
public void deleteWithMessage(Plot plot, Runnable whenDone) {

View File

@ -118,14 +118,16 @@ public class PlotAnalysis {
final AtomicInteger mi = new AtomicInteger(0);
Thread ratingAnalysis = new Thread(() -> {
for (; mi.intValue() < plots.size(); mi.incrementAndGet()) {
int i = mi.intValue();
Plot plot = plots.get(i);
ratings[i] = (int) (
(plot.getAverageRating() + plot.getSettings().getRatings().size())
* 100);
PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]);
Thread ratingAnalysis = new Thread(new Runnable() {
@Override public void run() {
for (; mi.intValue() < plots.size(); mi.incrementAndGet()) {
int i = mi.intValue();
Plot plot = plots.get(i);
ratings[i] = (int) (
(plot.getAverageRating() + plot.getSettings().getRatings().size())
* 100);
PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]);
}
}
});
ratingAnalysis.start();
@ -422,6 +424,9 @@ public class PlotAnalysis {
/**
* A simple array squaring algorithm.
* - Used for calculating the variance
*
* @param array
* @return
*/
public static int[] square(int[] array) {
array = array.clone();
@ -433,6 +438,9 @@ public class PlotAnalysis {
/**
* An optimized lossy standard deviation algorithm.
*
* @param ranks
* @return
*/
public static int[] getSD(int[]... ranks) {
if (ranks.length == 0) {
@ -459,13 +467,20 @@ public class PlotAnalysis {
* An optimized algorithm for ranking a very specific set of inputs<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
*
* @param input
* @param input
* @return
*/
public static int[] rank(int[] input) {
return rank(input, 102400);
}
/**
* An optimized algorithm for ranking a very specific set of inputs.
* An optimized algorithm for ranking a very specific set of inputs
*
* @param input
* @return
*/
public static int[] rank(int[] input, int size) {
int[] cache = new int[size];

View File

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

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(PlotCluster cluster, HashMap<Flag<?>, Object> flags) {
}
@Override public void setClusterName(PlotCluster cluster, String name) {
}

View File

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