Major cleanup.

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

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

View File

@ -134,7 +134,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
private final BlockRegistry<Material> blockRegistry =
new BukkitBlockRegistry(Material.values());
private int[] version;
@Getter private String pluginName;
private String pluginName;
@Getter private SingleWorldListener singleWorldListener;
private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false;
@ -165,9 +165,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);
@ -319,6 +319,11 @@ 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");
@ -586,6 +591,7 @@ 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();
@ -802,7 +808,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) {
PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen);
PlotSquared.get().loadWorld(worldName, (GeneratorWrapper<?>) gen);
} else if (gen != null) {
PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen));
} else if (PlotSquared.get().worlds.contains("worlds." + worldName)) {

View File

@ -320,34 +320,6 @@ 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

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

View File

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

View File

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

View File

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

View File

@ -10,6 +10,7 @@ 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,8 +38,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
private static final HashMap<UUID, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override public void run() {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
@ -79,7 +79,6 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
}
}
}, 0L, 20L);
}
@ -108,7 +107,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Player player = (Player) event.getEntity();
Entity player = event.getEntity();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;

View File

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

View File

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

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

View File

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

View File

@ -99,10 +99,6 @@ public final class BukkitEventUtil extends EventUtil {
new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner));
}
@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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because one or more lines are too long

View File

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

View File

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

View File

@ -302,6 +302,7 @@ 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,6 +348,7 @@ 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) {
@ -405,6 +407,7 @@ 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) {
@ -440,7 +443,6 @@ 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();
}
}
@ -462,6 +464,7 @@ 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) {
@ -534,6 +537,7 @@ 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) {
@ -581,6 +585,7 @@ 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,6 +65,7 @@ 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);
@ -126,14 +127,12 @@ import java.util.concurrent.atomic.AtomicBoolean;
}
i++;
final AtomicBoolean result = new AtomicBoolean(false);
result.set(origin.move(possible, new Runnable() {
@Override public void run() {
result.set(origin.move(possible, () -> {
if (result.get()) {
MainUtil.sendMessage(player,
"Moving: " + origin + " -> " + possible);
TaskManager.runTaskLater(task, 1);
}
}
}, false));
if (result.get()) {
break;

View File

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

View File

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

View File

@ -165,9 +165,8 @@ import java.util.Optional;
inbox.clearInbox(plot);
Optional<ArrayList<PlotComment>> comments =
plot.getSettings().getComments(inbox.toString());
if (comments.isPresent()) {
plot.getSettings().removeComments(comments.get());
}
comments
.ifPresent(plotComments -> plot.getSettings().removeComments(plotComments));
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.containsKey("merge") ? plotArea.PRICES.get("merge") : null;
plotArea.PRICES.getOrDefault("merge", Expression.constant(0d));
final int size = plot.getConnectedPlots().size();
final double price = priceExr == null ? 0d : priceExr.evaluate((double) size);
final double price = priceExr.evaluate((double) size);
if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d
&& EconHandler.manager.getMoney(player) < price) {
sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price));

View File

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

View File

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

View File

@ -143,14 +143,6 @@ 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,6 +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 {
/**
* The "global" uuid.
@ -298,17 +299,6 @@ public class DBFunc {
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;
@ -330,10 +320,6 @@ public class DBFunc {
DBFunc.dbManager.purge(area, plotIds);
}
/**
* @param plot
* @param position
*/
public static void setPosition(Plot plot, String position) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -341,10 +327,6 @@ public class DBFunc {
DBFunc.dbManager.setPosition(plot, position);
}
/**
* @param plot
* @param comment
*/
public static void removeComment(Plot plot, PlotComment comment) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -359,10 +341,6 @@ public class DBFunc {
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;
@ -370,9 +348,6 @@ public class DBFunc {
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) {
@ -381,10 +356,6 @@ public class DBFunc {
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;
@ -392,10 +363,6 @@ public class DBFunc {
DBFunc.dbManager.removeTrusted(plot, uuid);
}
/**
* @param cluster
* @param uuid
*/
public static void removeHelper(PlotCluster cluster, UUID uuid) {
if (dbManager == null) {
return;
@ -403,9 +370,6 @@ public class DBFunc {
DBFunc.dbManager.removeHelper(cluster, uuid);
}
/**
* @param cluster
*/
public static void createCluster(PlotCluster cluster) {
if (dbManager == null) {
return;
@ -413,11 +377,6 @@ public class DBFunc {
DBFunc.dbManager.createCluster(cluster);
}
/**
* @param current
* @param min
* @param max
*/
public static void resizeCluster(PlotCluster current, PlotId min, PlotId max) {
if (dbManager == null) {
return;
@ -425,10 +384,6 @@ public class DBFunc {
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;
@ -436,10 +391,6 @@ public class DBFunc {
DBFunc.dbManager.removeMember(plot, uuid);
}
/**
* @param cluster
* @param uuid
*/
public static void removeInvited(PlotCluster cluster, UUID uuid) {
if (dbManager == null) {
return;
@ -447,10 +398,6 @@ public class DBFunc {
DBFunc.dbManager.removeInvited(cluster, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void setTrusted(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -465,10 +412,6 @@ public class DBFunc {
DBFunc.dbManager.setHelper(cluster, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void setMember(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -483,10 +426,6 @@ public class DBFunc {
DBFunc.dbManager.setInvited(cluster, uuid);
}
/**
* @param plot
* @param uuid
*/
public static void removeDenied(Plot plot, UUID uuid) {
if (plot.temp == -1 || dbManager == null) {
return;
@ -494,10 +433,6 @@ public class DBFunc {
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 abstract class Database {
public interface Database {
public abstract Connection forceConnection() throws SQLException, ClassNotFoundException;
Connection forceConnection() throws SQLException, ClassNotFoundException;
/**
* Opens a connection with the database.
@ -22,7 +22,7 @@ public abstract class Database {
* @throws SQLException if the connection can not be opened
* @throws ClassNotFoundException if the driver cannot be found
*/
public abstract Connection openConnection() throws SQLException, ClassNotFoundException;
Connection openConnection() throws SQLException, ClassNotFoundException;
/**
* Checks if a connection is open with the database.
@ -30,14 +30,14 @@ public abstract class Database {
* @return true if the connection is open
* @throws SQLException if the connection cannot be checked
*/
public abstract boolean checkConnection() throws SQLException;
boolean checkConnection() throws SQLException;
/**
* Gets the connection with the database.
*
* @return Connection with the database, null if none
*/
public abstract Connection getConnection();
Connection getConnection();
/**
* Closes the connection with the database.
@ -45,7 +45,7 @@ public abstract class Database {
* @return true if successful
* @throws SQLException if the connection cannot be closed
*/
public abstract boolean closeConnection() throws SQLException;
boolean closeConnection() throws SQLException;
/**
* Executes a SQL Query.
@ -56,7 +56,7 @@ public abstract class Database {
* @throws SQLException If the query cannot be executed
* @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()}
*/
public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException;
ResultSet querySQL(String query) throws SQLException, ClassNotFoundException;
/**
* Executes an Update SQL Query.
@ -68,5 +68,5 @@ public abstract class Database {
* @throws SQLException If the query cannot be executed
* @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()}
*/
public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException;
int updateSQL(String query) throws SQLException, ClassNotFoundException;
}

View File

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

View File

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

View File

@ -114,6 +114,7 @@ public class FlagManager {
* @param flag
* @return
*/
@SuppressWarnings("deprecation")
public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
if (plot.owner == null) {
return null;
@ -141,13 +142,6 @@ 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.
*
@ -217,20 +211,6 @@ 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()) {
@ -248,20 +228,6 @@ public class FlagManager {
}
}
public static void setClusterFlags(PlotCluster cluster, Set<Flag> flags) {
if (flags != null && !flags.isEmpty()) {
cluster.settings.flags.clear();
for (Flag flag : flags) {
cluster.settings.flags.put(flag, flag);
}
} else if (cluster.settings.flags.isEmpty()) {
return;
} else {
cluster.settings.flags.clear();
}
DBFunc.setFlags(cluster, cluster.settings.flags);
}
/**
* Get a list of registered {@link Flag} objects based on player permissions.
*

View File

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

View File

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

View File

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

View File

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

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

View File

@ -13,6 +13,7 @@ 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,25 +48,17 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)<br>
* - Accepts sponge/bukkit Player (online)
* - Accepts player name (online)
* - Accepts UUID
* - Accepts bukkit OfflinePlayer (offline)
*
* @param player
* @return
* 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)
*/
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
*
* @param name
* @return
* Get the cached PlotPlayer from a username<br> - This will return null if the player has not
* finished logging in or is not online
*/
public static PlotPlayer get(String name) {
return UUIDHandler.getPlayer(name);
@ -74,9 +66,6 @@ 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) {
@ -112,11 +101,8 @@ 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
*
* @param key
* Delete the metadata for a key. - metadata is session only - deleting other plugin's metadata
* may cause issues
*/
public Object deleteMeta(String key) {
return this.meta == null ? null : this.meta.remove(key);
@ -127,14 +113,16 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
*
* @return the name of the player
*/
@Override public String toString() {
@Override
public String toString() {
return getName();
}
/**
* 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);
@ -145,10 +133,11 @@ 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);
@ -157,7 +146,8 @@ 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);
@ -191,7 +181,8 @@ 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()
*/
@ -202,7 +193,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final AtomicInteger count = new AtomicInteger(0);
final UUID uuid = getUUID();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) {
@Override
public void run(PlotArea value) {
if (!Settings.Done.COUNTS_TOWARDS_LIMIT) {
for (Plot plot : value.getPlotsAbs(uuid)) {
if (!plot.hasFlag(Flags.DONE)) {
@ -224,7 +216,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final AtomicInteger count = new AtomicInteger(0);
final UUID uuid = getUUID();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) {
@Override
public void run(PlotArea value) {
for (PlotCluster cluster : value.getClusters()) {
if (cluster.isOwner(getUUID())) {
count.incrementAndGet();
@ -239,7 +232,6 @@ 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();
@ -284,8 +276,6 @@ 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());
@ -295,7 +285,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
return PlotSquared.get().getApplicablePlotArea(getLocation());
}
@Override public RequiredType getSuperCaller() {
@Override
public RequiredType getSuperCaller() {
return RequiredType.PLAYER;
}
@ -318,22 +309,20 @@ 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
*/
@Override public abstract UUID getUUID();
@Override
public abstract UUID getUUID();
public boolean canTeleport(Location loc) {
Location current = getLocationFull();
@ -372,20 +361,16 @@ 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
*
* @param key
* Set player data that will persist restarts. - Please note that this is not intended to store
* large values - For session only data use meta
*/
public void setAttribute(String key) {
setPersistentMeta("attrib_" + key, new byte[] {(byte) 1});
setPersistentMeta("attrib_" + key, new byte[]{(byte) 1});
}
/**
* Retrieves the attribute of this player.
*
* @param key
* @return the attribute will be either true or false
*/
public boolean getAttribute(String key) {
@ -397,8 +382,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Remove an attribute from a player.
*
* @param key
*/
public void removeAttribute(String key) {
removePersistentMeta("attrib_" + key);
@ -492,7 +475,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",
plot.getId(), getName()));
owned.getId(), getName()));
}
}
String name = getName();
@ -505,9 +488,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Get the amount of clusters this player owns in the specific world.
*
* @param world
* @return
*/
public int getPlayerClusterCount(String world) {
UUID uuid = getUUID();
@ -528,7 +508,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public int getPlayerClusterCount() {
final AtomicInteger count = new AtomicInteger();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) {
@Override
public void run(PlotArea value) {
count.addAndGet(value.getClusters().size());
}
});
@ -555,7 +536,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public void populatePersistentMetaMap() {
if (Settings.Enabled_Components.PERSISTENT_META) {
DBFunc.getPersistentMeta(getUUID(), new RunnableVal<Map<String, byte[]>>() {
@Override public void run(Map<String, byte[]> value) {
@Override
public void run(Map<String, byte[]> value) {
try {
PlotPlayer.this.metaMap = value;
if (!value.isEmpty()) {
@ -580,22 +562,19 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final Location loc =
new Location(plot.getWorldName(), x, y, z);
if (plot.isLoaded()) {
TaskManager.runTask(new Runnable() {
@Override public void run() {
TaskManager.runTask(() -> {
if (getMeta("teleportOnLogin", true)) {
teleport(loc);
sendMessage(C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc) (" + plotX + ","
+ plotZ + ")");
}
}
});
} else if (!PlotSquared.get()
.isMainThread(Thread.currentThread())) {
if (getMeta("teleportOnLogin", true)) {
if (plot.teleportPlayer(PlotPlayer.this)) {
TaskManager.runTask(new Runnable() {
@Override public void run() {
TaskManager.runTask(() -> {
if (getMeta("teleportOnLogin",
true)) {
teleport(loc);
@ -605,7 +584,6 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
+ plotX + ","
+ plotZ + ")");
}
}
});
}
}
@ -653,8 +631,6 @@ 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);
@ -673,6 +649,7 @@ 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
* @deprecated Raw access. Not compatible with PlotClusters.
*/
@Deprecated public HashMap<Flag<?>, Object> flags = new HashMap<>();
/**
@ -85,7 +85,7 @@ public class PlotSettings {
return this.ratings;
}
public boolean setMerged(int direction, boolean merged) {
boolean setMerged(int direction, boolean merged) {
if (this.merged[direction] != merged) {
this.merged[direction] = merged;
return true;
@ -142,6 +142,7 @@ public class PlotSettings {
}
}
//todo need a plot method
public Optional<ArrayList<PlotComment>> getComments(String inbox) {
ArrayList<PlotComment> c = new ArrayList<>();
if (this.comments == null) {
@ -155,22 +156,26 @@ 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,29 +4,30 @@ import java.io.IOException;
import java.io.OutputStream;
public class AbstractDelegateOutputStream extends OutputStream {
private final OutputStream parent;
public AbstractDelegateOutputStream(OutputStream os) {
this.parent = os;
}
@Override public void write(int b) throws IOException {
@Override
public void write(int b) throws IOException {
parent.write(b);
}
@Override public void write(byte[] b) throws IOException {
@Override
public void write(byte[] b) throws IOException {
parent.write(b);
}
@Override public void write(byte[] b, int off, int len) throws IOException {
parent.write(b, off, len);
}
@Override public void flush() throws IOException {
@Override
public void flush() throws IOException {
parent.flush();
}
@Override public void close() throws IOException {
@Override
public void close() throws IOException {
parent.close();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

@ -118,8 +118,7 @@ public class PlotAnalysis {
final AtomicInteger mi = new AtomicInteger(0);
Thread ratingAnalysis = new Thread(new Runnable() {
@Override public void run() {
Thread ratingAnalysis = new Thread(() -> {
for (; mi.intValue() < plots.size(); mi.incrementAndGet()) {
int i = mi.intValue();
Plot plot = plots.get(i);
@ -128,7 +127,6 @@ public class PlotAnalysis {
* 100);
PlotSquared.debug(" | " + plot + " (rating) " + ratings[i]);
}
}
});
ratingAnalysis.start();
@ -424,9 +422,6 @@ 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();
@ -439,8 +434,6 @@ public class PlotAnalysis {
/**
* An optimized lossy standard deviation algorithm.
*
* @param ranks
* @return
*/
public static int[] getSD(int[]... ranks) {
if (ranks.length == 0) {
@ -468,19 +461,13 @@ public class PlotAnalysis {
* - 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
*
* @param input
* @return
* An optimized algorithm for ranking a very specific set of inputs.
*/
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 abstract class UUIDWrapper {
public interface UUIDWrapper {
public abstract UUID getUUID(PlotPlayer player);
UUID getUUID(PlotPlayer player);
public abstract UUID getUUID(OfflinePlotPlayer player);
UUID getUUID(OfflinePlotPlayer player);
public abstract UUID getUUID(String name);
UUID getUUID(String name);
public abstract OfflinePlotPlayer getOfflinePlayer(UUID uuid);
OfflinePlotPlayer getOfflinePlayer(UUID uuid);
public abstract OfflinePlotPlayer getOfflinePlayer(String name);
OfflinePlotPlayer getOfflinePlayer(String name);
public abstract OfflinePlotPlayer[] getOfflinePlayers();
OfflinePlotPlayer[] getOfflinePlayers();
}

View File

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

View File

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