Hows this?

This commit is contained in:
boy0001
2015-09-13 14:04:31 +10:00
parent 1cccdd9d4d
commit 5137b23357
379 changed files with 18471 additions and 28437 deletions

View File

@ -3,18 +3,17 @@ package com.intellectualcrafters.plot.util;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
public abstract class AbstractTitle
{
public abstract class AbstractTitle {
public static AbstractTitle TITLE_CLASS;
public static void sendTitle(final PlotPlayer player, final String head, final String sub)
{
if (ConsolePlayer.isConsole(player)) { return; }
if ((TITLE_CLASS != null) && !player.getAttribute("disabletitles"))
{
public static void sendTitle(final PlotPlayer player, final String head, final String sub) {
if (ConsolePlayer.isConsole(player)) {
return;
}
if ((TITLE_CLASS != null) && !player.getAttribute("disabletitles")) {
TITLE_CLASS.sendTitle(player, head, sub, 1, 2, 1);
}
}
public abstract void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out);
}

View File

@ -20,28 +20,26 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
public class BO3Handler
{
public class BO3Handler {
/**
* @see #saveBO3(null, Plot)
* @param plot
* @return if successfully exported
*/
public static boolean saveBO3(final Plot plot)
{
public static boolean saveBO3(final Plot plot) {
return saveBO3(null, plot);
}
public static boolean contains(final PlotBlock[] blocks, final PlotBlock block)
{
for (final PlotBlock item : blocks)
{
if (item.equals(block)) { return true; }
public static boolean contains(final PlotBlock[] blocks, final PlotBlock block) {
for (final PlotBlock item : blocks) {
if (item.equals(block)) {
return true;
}
}
return false;
}
/**
* Save a plot as a BO3 file<br>
* - Use null for the player object if no player is applicable
@ -49,11 +47,9 @@ public class BO3Handler
* @param plot
* @return
*/
public static boolean saveBO3(final PlotPlayer plr, final Plot plot)
{
public static boolean saveBO3(final PlotPlayer plr, final Plot plot) {
final PlotWorld plotworld = PS.get().getPlotWorld(plot.world);
if (!(plotworld instanceof ClassicPlotWorld) || (plotworld.TYPE != 0))
{
if (!(plotworld instanceof ClassicPlotWorld) || (plotworld.TYPE != 0)) {
MainUtil.sendMessage(plr, "BO3 exporting only supports type 0 classic generation.");
return false;
}
@ -62,160 +58,128 @@ public class BO3Handler
final Location pos2 = plot.getTop();
final ClassicPlotWorld cpw = (ClassicPlotWorld) plotworld;
final int height = cpw.PLOT_HEIGHT;
final int cx = (pos1.getX() + pos2.getX()) / 2;
final int cz = (pos1.getZ() + pos2.getZ()) / 2;
final HashMap<ChunkLoc, BO3> map = new HashMap<>();
boolean content = false;
for (int x = pos1.getX(); x <= pos2.getX(); x++)
{
for (int x = pos1.getX(); x <= pos2.getX(); x++) {
final int X = ((x + 7) - cx) >> 4;
final int xx = (x - cx) % 16;
for (int z = pos1.getZ(); z <= pos2.getZ(); z++)
{
final int Z = ((z + 7) - cz) >> 4;
final int zz = (z - cz) % 16;
final ChunkLoc loc = new ChunkLoc(X, Z);
BO3 bo3 = map.get(loc);
for (int y = 1; y < height; y++)
{
final PlotBlock block = BlockManager.manager.getBlock(new Location(plot.world, x, y, z));
if ((block != null) && !contains(cpw.MAIN_BLOCK, block))
{
if (bo3 == null)
{
bo3 = new BO3(alias, loc);
map.put(loc, bo3);
content = true;
final int xx = (x - cx) % 16;
for (int z = pos1.getZ(); z <= pos2.getZ(); z++) {
final int Z = ((z + 7) - cz) >> 4;
final int zz = (z - cz) % 16;
final ChunkLoc loc = new ChunkLoc(X, Z);
BO3 bo3 = map.get(loc);
for (int y = 1; y < height; y++) {
final PlotBlock block = BlockManager.manager.getBlock(new Location(plot.world, x, y, z));
if ((block != null) && !contains(cpw.MAIN_BLOCK, block)) {
if (bo3 == null) {
bo3 = new BO3(alias, loc);
map.put(loc, bo3);
content = true;
}
bo3.addBlock(xx, y - height - 1, zz, block);
}
}
bo3.addBlock(xx, y - height - 1, zz, block);
}
}
final PlotBlock floor = BlockManager.manager.getBlock(new Location(plot.world, x, height, z));
if ((floor != null) && !contains(cpw.TOP_BLOCK, floor))
{
if (bo3 == null)
{
bo3 = new BO3(alias, loc);
map.put(loc, bo3);
content = true;
}
bo3.addBlock(xx, -1, zz, floor);
}
for (int y = height + 1; y < 256; y++)
{
final PlotBlock block = BlockManager.manager.getBlock(new Location(plot.world, x, y, z));
if ((block != null) && (block.id != 0))
{
if (bo3 == null)
{
bo3 = new BO3(alias, loc);
map.put(loc, bo3);
content = true;
final PlotBlock floor = BlockManager.manager.getBlock(new Location(plot.world, x, height, z));
if ((floor != null) && !contains(cpw.TOP_BLOCK, floor)) {
if (bo3 == null) {
bo3 = new BO3(alias, loc);
map.put(loc, bo3);
content = true;
}
bo3.addBlock(xx, -1, zz, floor);
}
for (int y = height + 1; y < 256; y++) {
final PlotBlock block = BlockManager.manager.getBlock(new Location(plot.world, x, y, z));
if ((block != null) && (block.id != 0)) {
if (bo3 == null) {
bo3 = new BO3(alias, loc);
map.put(loc, bo3);
content = true;
}
bo3.addBlock(xx, y - height - 1, zz, block);
}
}
bo3.addBlock(xx, y - height - 1, zz, block);
}
}
}
}
if (!content)
{
if (!content) {
MainUtil.sendMessage(plr, "No content found!");
return false;
}
for (final Entry<ChunkLoc, BO3> entry : map.entrySet())
{
for (final Entry<ChunkLoc, BO3> entry : map.entrySet()) {
final ChunkLoc chunk = entry.getKey();
final BO3 bo3 = entry.getValue();
if ((chunk.x == 0) && (chunk.z == 0))
{
if ((chunk.x == 0) && (chunk.z == 0)) {
continue;
}
int x = chunk.x;
int z = chunk.z;
if (Math.abs(chunk.x) > Math.abs(chunk.z))
{
if (Math.abs(chunk.x) > Math.abs(chunk.z)) {
x += chunk.x > 0 ? -1 : 1;
}
else
{
} else {
z += chunk.z > 0 ? -1 : 1;
}
ChunkLoc parentLoc = new ChunkLoc(x, z);
if (!map.containsKey(parentLoc))
{
if (!map.containsKey(parentLoc)) {
parentLoc = null;
for (final Entry<ChunkLoc, BO3> entry2 : map.entrySet())
{
for (final Entry<ChunkLoc, BO3> entry2 : map.entrySet()) {
final ChunkLoc other = entry2.getKey();
if (((other.x == (chunk.x - 1)) && (other.z == chunk.z)) || ((other.z == (chunk.z - 1)) && (other.x == chunk.x)))
{
if (((other.x == (chunk.x - 1)) && (other.z == chunk.z)) || ((other.z == (chunk.z - 1)) && (other.x == chunk.x))) {
parentLoc = other;
}
}
if (parentLoc == null)
{
if (parentLoc == null) {
MainUtil.sendMessage(plr, "Exporting BO3 cancelled due to detached chunk: " + chunk + " - Make sure you only have one object per plot");
return false;
}
}
map.get(parentLoc).addChild(bo3);
}
for (final Entry<ChunkLoc, BO3> entry : map.entrySet())
{
for (final Entry<ChunkLoc, BO3> entry : map.entrySet()) {
save(plot, entry.getValue());
}
MainUtil.sendMessage(plr, "BO3 exporting was successful!");
return true;
}
public static boolean save(final Plot plot, final BO3 bo3)
{
public static boolean save(final Plot plot, final BO3 bo3) {
final File base = getBaseFile(plot.world);
try
{
try {
final List<String> lines = Files.readAllLines(base.toPath(), StandardCharsets.UTF_8);
for (int i = 0; i < lines.size(); i++)
{
for (int i = 0; i < lines.size(); i++) {
final String line = lines.get(i).trim();
final String result = StringMan.replaceAll(line, "%owner%", MainUtil.getName(plot.owner), "%alias%", plot.toString(), "%blocks%", bo3.getBlocks(), "%branches%", bo3.getChildren(),
"%flags%", StringMan.join(FlagManager.getPlotFlags(plot).values(), ","));
if (!StringMan.isEqual(result, line))
{
if (!StringMan.isEqual(result, line)) {
lines.set(i, result);
}
}
File bo3File;
if ((bo3.getLoc().x == 0) && (bo3.getLoc().z == 0))
{
if ((bo3.getLoc().x == 0) && (bo3.getLoc().z == 0)) {
bo3File = new File(base.getParentFile(), bo3.getName() + ".bo3");
}
else
{
} else {
bo3File = new File(base.getParentFile(), bo3.getName() + "_" + bo3.getLoc().x + "_" + bo3.getLoc().z + ".bo3");
}
bo3File.createNewFile();
Files.write(bo3File.toPath(), StringMan.join(lines, System.getProperty("line.separator")).getBytes(), StandardOpenOption.WRITE);
return true;
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
public static File getBaseFile(final String category)
{
public static File getBaseFile(final String category) {
final File base = new File(PS.get().IMP.getDirectory(), Settings.BO3_SAVE_PATH + File.separator + category + File.separator + "base.yml");
if (!base.exists())
{
if (!base.exists()) {
PS.get().copyFile("base.yml", Settings.BO3_SAVE_PATH + File.separator + category);
}
return base;

View File

@ -4,55 +4,51 @@ import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
public abstract class BlockManager
{
public abstract class BlockManager {
public static BlockManager manager;
public abstract boolean isBlockSolid(final PlotBlock block);
public abstract StringComparison<PlotBlock>.ComparisonResult getClosestBlock(final String name);
public abstract String getClosestMatchingName(final PlotBlock block);
public abstract String[] getBiomeList();
public abstract boolean addItems(final String world, final PlotItem items);
public abstract int getBiomeFromString(final String biome);
public abstract PlotBlock getPlotBlockFromString(final String block);
public abstract int getHeighestBlock(final String world, final int x, final int z);
public abstract String getBiome(final String world, final int x, final int z);
public abstract PlotBlock getBlock(final Location loc);
public abstract Location getSpawn(final String world);
public abstract String[] getSign(final Location loc);
public abstract boolean isWorld(final String world);
public abstract void functionSetBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data);
public abstract void functionSetSign(final String worldname, final int x, final int y, final int z, final String[] lines);
public abstract void functionSetBlock(final String worldname, final int x, final int y, final int z, final int id, final byte data);
public abstract void functionSetBiomes(final String worldname, final int[] x, final int z[], final String biome);
public static void setBiomes(final String worldname, final int[] x, final int z[], final String biome)
{
public static void setBiomes(final String worldname, final int[] x, final int z[], final String biome) {
manager.functionSetBiomes(worldname, x, z, biome);
}
public static void setBlocks(final String worldname, final int[] x, final int y[], final int z[], final PlotBlock[][] blocks)
{
public static void setBlocks(final String worldname, final int[] x, final int y[], final int z[], final PlotBlock[][] blocks) {
final int[] id = new int[blocks.length];
final byte[] data = new byte[blocks.length];
for (int i = 0; i < blocks.length; i++)
{
for (int i = 0; i < blocks.length; i++) {
final PlotBlock[] current = blocks[i];
final int n = MainUtil.random.random(current.length);
id[i] = current[n].id;
@ -60,27 +56,23 @@ public abstract class BlockManager
}
setBlocks(worldname, x, y, z, id, data);
}
public static void setBlocks(final String worldname, final int[] x, final int y[], final int z[], final PlotBlock[] blocks)
{
public static void setBlocks(final String worldname, final int[] x, final int y[], final int z[], final PlotBlock[] blocks) {
final int[] id = new int[blocks.length];
final byte[] data = new byte[blocks.length];
for (int i = 0; i < blocks.length; i++)
{
for (int i = 0; i < blocks.length; i++) {
final PlotBlock current = blocks[i];
id[i] = current.id;
data[i] = current.data;
}
setBlocks(worldname, x, y, z, id, data);
}
public static void setSign(final String worldname, final int x, final int y, final int z, final String[] lines)
{
public static void setSign(final String worldname, final int x, final int y, final int z, final String[] lines) {
manager.functionSetSign(worldname, x, y, z, lines);
}
public static void setBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data)
{
public static void setBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data) {
manager.functionSetBlocks(worldname, x, y, z, id, data);
}
}

View File

@ -4,9 +4,8 @@ import java.util.Collection;
import com.intellectualcrafters.plot.object.ChunkLoc;
public abstract class BlockUpdateUtil
{
public abstract class BlockUpdateUtil {
public static BlockUpdateUtil setBlockManager = null;
public abstract void update(final String worldname, final Collection<ChunkLoc> chunkLocs);
}

View File

@ -3,21 +3,20 @@ package com.intellectualcrafters.plot.util;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
public abstract class ChatManager<T>
{
public abstract class ChatManager<T> {
public static ChatManager<?> manager;
public abstract T builder();
public abstract void color(final PlotMessage message, final String color);
public abstract void tooltip(final PlotMessage message, final PlotMessage... tooltip);
public abstract void command(final PlotMessage message, final String command);
public abstract void text(final PlotMessage message, final String text);
public abstract void send(final PlotMessage plotMessage, final PlotPlayer player);
public abstract void suggest(final PlotMessage plotMessage, final String command);
}

View File

@ -14,23 +14,21 @@ import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.SetBlockQueue.ChunkWrapper;
public abstract class ChunkManager
{
public abstract class ChunkManager {
public static ChunkManager manager = null;
public static RegionWrapper CURRENT_PLOT_CLEAR = null;
public static boolean FORCE_PASTE = false;
public static HashMap<PlotLoc, HashMap<Short, Short>> GENERATE_BLOCKS = new HashMap<>();
public static HashMap<PlotLoc, HashMap<Short, Byte>> GENERATE_DATA = new HashMap<>();
public static ChunkLoc getChunkChunk(final Location loc)
{
public static ChunkLoc getChunkChunk(final Location loc) {
final int x = loc.getX() >> 9;
final int z = loc.getZ() >> 9;
return new ChunkLoc(x, z);
}
/**
* The int[] will be in the form: [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] and will represent the bottom and top parts of the chunk
* @param pos1
@ -38,8 +36,7 @@ public abstract class ChunkManager
* @param task
* @param whenDone
*/
public static void chunkTask(final Location pos1, final Location pos2, final RunnableVal<int[]> task, final Runnable whenDone, final int allocate)
{
public static void chunkTask(final Location pos1, final Location pos2, final RunnableVal<int[]> task, final Runnable whenDone, final int allocate) {
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
@ -48,25 +45,20 @@ public abstract class ChunkManager
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final ArrayList<ChunkLoc> chunks = new ArrayList<ChunkLoc>();
for (int x = bcx; x <= tcx; x++)
{
for (int z = bcz; z <= tcz; z++)
{
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z));
}
}
TaskManager.runTask(new Runnable()
{
TaskManager.runTask(new Runnable() {
@Override
public void run()
{
public void run() {
final long start = System.currentTimeMillis();
while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < allocate))
{
while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < allocate)) {
final ChunkLoc chunk = chunks.remove(0);
task.value = new int[7];
task.value[0] = chunk.x;
@ -75,62 +67,55 @@ public abstract class ChunkManager
task.value[3] = task.value[1] << 4;
task.value[4] = task.value[2] + 15;
task.value[5] = task.value[3] + 15;
if (task.value[0] == bcx)
{
if (task.value[0] == bcx) {
task.value[2] = p1x;
task.value[6] = 1;
}
if (task.value[0] == tcx)
{
if (task.value[0] == tcx) {
task.value[4] = p2x;
task.value[6] = 1;
}
if (task.value[1] == bcz)
{
if (task.value[1] == bcz) {
task.value[3] = p1z;
task.value[6] = 1;
}
if (task.value[1] == tcz)
{
if (task.value[1] == tcz) {
task.value[5] = p2z;
task.value[6] = 1;
}
task.run();
}
if (chunks.size() != 0)
{
if (chunks.size() != 0) {
TaskManager.runTaskLater(this, 1);
}
else
{
} else {
TaskManager.runTask(whenDone);
}
}
});
}
public abstract void setChunk(final ChunkWrapper loc, final PlotBlock[][] result);
public abstract int[] countEntities(final Plot plot);
public abstract boolean loadChunk(final String world, final ChunkLoc loc, final boolean force);
public abstract boolean unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe);
public abstract List<ChunkLoc> getChunkChunks(final String world);
public abstract void regenerateChunk(final String world, final ChunkLoc loc);
public abstract void deleteRegionFile(final String world, final ChunkLoc loc);
public abstract void deleteRegionFiles(final String world, final List<ChunkLoc> chunks);
public abstract void deleteRegionFiles(final String world, final List<ChunkLoc> chunks, final Runnable whenDone);
public abstract Plot hasPlot(String world, ChunkLoc chunk);
public abstract boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone);
/**
* Assumptions:<br>
* - pos1 and pos2 are in the same plot<br>
@ -141,10 +126,10 @@ public abstract class ChunkManager
* @return
*/
public abstract boolean regenerateRegion(final Location pos1, final Location pos2, final Runnable whenDone);
public abstract void clearAllEntities(final Location pos1, final Location pos2);
public abstract void swap(final String world, final PlotId id, final PlotId plotid);
public abstract void swap(final String worldname, final Location bot1, final Location top1, final Location bot2, final Location top2);
}

View File

@ -25,116 +25,101 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.plotsquared.bukkit.generator.AugmentedPopulator;
public class ClusterManager
{
public class ClusterManager {
public static HashMap<String, HashSet<PlotCluster>> clusters;
public static PlotCluster last;
private static HashSet<String> regenerating = new HashSet<>();
public static boolean contains(final PlotCluster cluster, final PlotId id)
{
public static boolean contains(final PlotCluster cluster, final PlotId id) {
return (cluster.getP1().x <= id.x) && (cluster.getP1().y <= id.y) && (cluster.getP2().x >= id.x) && (cluster.getP2().y >= id.y);
}
public static HashSet<PlotCluster> getClusters(final World world)
{
public static HashSet<PlotCluster> getClusters(final World world) {
return getClusters(world.getName());
}
public static HashSet<PlotCluster> getClusters(final String world)
{
if (clusters.containsKey(world)) { return clusters.get(world); }
public static HashSet<PlotCluster> getClusters(final String world) {
if (clusters.containsKey(world)) {
return clusters.get(world);
}
return new HashSet<>();
}
public static int getPlayerClusterCount(final String world, final PlotPlayer player)
{
public static int getPlayerClusterCount(final String world, final PlotPlayer player) {
final UUID uuid = player.getUUID();
int count = 0;
for (final PlotCluster cluster : ClusterManager.getClusters(world))
{
if (uuid.equals(cluster.owner))
{
for (final PlotCluster cluster : ClusterManager.getClusters(world)) {
if (uuid.equals(cluster.owner)) {
count += cluster.getArea();
}
}
return count;
}
public static int getPlayerClusterCount(final PlotPlayer plr)
{
public static int getPlayerClusterCount(final PlotPlayer plr) {
int count = 0;
for (final String world : PS.get().getPlotWorldsString())
{
for (final String world : PS.get().getPlotWorldsString()) {
count += getPlayerClusterCount(world, plr);
}
return count;
}
public static Location getHome(final PlotCluster cluster)
{
public static Location getHome(final PlotCluster cluster) {
final BlockLoc home = cluster.settings.getPosition();
Location toReturn;
if (home.y == 0)
{
if (home.y == 0) {
// default pos
final PlotId center = getCenterPlot(cluster);
toReturn = MainUtil.getPlotHome(cluster.world, center);
if (toReturn.getY() == 0)
{
if (toReturn.getY() == 0) {
final PlotManager manager = PS.get().getPlotManager(cluster.world);
final PlotWorld plotworld = PS.get().getPlotWorld(cluster.world);
final Location loc = manager.getSignLoc(plotworld, MainUtil.getPlot(cluster.world, center));
toReturn.setY(loc.getY());
}
}
else
{
} else {
toReturn = getClusterBottom(cluster).add(home.x, home.y, home.z);
}
final int max = MainUtil.getHeighestBlock(cluster.world, toReturn.getX(), toReturn.getZ());
if (max > toReturn.getY())
{
if (max > toReturn.getY()) {
toReturn.setY(max);
}
return toReturn;
}
public static PlotId getCenterPlot(final PlotCluster cluster)
{
public static PlotId getCenterPlot(final PlotCluster cluster) {
final PlotId bot = cluster.getP1();
final PlotId top = cluster.getP2();
return new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2);
}
public static Location getClusterBottom(final PlotCluster cluster)
{
public static Location getClusterBottom(final PlotCluster cluster) {
final String world = cluster.world;
final PlotWorld plotworld = PS.get().getPlotWorld(world);
final PlotManager manager = PS.get().getPlotManager(world);
return manager.getPlotBottomLocAbs(plotworld, cluster.getP1());
}
public static Location getClusterTop(final PlotCluster cluster)
{
public static Location getClusterTop(final PlotCluster cluster) {
final String world = cluster.world;
final PlotWorld plotworld = PS.get().getPlotWorld(world);
final PlotManager manager = PS.get().getPlotManager(world);
return manager.getPlotTopLocAbs(plotworld, cluster.getP2());
}
public static PlotCluster getCluster(final String world, final String name)
{
if (!clusters.containsKey(world)) { return null; }
for (final PlotCluster cluster : clusters.get(world))
{
if (cluster.getName().equals(name)) { return cluster; }
public static PlotCluster getCluster(final String world, final String name) {
if (!clusters.containsKey(world)) {
return null;
}
for (final PlotCluster cluster : clusters.get(world)) {
if (cluster.getName().equals(name)) {
return cluster;
}
}
return null;
}
public static boolean contains(final PlotCluster cluster, final Location loc)
{
public static boolean contains(final PlotCluster cluster, final Location loc) {
final String world = loc.getWorld();
final PlotManager manager = PS.get().getPlotManager(world);
final PlotWorld plotworld = PS.get().getPlotWorld(world);
@ -142,132 +127,129 @@ public class ClusterManager
final Location top = manager.getPlotTopLocAbs(plotworld, cluster.getP2()).add(1, 0, 1);
return (bot.getX() < loc.getX()) && (bot.getZ() < loc.getZ()) && (top.getX() > loc.getX()) && (top.getZ() > loc.getZ());
}
public static HashSet<PlotCluster> getIntersects(final String world, final PlotClusterId id)
{
if (!clusters.containsKey(world)) { return new HashSet<>(); }
public static HashSet<PlotCluster> getIntersects(final String world, final PlotClusterId id) {
if (!clusters.containsKey(world)) {
return new HashSet<>();
}
final HashSet<PlotCluster> list = new HashSet<PlotCluster>();
for (final PlotCluster cluster : clusters.get(world))
{
if (intersects(cluster, id))
{
for (final PlotCluster cluster : clusters.get(world)) {
if (intersects(cluster, id)) {
list.add(cluster);
}
}
return list;
}
public static boolean intersects(final PlotCluster cluster, final PlotClusterId id)
{
public static boolean intersects(final PlotCluster cluster, final PlotClusterId id) {
final PlotId pos1 = cluster.getP1();
final PlotId pos2 = cluster.getP2();
return (pos1.x <= id.pos2.x) && (pos2.x >= id.pos1.x) && (pos1.y <= id.pos2.y) && (pos2.y >= id.pos1.y);
}
public static PlotCluster getCluster(final Plot plot)
{
public static PlotCluster getCluster(final Plot plot) {
return getCluster(plot.world, plot.id);
}
public static PlotCluster getClusterAbs(final Location loc)
{
public static PlotCluster getClusterAbs(final Location loc) {
final String world = loc.getWorld();
if ((last != null) && last.world.equals(world))
{
if (contains(last, loc)) { return last; }
if ((last != null) && last.world.equals(world)) {
if (contains(last, loc)) {
return last;
}
}
if (clusters == null) {
return null;
}
if (clusters == null) { return null; }
final HashSet<PlotCluster> local = clusters.get(world);
if (local == null) { return null; }
for (final PlotCluster cluster : local)
{
if (contains(cluster, loc))
{
if (local == null) {
return null;
}
for (final PlotCluster cluster : local) {
if (contains(cluster, loc)) {
last = cluster;
return cluster;
}
}
return null;
}
public static PlotCluster getCluster(final Location loc)
{
public static PlotCluster getCluster(final Location loc) {
final String world = loc.getWorld();
final PlotManager manager = PS.get().getPlotManager(world);
if (manager == null) { return null; }
if (manager == null) {
return null;
}
final PlotId id = manager.getPlotIdAbs(PS.get().getPlotWorld(world), loc.getX(), loc.getY(), loc.getZ());
if (id != null) { return getCluster(world, id); }
if (id != null) {
return getCluster(world, id);
}
return getClusterAbs(loc);
}
public static PlotCluster getCluster(final String world, final PlotId id)
{
if ((last != null) && last.world.equals(world))
{
if (contains(last, id)) { return last; }
public static PlotCluster getCluster(final String world, final PlotId id) {
if ((last != null) && last.world.equals(world)) {
if (contains(last, id)) {
return last;
}
}
if (clusters == null) {
return null;
}
if (clusters == null) { return null; }
final HashSet<PlotCluster> local = clusters.get(world);
if (local == null) { return null; }
for (final PlotCluster cluster : local)
{
if (contains(cluster, id))
{
if (local == null) {
return null;
}
for (final PlotCluster cluster : local) {
if (contains(cluster, id)) {
last = cluster;
return cluster;
}
}
return null;
}
public static boolean removeCluster(final PlotCluster cluster)
{
if (clusters != null)
{
if (clusters.containsKey(cluster.world))
{
public static boolean removeCluster(final PlotCluster cluster) {
if (clusters != null) {
if (clusters.containsKey(cluster.world)) {
clusters.get(cluster.world).remove(cluster);
return true;
}
}
return false;
}
public static PlotClusterId getClusterId(final PlotCluster cluster)
{
public static PlotClusterId getClusterId(final PlotCluster cluster) {
return new PlotClusterId(cluster.getP1(), cluster.getP2());
}
public static AugmentedPopulator getPopulator(final PlotCluster cluster)
{
public static AugmentedPopulator getPopulator(final PlotCluster cluster) {
final World world = Bukkit.getWorld(cluster.world);
for (final BlockPopulator populator : world.getPopulators())
{
if (populator instanceof AugmentedPopulator)
{
if (((AugmentedPopulator) populator).cluster.equals(cluster)) { return (AugmentedPopulator) populator; }
for (final BlockPopulator populator : world.getPopulators()) {
if (populator instanceof AugmentedPopulator) {
if (((AugmentedPopulator) populator).cluster.equals(cluster)) {
return (AugmentedPopulator) populator;
}
}
}
return null;
}
public static PlotId estimatePlotId(final Location loc)
{
public static PlotId estimatePlotId(final Location loc) {
final Plot plot = MainUtil.getPlot(loc);
if (plot != null) { return plot.id; }
if (plot != null) {
return plot.id;
}
final PlotId a = new PlotId(0, 0);
final PlotId b = new PlotId(1, 1);
int xw;
int zw;
final String world = loc.getWorld();
final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (plotworld == null)
{
if (plotworld == null) {
xw = 39;
zw = 39;
}
else
{
} else {
final PlotManager manager = PS.get().getPlotManager(world);
final Location al = manager.getPlotBottomLocAbs(plotworld, a);
final Location bl = manager.getPlotBottomLocAbs(plotworld, b);
@ -278,10 +260,11 @@ public class ClusterManager
final int z = loc.getZ();
return new PlotId((x / xw) + 1, (z / zw) + 1);
}
public static void regenCluster(final PlotCluster cluster)
{
if (regenerating.contains(cluster.world + ":" + cluster.getName())) { return; }
public static void regenCluster(final PlotCluster cluster) {
if (regenerating.contains(cluster.world + ":" + cluster.getName())) {
return;
}
regenerating.add(cluster.world + ":" + cluster.getName());
final int interval = 1;
int i = 0;
@ -296,44 +279,33 @@ public class ClusterManager
final int maxChunkZ = (top.getZ() >> 4) + 1;
final AugmentedPopulator populator = getPopulator(cluster);
final ArrayList<Chunk> chunks = new ArrayList<>();
TaskManager.runTaskLater(new Runnable()
{
TaskManager.runTaskLater(new Runnable() {
@Override
public void run()
{
public void run() {
ClusterManager.regenerating.remove(cluster.world + ":" + cluster.getName());
final PlotPlayer owner = UUIDHandler.getPlayer(cluster.owner);
if (owner != null)
{
if (owner != null) {
MainUtil.sendMessage(owner, C.CLEARING_DONE);
}
}
}, (interval * chunks.size()) + 20);
// chunks
for (int x = minChunkX; x <= maxChunkX; x++)
{
for (int z = minChunkZ; z <= maxChunkZ; z++)
{
for (int x = minChunkX; x <= maxChunkX; x++) {
for (int z = minChunkZ; z <= maxChunkZ; z++) {
final Chunk chunk = world.getChunkAt(x, z);
chunks.add(chunk);
}
}
for (final Chunk chunk : chunks)
{
for (final Chunk chunk : chunks) {
i += interval;
TaskManager.runTaskLater(new Runnable()
{
TaskManager.runTaskLater(new Runnable() {
@Override
public void run()
{
if ((populator == null) || (plotworld.TYPE == 0))
{
public void run() {
if ((populator == null) || (plotworld.TYPE == 0)) {
final ChunkLoc loc = new ChunkLoc(chunk.getX(), chunk.getZ());
ChunkManager.manager.regenerateChunk(world.getName(), loc);
MainUtil.update(world.getName(), loc);
}
else
{
} else {
populator.populate(world, rand, chunk);
}
}

View File

@ -6,44 +6,35 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.CmdInstance;
import com.intellectualcrafters.plot.object.PlotPlayer;
public class CmdConfirm
{
public class CmdConfirm {
private static HashMap<String, CmdInstance> pending = new HashMap<>();
public static CmdInstance getPending(final PlotPlayer player)
{
if (player == null) { return pending.get("__CONSOLE__"); }
public static CmdInstance getPending(final PlotPlayer player) {
if (player == null) {
return pending.get("__CONSOLE__");
}
return pending.get(player.getName());
}
public static void removePending(final PlotPlayer player)
{
if (player == null)
{
public static void removePending(final PlotPlayer player) {
if (player == null) {
pending.remove("__CONSOLE__");
}
else
{
} else {
pending.remove(player.getName());
}
}
public static void removePending(final String name)
{
public static void removePending(final String name) {
pending.remove(name);
}
public static void addPending(final PlotPlayer player, final String commandStr, final Runnable runnable)
{
public static void addPending(final PlotPlayer player, final String commandStr, final Runnable runnable) {
MainUtil.sendMessage(player, C.REQUIRES_CONFIRM, commandStr);
final CmdInstance cmd = new CmdInstance(runnable);
String name;
if (player == null)
{
if (player == null) {
name = "__CONSOLE__";
}
else
{
} else {
name = player.getName();
}
pending.put(name, cmd);

View File

@ -16,48 +16,39 @@ import com.intellectualcrafters.plot.object.comment.InboxPublic;
import com.intellectualcrafters.plot.object.comment.InboxReport;
import com.intellectualcrafters.plot.object.comment.PlotComment;
public class CommentManager
{
public class CommentManager {
public static HashMap<String, CommentInbox> inboxes = new HashMap<>();
public static void sendTitle(final PlotPlayer player, final Plot plot)
{
if (!Settings.COMMENT_NOTIFICATIONS) { return; }
if (!plot.isOwner(player.getUUID())) { return; }
TaskManager.runTaskLaterAsync(new Runnable()
{
public static void sendTitle(final PlotPlayer player, final Plot plot) {
if (!Settings.COMMENT_NOTIFICATIONS) {
return;
}
if (!plot.isOwner(player.getUUID())) {
return;
}
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
public void run()
{
public void run() {
final Collection<CommentInbox> boxes = CommentManager.inboxes.values();
final AtomicInteger count = new AtomicInteger(0);
final AtomicInteger size = new AtomicInteger(boxes.size());
for (final CommentInbox inbox : inboxes.values())
{
inbox.getComments(plot, new RunnableVal()
{
for (final CommentInbox inbox : inboxes.values()) {
inbox.getComments(plot, new RunnableVal() {
@Override
public void run()
{
public void run() {
int total;
if (value != null)
{
if (value != null) {
int num = 0;
for (final PlotComment comment : (ArrayList<PlotComment>) value)
{
if (comment.timestamp > getTimestamp(player, inbox.toString()))
{
for (final PlotComment comment : (ArrayList<PlotComment>) value) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) {
num++;
}
}
total = count.addAndGet(num);
}
else
{
} else {
total = count.get();
}
if ((size.decrementAndGet() == 0) && (total > 0))
{
if ((size.decrementAndGet() == 0) && (total > 0)) {
AbstractTitle.sendTitle(player, "", C.INBOX_NOTIFICATION.s().replaceAll("%s", "" + total));
}
}
@ -66,21 +57,20 @@ public class CommentManager
}
}, 20);
}
public static long getTimestamp(final PlotPlayer player, final String inbox)
{
public static long getTimestamp(final PlotPlayer player, final String inbox) {
final Object meta = player.getMeta("inbox:" + inbox);
if (meta == null) { return player.getPreviousLogin(); }
if (meta == null) {
return player.getPreviousLogin();
}
return (Long) meta;
}
public static void addInbox(final CommentInbox inbox)
{
public static void addInbox(final CommentInbox inbox) {
inboxes.put(inbox.toString().toLowerCase(), inbox);
}
public static void registerDefaultInboxes()
{
public static void registerDefaultInboxes() {
addInbox(new InboxReport());
addInbox(new InboxPublic());
addInbox(new InboxOwner());

View File

@ -20,10 +20,8 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.util;
public class ConsoleColors
{
public static String fromString(String input)
{
public class ConsoleColors {
public static String fromString(String input) {
input = input.replaceAll("&0", fromChatColor("&0")).replaceAll("&1", fromChatColor("&1")).replaceAll("&2", fromChatColor("&2")).replaceAll("&3", fromChatColor("&3"))
.replaceAll("&4", fromChatColor("&4")).replaceAll("&5", fromChatColor("&5")).replaceAll("&6", fromChatColor("&6")).replaceAll("&7", fromChatColor("&7")).replaceAll("&8", fromChatColor("&8"))
.replaceAll("&9", fromChatColor("&9")).replaceAll("&a", fromChatColor("&a")).replaceAll("&b", fromChatColor("&b")).replaceAll("&c", fromChatColor("&c")).replaceAll("&d", fromChatColor("&d"))
@ -31,7 +29,7 @@ public class ConsoleColors
.replaceAll("&n", fromChatColor("&n")).replaceAll("&o", fromChatColor("&o")).replaceAll("&r", fromChatColor("&r"));
return input + "\u001B[0m";
}
/*
* public static final String ANSI_RESET = "\u001B[0m"; public static final
* String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED =
@ -44,15 +42,12 @@ public class ConsoleColors
* String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC
* = "\033[3m]";
*/
public static String fromChatColor(final String color)
{
public static String fromChatColor(final String color) {
return chatColor(color).getLin();
}
public static ConsoleColor chatColor(final String color)
{
switch (color)
{
public static ConsoleColor chatColor(final String color) {
switch (color) {
case "&r":
return ConsoleColor.RESET;
case "&7":
@ -88,38 +83,24 @@ public class ConsoleColors
return ConsoleColor.RESET;
}
}
static enum ConsoleColor
{
RESET("\u001B[0m"),
BLACK("\u001B[30m"),
RED("\u001B[31m"),
GREEN("\u001B[32m"),
YELLOW("\u001B[33m"),
BLUE("\u001B[34m"),
PURPLE("\u001B[35m"),
CYAN("\u001B[36m"),
WHITE("\u001B[37m"),
BOLD("\033[1m"),
UNDERLINE("\033[0m"),
ITALIC("\033[3m");
static enum ConsoleColor {
RESET("\u001B[0m"), BLACK("\u001B[30m"), RED("\u001B[31m"), GREEN("\u001B[32m"), YELLOW("\u001B[33m"), BLUE("\u001B[34m"), PURPLE("\u001B[35m"), CYAN("\u001B[36m"), WHITE("\u001B[37m"), BOLD(
"\033[1m"), UNDERLINE("\033[0m"), ITALIC("\033[3m");
private final String win;
private final String lin;
ConsoleColor(final String lin)
{
ConsoleColor(final String lin) {
this.lin = lin;
win = lin;
}
@SuppressWarnings("unused")
public String getWin()
{
public String getWin() {
return win;
}
public String getLin()
{
public String getLin() {
return lin;
}
}

View File

@ -4,33 +4,31 @@ import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
public abstract class EconHandler
{
public abstract class EconHandler {
public static EconHandler manager;
public double getMoney(final PlotPlayer player)
{
if (ConsolePlayer.isConsole(player)) { return Double.MAX_VALUE; }
public double getMoney(final PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) {
return Double.MAX_VALUE;
}
return Double.NaN;
}
public abstract void withdrawMoney(final PlotPlayer player, final double amount);
public abstract void depositMoney(final PlotPlayer player, final double amount);
public abstract void depositMoney(final OfflinePlotPlayer player, final double amount);
public void setPermission(final String player, final String perm, final boolean value)
{
public void setPermission(final String player, final String perm, final boolean value) {
setPermission(null, player, perm, value);
}
public abstract void setPermission(final String world, final String player, final String perm, final boolean value);
public abstract boolean hasPermission(final String world, final String player, final String perm);
public boolean hasPermission(final String player, final String perm)
{
public boolean hasPermission(final String player, final String perm) {
return hasPermission(null, player, perm);
}
}

View File

@ -18,183 +18,238 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
import com.plotsquared.bukkit.listeners.PlayerBlockEventType;
public abstract class EventUtil
{
public abstract class EventUtil {
public static EventUtil manager = null;
public static void unregisterPlayer(final PlotPlayer player)
{
public static void unregisterPlayer(final PlotPlayer player) {
final String name = player.getName();
if (SetupUtils.setupMap.containsKey(name))
{
if (SetupUtils.setupMap.containsKey(name)) {
SetupUtils.setupMap.remove(name);
}
CmdConfirm.removePending(name);
PS.get().IMP.unregister(player);
}
public abstract Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating);
public abstract boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto);
public abstract boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot);
public abstract boolean callClear(final String world, final PlotId id);
public abstract void callDelete(final String world, final PlotId id);
public abstract boolean callFlagAdd(final Flag flag, final Plot plot);
public abstract boolean callFlagRemove(final Flag flag, final Plot plot);
public abstract boolean callFlagRemove(final Flag flag, final PlotCluster cluster);
public abstract boolean callMerge(final String world, final Plot plot, final ArrayList<PlotId> plots);
public abstract boolean callUnlink(final String world, final ArrayList<PlotId> plots);
public abstract void callEntry(final PlotPlayer player, final Plot plot);
public abstract void callLeave(final PlotPlayer player, final Plot plot);
public abstract void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added);
public abstract void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added);
public abstract void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added);
public boolean checkPlayerBlockEvent(final PlotPlayer pp, final PlayerBlockEventType type, final Location loc, final LazyBlock block, final boolean notifyPerms)
{
public boolean checkPlayerBlockEvent(final PlotPlayer pp, final PlayerBlockEventType type, final Location loc, final LazyBlock block, final boolean notifyPerms) {
final Plot plot = MainUtil.getPlot(loc);
final UUID uuid = pp.getUUID();
if (plot == null)
{
if (!MainUtil.isPlotAreaAbs(loc)) { return true; }
if (plot == null) {
if (!MainUtil.isPlotAreaAbs(loc)) {
return true;
}
} else if (plot.isAdded(uuid)) {
return true;
}
else if (plot.isAdded(uuid)) { return true; }
switch (type)
{
case TELEPORT_OBJECT:
{
switch (type) {
case TELEPORT_OBJECT: {
return false;
}
case EAT:
case READ:
{
case READ: {
return true;
}
case BREAK_BLOCK:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
case BREAK_BLOCK: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
final Flag use = FlagManager.getPlotFlag(plot, "use");
if (use != null)
{
if (use != null) {
final HashSet<PlotBlock> value = (HashSet<PlotBlock>) use.getValue();
if (value.contains(PlotBlock.EVERYTHING) || value.contains(block.getPlotBlock())) { return true; }
if (value.contains(PlotBlock.EVERYTHING) || value.contains(block.getPlotBlock())) {
return true;
}
}
final Flag destroy = FlagManager.getPlotFlag(plot, "break");
if (destroy != null)
{
if (destroy != null) {
final HashSet<PlotBlock> value = (HashSet<PlotBlock>) destroy.getValue();
if (value.contains(PlotBlock.EVERYTHING) || value.contains(block.getPlotBlock())) { return true; }
if (value.contains(PlotBlock.EVERYTHING) || value.contains(block.getPlotBlock())) {
return true;
}
}
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
case BREAK_HANGING:
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "hanging-break")) { return true; }
if (plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); }
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "hanging-break")) {
return true;
}
if (plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
case BREAK_MISC:
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "misc-break")) { return true; }
if (plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); }
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "misc-break")) {
return true;
}
if (plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
case BREAK_VEHICLE:
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "vehicle-break")) { return true; }
if (plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); }
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "vehicle-break")) {
return true;
}
if (plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
case INTERACT_BLOCK:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
case INTERACT_BLOCK: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
final Flag flag = FlagManager.getPlotFlag(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case PLACE_BLOCK:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED.s(), notifyPerms); }
case PLACE_BLOCK: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED.s(), notifyPerms);
}
final Flag flag = FlagManager.getPlotFlag(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER.s(), notifyPerms);
}
return true;
}
case TRIGGER_PHYSICAL:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), false); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), false); }
if (FlagManager.isPlotFlagTrue(plot, "device-interact")) { return true; }
case TRIGGER_PHYSICAL: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), false);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), false);
}
if (FlagManager.isPlotFlagTrue(plot, "device-interact")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case INTERACT_HANGING:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "hanging-interact")) { return true; }
case INTERACT_HANGING: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "hanging-interact")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case INTERACT_MISC:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "misc-interact")) { return true; }
case INTERACT_MISC: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "misc-interact")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case INTERACT_VEHICLE:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "vehicle-use")) { return true; }
case INTERACT_VEHICLE: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "vehicle-use")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case SPAWN_MOB:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "mob-place")) { return true; }
case SPAWN_MOB: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "mob-place")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case PLACE_HANGING:
{
case PLACE_HANGING: {
// if (plot == null) {
// return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
// }
@ -212,28 +267,40 @@ public abstract class EventUtil
// }
return true;
}
case PLACE_MISC:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "misc-place")) { return true; }
case PLACE_MISC: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "misc-place")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
case PLACE_VEHICLE:
{
if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); }
if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); }
if (FlagManager.isPlotFlagTrue(plot, "vehicle-place")) { return true; }
case PLACE_VEHICLE: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "vehicle-place")) {
return true;
}
final Flag flag = FlagManager.getPlotFlag(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(),
notifyPerms); }
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
return true;
}
default:

View File

@ -23,147 +23,112 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.RunnableVal;
public class ExpireManager
{
public class ExpireManager {
public static ConcurrentHashMap<String, List<Plot>> expiredPlots = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, Boolean> updatingPlots = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, Long> timestamp = new ConcurrentHashMap<>();
public static ConcurrentHashMap<UUID, Long> dates = new ConcurrentHashMap<>();
public static int task;
public static long getTimeStamp(final String world)
{
if (timestamp.containsKey(world))
{
public static long getTimeStamp(final String world) {
if (timestamp.containsKey(world)) {
return timestamp.get(world);
}
else
{
} else {
timestamp.put(world, 0l);
return 0;
}
}
public static boolean updateExpired(final String world)
{
public static boolean updateExpired(final String world) {
updatingPlots.put(world, true);
final long now = System.currentTimeMillis();
if (now > getTimeStamp(world))
{
if (now > getTimeStamp(world)) {
timestamp.put(world, now + 86400000l);
TaskManager.runTaskAsync(new Runnable()
{
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
final List<Plot> plots = getOldPlots(world);
PS.debug("$2[&5Expire&dManager$2] $4Found " + plots.size() + " expired plots for " + world + "!");
expiredPlots.put(world, plots);
updatingPlots.put(world, false);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
});
return true;
}
else
{
} else {
updatingPlots.put(world, false);
return false;
}
}
public static void runTask()
{
ExpireManager.task = TaskManager.runTaskRepeatAsync(new Runnable()
{
public static void runTask() {
ExpireManager.task = TaskManager.runTaskRepeatAsync(new Runnable() {
@Override
public void run()
{
try
{
for (final String world : PS.get().getPlotWorldsString())
{
if (!ExpireManager.updatingPlots.containsKey(world))
{
public void run() {
try {
for (final String world : PS.get().getPlotWorldsString()) {
if (!ExpireManager.updatingPlots.containsKey(world)) {
ExpireManager.updatingPlots.put(world, false);
}
final Boolean updating = ExpireManager.updatingPlots.get(world);
if (updating)
{
if (updating) {
PS.debug("$2[&5Expire&dManager$2] $4Waiting on fetch...");
return;
}
if (!expiredPlots.containsKey(world))
{
if (!expiredPlots.containsKey(world)) {
PS.debug("$2[&5Expire&dManager$2] $4Updating expired plots for: " + world);
updateExpired(world);
return;
}
final List<Plot> plots = expiredPlots.get(world);
if ((plots == null) || (plots.size() == 0))
{
if (updateExpired(world))
{
if ((plots == null) || (plots.size() == 0)) {
if (updateExpired(world)) {
PS.debug("$2[&5Expire&dManager$2] $4Re-evaluating expired plots for: " + world);
return;
}
continue;
}
final Plot plot = plots.iterator().next();
if (!isExpired(plot))
{
if (!isExpired(plot)) {
expiredPlots.get(world).remove(plot);
PS.debug("$2[&5Expire&dManager$2] &bSkipping no longer expired: " + plot);
return;
}
for (final UUID helper : plot.getTrusted())
{
for (final UUID helper : plot.getTrusted()) {
final PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null)
{
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.id.toString());
}
}
for (final UUID helper : plot.getMembers())
{
for (final UUID helper : plot.getMembers()) {
final PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null)
{
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.id.toString());
}
}
final PlotManager manager = PS.get().getPlotManager(world);
if (manager == null)
{
if (manager == null) {
PS.debug("$2[&5Expire&dManager$2] &cThis is a friendly reminder to create or delete " + world + " as it is currently setup incorrectly");
expiredPlots.get(world).remove(plot);
return;
}
final PlotWorld plotworld = PS.get().getPlotWorld(world);
final RunnableVal<PlotAnalysis> run = new RunnableVal<PlotAnalysis>()
{
final RunnableVal<PlotAnalysis> run = new RunnableVal<PlotAnalysis>() {
@Override
public void run()
{
public void run() {
final PlotAnalysis changed = value;
if ((Settings.CLEAR_THRESHOLD != -1) && (plotworld.TYPE == 0) && (changed != null))
{
if ((changed.changes != 0) && (changed.getComplexity() > Settings.CLEAR_THRESHOLD))
{
if ((Settings.CLEAR_THRESHOLD != -1) && (plotworld.TYPE == 0) && (changed != null)) {
if ((changed.changes != 0) && (changed.getComplexity() > Settings.CLEAR_THRESHOLD)) {
PS.debug("$2[&5Expire&dManager$2] &bIgnoring modified plot: " + plot + " : " + changed.getComplexity() + " - " + changed.changes);
expiredPlots.get(world).remove(plot);
FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("analysis"), changed.asList()));
return;
}
}
if (plot.isMerged())
{
if (plot.isMerged()) {
MainUtil.unlinkPlot(plot, true);
}
plot.deletePlot(null);
@ -172,30 +137,23 @@ public class ExpireManager
final int modified = changed == null ? 0 : changed.changes;
PS.debug("$2[&5Expire&dManager$2] &cDeleted expired plot: " + plot + " : " + complexity + " - " + modified);
PS.debug("$4 - World: " + plot.world);
if (plot.hasOwner())
{
if (plot.hasOwner()) {
PS.debug("$4 - Owner: " + UUIDHandler.getName(plot.owner));
}
else
{
} else {
PS.debug("$4 - Owner: Unowned");
}
}
};
if (MainUtil.runners.containsKey(plot))
{
if (MainUtil.runners.containsKey(plot)) {
PS.debug("$2[&5Expire&dManager$2] &bSkipping plot in use: " + plot);
expiredPlots.get(world).remove(plot);
run();
return;
}
if ((Settings.CLEAR_THRESHOLD != -1) && (plotworld.TYPE == 0))
{
if ((Settings.CLEAR_THRESHOLD != -1) && (plotworld.TYPE == 0)) {
final PlotAnalysis analysis = plot.getComplexity();
if (analysis != null)
{
if (analysis.getComplexity() > Settings.CLEAR_THRESHOLD)
{
if (analysis != null) {
if (analysis.getComplexity() > Settings.CLEAR_THRESHOLD) {
PS.debug("$2[&5Expire&dManager$2] &bSkipping modified: " + plot);
expiredPlots.get(world).remove(plot);
run();
@ -203,97 +161,82 @@ public class ExpireManager
}
}
HybridUtils.manager.analyzePlot(plot, run);
}
else
{
} else {
run.value = null;
run.run();
}
return;
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
}, Settings.CLEAR_INTERVAL * 20);
}
public static boolean isExpired(final UUID uuid)
{
if (UUIDHandler.getPlayer(uuid) != null) { return false; }
public static boolean isExpired(final UUID uuid) {
if (UUIDHandler.getPlayer(uuid) != null) {
return false;
}
final String name = UUIDHandler.getName(uuid);
if (name != null)
{
if (name != null) {
long last;
if (dates.contains(uuid))
{
if (dates.contains(uuid)) {
last = dates.get(uuid);
}
else
{
} else {
OfflinePlayer op;
if (Settings.TWIN_MODE_UUID)
{
if (Settings.TWIN_MODE_UUID) {
op = Bukkit.getOfflinePlayer(uuid);
}
else
{
} else {
op = Bukkit.getOfflinePlayer(name);
}
if (op.hasPlayedBefore())
{
if (op.hasPlayedBefore()) {
last = op.getLastPlayed();
dates.put(uuid, last);
}
else
{
} else {
return false;
}
}
if (last == 0) { return false; }
if (last == 0) {
return false;
}
final long compared = System.currentTimeMillis() - last;
if (compared >= (86400000l * Settings.AUTO_CLEAR_DAYS)) { return true; }
if (compared >= (86400000l * Settings.AUTO_CLEAR_DAYS)) {
return true;
}
}
return false;
}
public static boolean isExpired(final Plot plot)
{
for (final UUID owner : PlotHandler.getOwners(plot))
{
if (!isExpired(owner)) { return false; }
public static boolean isExpired(final Plot plot) {
for (final UUID owner : PlotHandler.getOwners(plot)) {
if (!isExpired(owner)) {
return false;
}
}
return true;
}
public static List<Plot> getOldPlots(final String world)
{
public static List<Plot> getOldPlots(final String world) {
final ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlotsInWorld(world));
final List<Plot> toRemove = new ArrayList<>();
final Iterator<Plot> iter = plots.iterator();
while (iter.hasNext())
{
while (iter.hasNext()) {
final Plot plot = iter.next();
final Flag keepFlag = FlagManager.getPlotFlag(plot, "keep");
if ((keepFlag != null) && (Boolean) keepFlag.getValue())
{
if ((keepFlag != null) && (Boolean) keepFlag.getValue()) {
continue;
}
final UUID uuid = plot.owner;
if (uuid == null)
{
if (uuid == null) {
toRemove.add(plot);
continue;
}
final PlotPlayer player = UUIDHandler.getPlayer(uuid);
if (player != null)
{
if (player != null) {
continue;
}
if (isExpired(plot))
{
if (isExpired(plot)) {
toRemove.add(plot);
}
}

View File

@ -11,59 +11,50 @@ import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HastebinUtility
{
public class HastebinUtility {
public static final String BIN_URL = "http://hastebin.com/documents", USER_AGENT = "Mozilla/5.0";
public static final Pattern PATTERN = Pattern.compile("\\{\"key\":\"([\\S\\s]*)\"\\}");
public static String upload(final String string) throws IOException
{
public static String upload(final String string) throws IOException {
final URL url = new URL(BIN_URL);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setDoOutput(true);
final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(string.getBytes());
outputStream.flush();
outputStream.close();
final BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
final StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
final Matcher matcher = PATTERN.matcher(response.toString());
if (matcher.matches())
{
if (matcher.matches()) {
return "http://hastebin.com/" + matcher.group(1);
}
else
{
} else {
throw new RuntimeException("Couldn't read response!");
}
}
public static String upload(final File file) throws IOException
{
public static String upload(final File file) throws IOException {
final StringBuilder content = new StringBuilder();
final BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
return upload(content.toString());
}
}

View File

@ -7,21 +7,20 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
/**
* This class is only used by internal functions, for most cases use the PlotInventory class
*/
public abstract class InventoryUtil
{
public abstract class InventoryUtil {
/**
* This class is only used by internal functions, for most cases use the PlotInventory class
*/
public static InventoryUtil manager = null;
public abstract void open(final PlotInventory inv);
public abstract void close(final PlotInventory inv);
public abstract void setItem(final PlotInventory plotInventory, final int index, final PlotItemStack item);
public abstract PlotItemStack[] getItems(final PlotPlayer player);
public abstract boolean isOpen(final PlotInventory plotInventory);
}

View File

@ -24,8 +24,7 @@ package com.intellectualcrafters.plot.util;
* TPS and Lag Checker.
*
*/
public class Lag implements Runnable
*/
public class Lag implements Runnable {
/**
* Ticks
@ -39,17 +38,16 @@ public class Lag implements Runnable
* something :_:
*/
@SuppressWarnings("unused")
public static long LT = 0L;
public static long LT = 0L;
/**
* Get the server TPS
*
* @return server tick per second
*/
public static double getTPS()
*/
public static double getTPS() {
return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100));
}
}
/**
* Return the tick per second (measured in $ticks)
@ -57,14 +55,15 @@ public class Lag implements Runnable
* @param ticks Ticks
*
* @return ticks per second
*/
public static double getTPS(final int ticks)
{
*/
public static double getTPS(final int ticks) {
if (TC < ticks) {
return 20.0D;
}
final int t = (TC - 1 - ticks) % T.length;
final long e = System.currentTimeMillis() - T[t];
return ticks / (e / 1000.0D);
}
}
/**
* Get number of ticks since
@ -72,35 +71,31 @@ public class Lag implements Runnable
* @param tI Ticks <
*
* @return number of ticks since $tI
*/
public static long getElapsed(final int tI)
*/
public static long getElapsed(final int tI) {
final long t = T[tI % T.length];
return System.currentTimeMillis() - t;
}
}
/**
* Get lag percentage
*
* @return lag percentage
*/
public static double getPercentage()
*/
public static double getPercentage() {
return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D);
}
}
/**
* Get TPS percentage (of 20)
*
* @return TPS percentage
*/
public static double getFullPercentage()
*/
public static double getFullPercentage() {
return getTPS() * 5.0D;
}
}
@Override
public void run()
@Override
public void run() {
T[TC % T.length] = System.currentTimeMillis();
TC++;

File diff suppressed because it is too large Load Diff

View File

@ -1,48 +1,37 @@
package com.intellectualcrafters.plot.util;
public class MathMan
{
public static double getMean(final int[] array)
{
public class MathMan {
public static double getMean(final int[] array) {
double count = 0;
for (final int i : array)
{
for (final int i : array) {
count += i;
}
return count / array.length;
}
public static double getMean(final double[] array)
{
public static double getMean(final double[] array) {
double count = 0;
for (final double i : array)
{
for (final double i : array) {
count += i;
}
return count / array.length;
}
/**
* Returns [x, y, z]
* @param yaw
* @param pitch
* @return
*/
public static float[] getDirection(final float yaw, final float pitch)
{
public static float[] getDirection(final float yaw, final float pitch) {
final double pitch_sin = Math.sin(pitch);
return new float[] {
(float) (pitch_sin * Math.cos(yaw)),
(float) (pitch_sin * Math.sin(yaw)),
(float) Math.cos(pitch)
};
return new float[] { (float) (pitch_sin * Math.cos(yaw)), (float) (pitch_sin * Math.sin(yaw)), (float) Math.cos(pitch) };
}
public static int roundInt(final double value)
{
public static int roundInt(final double value) {
return (int) (value < 0 ? (value == (int) value) ? value : value - 1 : value);
}
/**
* Returns [ pitch, yaw ]
* @param x
@ -50,93 +39,76 @@ public class MathMan
* @param z
* @return
*/
public static float[] getPitchAndYaw(final float x, final float y, final float z)
{
public static float[] getPitchAndYaw(final float x, final float y, final float z) {
final float distance = sqrtApprox((z * z) + (x * x));
return new float[] { atan2(y, distance), atan2(x, z) };
}
private static final int ATAN2_BITS = 7;
private static final int ATAN2_BITS2 = ATAN2_BITS << 1;
private static final int ATAN2_MASK = ~(-1 << ATAN2_BITS2);
private static final int ATAN2_COUNT = ATAN2_MASK + 1;
private static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT);
private static final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1);
private static final float[] atan2 = new float[ATAN2_COUNT];
static
{
for (int i = 0; i < ATAN2_DIM; i++)
{
for (int j = 0; j < ATAN2_DIM; j++)
{
static {
for (int i = 0; i < ATAN2_DIM; i++) {
for (int j = 0; j < ATAN2_DIM; j++) {
final float x0 = (float) i / ATAN2_DIM;
final float y0 = (float) j / ATAN2_DIM;
atan2[(j * ATAN2_DIM) + i] = (float) Math.atan2(y0, x0);
}
}
}
public static final float atan2(float y, float x)
{
public static final float atan2(float y, float x) {
float add, mul;
if (x < 0.0f)
{
if (y < 0.0f)
{
if (x < 0.0f) {
if (y < 0.0f) {
x = -x;
y = -y;
mul = 1.0f;
}
else
{
} else {
x = -x;
mul = -1.0f;
}
add = -3.141592653f;
}
else
{
if (y < 0.0f)
{
} else {
if (y < 0.0f) {
y = -y;
mul = -1.0f;
}
else
{
} else {
mul = 1.0f;
}
add = 0.0f;
}
final float invDiv = 1.0f / (((x < y) ? y : x) * INV_ATAN2_DIM_MINUS_1);
final int xi = (int) (x * invDiv);
final int yi = (int) (y * invDiv);
return (atan2[(yi * ATAN2_DIM) + xi] + add) * mul;
}
public static float sqrtApprox(final float f)
{
public static float sqrtApprox(final float f) {
return f * Float.intBitsToFloat(0x5f375a86 - (Float.floatToIntBits(f) >> 1));
}
public static double sqrtApprox(final double d)
{
public static double sqrtApprox(final double d) {
return Double.longBitsToDouble(((Double.doubleToLongBits(d) - (1l << 52)) >> 1) + (1l << 61));
}
public static float invSqrt(float x)
{
public static float invSqrt(float x) {
final float xhalf = 0.5f * x;
int i = Float.floatToIntBits(x);
i = 0x5f3759df - (i >> 1);
@ -144,66 +116,69 @@ public class MathMan
x = x * (1.5f - (xhalf * x * x));
return x;
}
public static int getPositiveId(final int i)
{
if (i < 0) { return (-i * 2) - 1; }
public static int getPositiveId(final int i) {
if (i < 0) {
return (-i * 2) - 1;
}
return i * 2;
}
public static boolean isInteger(final String str)
{
if (str == null) { return false; }
public static boolean isInteger(final String str) {
if (str == null) {
return false;
}
final int length = str.length();
if (length == 0) { return false; }
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-')
{
if (length == 1) { return false; }
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++)
{
for (; i < length; i++) {
final char c = str.charAt(i);
if ((c <= '/') || (c >= ':')) { return false; }
if ((c <= '/') || (c >= ':')) {
return false;
}
}
return true;
}
public static double getSD(final double[] array, final double av)
{
public static double getSD(final double[] array, final double av) {
double sd = 0;
for (final double element : array)
{
for (final double element : array) {
sd += Math.pow(Math.abs(element - av), 2);
}
return Math.sqrt(sd / array.length);
}
public static double getSD(final int[] array, final double av)
{
public static double getSD(final int[] array, final double av) {
double sd = 0;
for (final int element : array)
{
for (final int element : array) {
sd += Math.pow(Math.abs(element - av), 2);
}
return Math.sqrt(sd / array.length);
}
public static int mod(final int x, final int y)
{
if (isPowerOfTwo(y)) { return x & (y - 1); }
public static int mod(final int x, final int y) {
if (isPowerOfTwo(y)) {
return x & (y - 1);
}
return x % y;
}
public static int unsignedmod(final int x, final int y)
{
if (isPowerOfTwo(y)) { return x & (y - 1); }
public static int unsignedmod(final int x, final int y) {
if (isPowerOfTwo(y)) {
return x & (y - 1);
}
return x % y;
}
public static boolean isPowerOfTwo(final int x)
{
public static boolean isPowerOfTwo(final int x) {
return (x & (x - 1)) == 0;
}
}

View File

@ -4,56 +4,57 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandCaller;
public class Permissions
{
public static boolean hasPermission(final PlotPlayer player, final C c)
{
public class Permissions {
public static boolean hasPermission(final PlotPlayer player, final C c) {
return hasPermission(player, c.s());
}
public static boolean hasPermission(final PlotPlayer player, final String perm)
{
public static boolean hasPermission(final PlotPlayer player, final String perm) {
return hasPermission((CommandCaller) player, perm);
}
public static boolean hasPermission(final CommandCaller player, String perm)
{
if ((player == null) || player.hasPermission(C.PERMISSION_ADMIN.s()) || player.hasPermission(C.PERMISSION_STAR.s())) { return true; }
if (player.hasPermission(perm)) { return true; }
public static boolean hasPermission(final CommandCaller player, String perm) {
if ((player == null) || player.hasPermission(C.PERMISSION_ADMIN.s()) || player.hasPermission(C.PERMISSION_STAR.s())) {
return true;
}
if (player.hasPermission(perm)) {
return true;
}
perm = perm.toLowerCase().replaceAll("^[^a-z|0-9|\\.|_|-]", "");
final String[] nodes = perm.split("\\.");
final StringBuilder n = new StringBuilder();
for (int i = 0; i < (nodes.length - 1); i++)
{
for (int i = 0; i < (nodes.length - 1); i++) {
n.append(nodes[i] + ("."));
if (!perm.equals(n + C.PERMISSION_STAR.s()))
{
if (player.hasPermission(n + C.PERMISSION_STAR.s())) { return true; }
if (!perm.equals(n + C.PERMISSION_STAR.s())) {
if (player.hasPermission(n + C.PERMISSION_STAR.s())) {
return true;
}
}
}
return false;
}
public static boolean hasPermission(final PlotPlayer player, final String perm, final boolean notify)
{
if (!hasPermission(player, perm))
{
if (notify)
{
public static boolean hasPermission(final PlotPlayer player, final String perm, final boolean notify) {
if (!hasPermission(player, perm)) {
if (notify) {
MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, perm);
}
return false;
}
return true;
}
public static int hasPermissionRange(final PlotPlayer player, final String stub, final int range)
{
if ((player == null) || player.hasPermission(C.PERMISSION_ADMIN.s()) || player.hasPermission(C.PERMISSION_STAR.s())) { return Integer.MAX_VALUE; }
if (player.hasPermission(stub + ".*")) { return Integer.MAX_VALUE; }
for (int i = range; i > 0; i--)
{
if (player.hasPermission(stub + "." + i)) { return i; }
public static int hasPermissionRange(final PlotPlayer player, final String stub, final int range) {
if ((player == null) || player.hasPermission(C.PERMISSION_ADMIN.s()) || player.hasPermission(C.PERMISSION_STAR.s())) {
return Integer.MAX_VALUE;
}
if (player.hasPermission(stub + ".*")) {
return Integer.MAX_VALUE;
}
for (int i = range; i > 0; i--) {
if (player.hasPermission(stub + "." + i)) {
return i;
}
}
return 0;
}

View File

@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.util;
public enum PlotGamemode
{
ADVENTURE,
SURVIVAL,
CREATIVE,
SPECTATOR;
public enum PlotGamemode {
ADVENTURE, SURVIVAL, CREATIVE, SPECTATOR;
}

View File

@ -1,8 +1,5 @@
package com.intellectualcrafters.plot.util;
public enum PlotWeather
{
RAIN,
CLEAR,
RESET;
public enum PlotWeather {
RAIN, CLEAR, RESET;
}

View File

@ -35,15 +35,13 @@ import org.bukkit.Bukkit;
* @author DPOH-VAR
* @version 1.0
*/
public class ReflectionUtils
{
public ReflectionUtils(final String version)
{
public class ReflectionUtils {
public ReflectionUtils(final String version) {
preClassB += "." + version;
preClassM += "." + version;
}
/**
* prefix of bukkit classes
*/
@ -52,190 +50,141 @@ public class ReflectionUtils
* prefix of minecraft classes
*/
private static String preClassM = "net.minecraft.server";
public static Class<?> getNmsClass(final String name)
{
public static Class<?> getNmsClass(final String name) {
final String className = "net.minecraft.server." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getCbClass(final String name)
{
public static Class<?> getCbClass(final String name) {
final String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getUtilClass(final String name)
{
try
{
public static Class<?> getUtilClass(final String name) {
try {
return Class.forName(name); //Try before 1.8 first
}
catch (final ClassNotFoundException ex)
{
try
{
} catch (final ClassNotFoundException ex) {
try {
return Class.forName("net.minecraft.util." + name); //Not 1.8
}
catch (final ClassNotFoundException ex2)
{
} catch (final ClassNotFoundException ex2) {
return null;
}
}
}
public static String getVersion()
{
public static String getVersion() {
final String packageName = Bukkit.getServer().getClass().getPackage().getName();
return packageName.substring(packageName.lastIndexOf('.') + 1);
}
public static Object getHandle(final Object wrapper)
{
public static Object getHandle(final Object wrapper) {
final Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
return callMethod(getHandle, wrapper);
}
//Utils
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters)
{
try
{
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters) {
try {
return clazz.getDeclaredMethod(methodName, paramaters);
}
catch (final NoSuchMethodException ex)
{
} catch (final NoSuchMethodException ex) {
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters)
{
if (method == null) { throw new RuntimeException("No such method"); }
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters) {
if (method == null) {
throw new RuntimeException("No such method");
}
method.setAccessible(true);
try
{
try {
return (T) method.invoke(instance, paramaters);
}
catch (final InvocationTargetException ex)
{
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes)
{
try
{
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes) {
try {
return (Constructor<T>) clazz.getConstructor(paramaterTypes);
}
catch (final NoSuchMethodException ex)
{
} catch (final NoSuchMethodException ex) {
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters)
{
if (constructor == null) { throw new RuntimeException("No such constructor"); }
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters) {
if (constructor == null) {
throw new RuntimeException("No such constructor");
}
constructor.setAccessible(true);
try
{
try {
return constructor.newInstance(paramaters);
}
catch (final InvocationTargetException ex)
{
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static Field makeField(final Class<?> clazz, final String name)
{
try
{
public static Field makeField(final Class<?> clazz, final String name) {
try {
return clazz.getDeclaredField(name);
}
catch (final NoSuchFieldException ex)
{
} catch (final NoSuchFieldException ex) {
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T getField(final Field field, final Object instance)
{
if (field == null) { throw new RuntimeException("No such field"); }
public static <T> T getField(final Field field, final Object instance) {
if (field == null) {
throw new RuntimeException("No such field");
}
field.setAccessible(true);
try
{
try {
return (T) field.get(instance);
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static void setField(final Field field, final Object instance, final Object value)
{
if (field == null) { throw new RuntimeException("No such field"); }
public static void setField(final Field field, final Object instance, final Object value) {
if (field == null) {
throw new RuntimeException("No such field");
}
field.setAccessible(true);
try
{
try {
field.set(instance, value);
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static Class<?> getClass(final String name)
{
try
{
public static Class<?> getClass(final String name) {
try {
return Class.forName(name);
}
catch (final ClassNotFoundException ex)
{
} catch (final ClassNotFoundException ex) {
return null;
}
}
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass)
{
try
{
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass) {
try {
return Class.forName(name).asSubclass(superClass);
}
catch (ClassCastException | ClassNotFoundException ex)
{
} catch (ClassCastException | ClassNotFoundException ex) {
return null;
}
}
/**
* Get class for name. Replace {nms} to net.minecraft.server.V*. Replace {cb} to org.bukkit.craftbukkit.V*. Replace
* {nm} to net.minecraft
@ -246,21 +195,16 @@ public class ReflectionUtils
*
* @throws RuntimeException if no class found
*/
public static RefClass getRefClass(final String... classes) throws RuntimeException
{
for (String className : classes)
{
try
{
public static RefClass getRefClass(final String... classes) throws RuntimeException {
for (String className : classes) {
try {
className = className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft");
return getRefClass(Class.forName(className));
}
catch (final ClassNotFoundException ignored)
{}
} catch (final ClassNotFoundException ignored) {}
}
throw new RuntimeException("no class found");
}
/**
* get RefClass object by real class
*
@ -268,33 +212,29 @@ public class ReflectionUtils
*
* @return RefClass based on passed class
*/
public static RefClass getRefClass(final Class clazz)
{
public static RefClass getRefClass(final Class clazz) {
return new RefClass(clazz);
}
/**
* RefClass - utility to simplify work with reflections.
*/
public static class RefClass
{
public static class RefClass {
private final Class<?> clazz;
private RefClass(final Class<?> clazz)
{
private RefClass(final Class<?> clazz) {
this.clazz = clazz;
}
/**
* get passed class
*
* @return class
*/
public Class<?> getRealClass()
{
public Class<?> getRealClass() {
return clazz;
}
/**
* see {@link Class#isInstance(Object)}
*
@ -302,11 +242,10 @@ public class ReflectionUtils
*
* @return true if object is an instance of this class
*/
public boolean isInstance(final Object object)
{
public boolean isInstance(final Object object) {
return clazz.isInstance(object);
}
/**
* get existing method by name and types
*
@ -317,42 +256,29 @@ public class ReflectionUtils
*
* @throws RuntimeException if method not found
*/
public RefMethod getMethod(final String name, final Object... types) throws NoSuchMethodException
{
try
{
public RefMethod getMethod(final String name, final Object... types) throws NoSuchMethodException {
try {
final Class[] classes = new Class[types.length];
int i = 0;
for (final Object e : types)
{
if (e instanceof Class)
{
for (final Object e : types) {
if (e instanceof Class) {
classes[i++] = (Class) e;
}
else if (e instanceof RefClass)
{
} else if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass();
}
else
{
} else {
classes[i++] = e.getClass();
}
}
try
{
try {
return new RefMethod(clazz.getMethod(name, classes));
}
catch (final NoSuchMethodException ignored)
{
} catch (final NoSuchMethodException ignored) {
return new RefMethod(clazz.getDeclaredMethod(name, classes));
}
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/**
* get existing constructor by types
*
@ -362,42 +288,29 @@ public class ReflectionUtils
*
* @throws RuntimeException if constructor not found
*/
public RefConstructor getConstructor(final Object... types)
{
try
{
public RefConstructor getConstructor(final Object... types) {
try {
final Class[] classes = new Class[types.length];
int i = 0;
for (final Object e : types)
{
if (e instanceof Class)
{
for (final Object e : types) {
if (e instanceof Class) {
classes[i++] = (Class) e;
}
else if (e instanceof RefClass)
{
} else if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass();
}
else
{
} else {
classes[i++] = e.getClass();
}
}
try
{
try {
return new RefConstructor(clazz.getConstructor(classes));
}
catch (final NoSuchMethodException ignored)
{
} catch (final NoSuchMethodException ignored) {
return new RefConstructor(clazz.getDeclaredConstructor(classes));
}
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/**
* find method by type parameters
*
@ -407,39 +320,28 @@ public class ReflectionUtils
*
* @throws RuntimeException if method not found
*/
public RefMethod findMethod(final Object... types)
{
public RefMethod findMethod(final Object... types) {
final Class[] classes = new Class[types.length];
int t = 0;
for (final Object e : types)
{
if (e instanceof Class)
{
for (final Object e : types) {
if (e instanceof Class) {
classes[t++] = (Class) e;
}
else if (e instanceof RefClass)
{
} else if (e instanceof RefClass) {
classes[t++] = ((RefClass) e).getRealClass();
}
else
{
} else {
classes[t++] = e.getClass();
}
}
final List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods());
findMethod: for (final Method m : methods)
{
findMethod: for (final Method m : methods) {
final Class<?>[] methodTypes = m.getParameterTypes();
if (methodTypes.length != classes.length)
{
if (methodTypes.length != classes.length) {
continue;
}
for (final Class aClass : classes)
{
if (!Arrays.equals(classes, methodTypes))
{
for (final Class aClass : classes) {
if (!Arrays.equals(classes, methodTypes)) {
continue findMethod;
}
return new RefMethod(m);
@ -447,7 +349,7 @@ public class ReflectionUtils
}
throw new RuntimeException("no such method");
}
/**
* find method by name
*
@ -457,21 +359,20 @@ public class ReflectionUtils
*
* @throws RuntimeException if method not found
*/
public RefMethod findMethodByName(final String... names)
{
public RefMethod findMethodByName(final String... names) {
final List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods());
for (final Method m : methods)
{
for (final String name : names)
{
if (m.getName().equals(name)) { return new RefMethod(m); }
for (final Method m : methods) {
for (final String name : names) {
if (m.getName().equals(name)) {
return new RefMethod(m);
}
}
}
throw new RuntimeException("no such method");
}
/**
* find method by return value
*
@ -481,11 +382,10 @@ public class ReflectionUtils
*
* @throws RuntimeException if method not found
*/
public RefMethod findMethodByReturnType(final RefClass type)
{
public RefMethod findMethodByReturnType(final RefClass type) {
return findMethodByReturnType(type.clazz);
}
/**
* find method by return value
*
@ -495,22 +395,21 @@ public class ReflectionUtils
*
* @throws RuntimeException if method not found
*/
public RefMethod findMethodByReturnType(Class type)
{
if (type == null)
{
public RefMethod findMethodByReturnType(Class type) {
if (type == null) {
type = void.class;
}
final List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods());
for (final Method m : methods)
{
if (type.equals(m.getReturnType())) { return new RefMethod(m); }
for (final Method m : methods) {
if (type.equals(m.getReturnType())) {
return new RefMethod(m);
}
}
throw new RuntimeException("no such method");
}
/**
* find constructor by number of arguments
*
@ -520,18 +419,18 @@ public class ReflectionUtils
*
* @throws RuntimeException if constructor not found
*/
public RefConstructor findConstructor(final int number)
{
public RefConstructor findConstructor(final int number) {
final List<Constructor> constructors = new ArrayList<>();
Collections.addAll(constructors, clazz.getConstructors());
Collections.addAll(constructors, clazz.getDeclaredConstructors());
for (final Constructor m : constructors)
{
if (m.getParameterTypes().length == number) { return new RefConstructor(m); }
for (final Constructor m : constructors) {
if (m.getParameterTypes().length == number) {
return new RefConstructor(m);
}
}
throw new RuntimeException("no such constructor");
}
/**
* get field by name
*
@ -541,25 +440,18 @@ public class ReflectionUtils
*
* @throws RuntimeException if field not found
*/
public RefField getField(final String name)
{
try
{
try
{
public RefField getField(final String name) {
try {
try {
return new RefField(clazz.getField(name));
}
catch (final NoSuchFieldException ignored)
{
} catch (final NoSuchFieldException ignored) {
return new RefField(clazz.getDeclaredField(name));
}
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/**
* find field by type
*
@ -569,11 +461,10 @@ public class ReflectionUtils
*
* @throws RuntimeException if field not found
*/
public RefField findField(final RefClass type)
{
public RefField findField(final RefClass type) {
return findField(type.clazz);
}
/**
* find field by type
*
@ -583,60 +474,54 @@ public class ReflectionUtils
*
* @throws RuntimeException if field not found
*/
public RefField findField(Class type)
{
if (type == null)
{
public RefField findField(Class type) {
if (type == null) {
type = void.class;
}
final List<Field> fields = new ArrayList<>();
Collections.addAll(fields, clazz.getFields());
Collections.addAll(fields, clazz.getDeclaredFields());
for (final Field f : fields)
{
if (type.equals(f.getType())) { return new RefField(f); }
for (final Field f : fields) {
if (type.equals(f.getType())) {
return new RefField(f);
}
}
throw new RuntimeException("no such field");
}
}
/**
* Method wrapper
*/
public static class RefMethod
{
public static class RefMethod {
private final Method method;
private RefMethod(final Method method)
{
private RefMethod(final Method method) {
this.method = method;
method.setAccessible(true);
}
/**
* @return passed method
*/
public Method getRealMethod()
{
public Method getRealMethod() {
return method;
}
/**
* @return owner class of method
*/
public RefClass getRefClass()
{
public RefClass getRefClass() {
return new RefClass(method.getDeclaringClass());
}
/**
* @return class of method return type
*/
public RefClass getReturnRefClass()
{
public RefClass getReturnRefClass() {
return new RefClass(method.getReturnType());
}
/**
* apply method to object
*
@ -644,11 +529,10 @@ public class ReflectionUtils
*
* @return RefExecutor with method call(...)
*/
public RefExecutor of(final Object e)
{
public RefExecutor of(final Object e) {
return new RefExecutor(e);
}
/**
* call static method
*
@ -656,27 +540,21 @@ public class ReflectionUtils
*
* @return return value
*/
public Object call(final Object... params)
{
try
{
public Object call(final Object... params) {
try {
return method.invoke(null, params);
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public class RefExecutor
{
public class RefExecutor {
final Object e;
public RefExecutor(final Object e)
{
public RefExecutor(final Object e) {
this.e = e;
}
/**
* apply method for selected object
*
@ -686,49 +564,41 @@ public class ReflectionUtils
*
* @throws RuntimeException if something went wrong
*/
public Object call(final Object... params)
{
try
{
public Object call(final Object... params) {
try {
return method.invoke(e, params);
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
}
/**
* Constructor wrapper
*/
public static class RefConstructor
{
public static class RefConstructor {
private final Constructor constructor;
private RefConstructor(final Constructor constructor)
{
private RefConstructor(final Constructor constructor) {
this.constructor = constructor;
constructor.setAccessible(true);
}
/**
* @return passed constructor
*/
public Constructor getRealConstructor()
{
public Constructor getRealConstructor() {
return constructor;
}
/**
* @return owner class of method
*/
public RefClass getRefClass()
{
public RefClass getRefClass() {
return new RefClass(constructor.getDeclaringClass());
}
/**
* create new instance with constructor
*
@ -738,53 +608,44 @@ public class ReflectionUtils
*
* @throws RuntimeException if something went wrong
*/
public Object create(final Object... params)
{
try
{
public Object create(final Object... params) {
try {
return constructor.newInstance(params);
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
public static class RefField
{
public static class RefField {
private final Field field;
private RefField(final Field field)
{
private RefField(final Field field) {
this.field = field;
field.setAccessible(true);
}
/**
* @return passed field
*/
public Field getRealField()
{
public Field getRealField() {
return field;
}
/**
* @return owner class of field
*/
public RefClass getRefClass()
{
public RefClass getRefClass() {
return new RefClass(field.getDeclaringClass());
}
/**
* @return type of field
*/
public RefClass getFieldRefClass()
{
public RefClass getFieldRefClass() {
return new RefClass(field.getType());
}
/**
* apply fiend for object
*
@ -792,50 +653,39 @@ public class ReflectionUtils
*
* @return RefExecutor with getter and setter
*/
public RefExecutor of(final Object e)
{
public RefExecutor of(final Object e) {
return new RefExecutor(e);
}
public class RefExecutor
{
public class RefExecutor {
final Object e;
public RefExecutor(final Object e)
{
public RefExecutor(final Object e) {
this.e = e;
}
/**
* set field value for applied object
*
* @param param value
*/
public void set(final Object param)
{
try
{
public void set(final Object param) {
try {
field.set(e, param);
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/**
* get field value for applied object
*
* @return value of field
*/
public Object get()
{
try
{
public Object get() {
try {
return field.get(e);
}
catch (final Exception e)
{
} catch (final Exception e) {
throw new RuntimeException(e);
}
}

View File

@ -4,14 +4,12 @@ import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class RegExUtil
{
public class RegExUtil {
public static Map<String, Pattern> compiledPatterns;
static
{
static {
compiledPatterns = new HashMap<>();
}
}

View File

@ -9,9 +9,8 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.PlotBlock;
public class SetBlockQueue
{
public class SetBlockQueue {
private volatile static HashMap<ChunkWrapper, PlotBlock[][]> blocks;
private volatile static int allocate = 25;
private volatile static boolean running = false;
@ -21,30 +20,23 @@ public class SetBlockQueue
private static long last;
private static int lastInt = 0;
private static PlotBlock lastBlock = new PlotBlock((short) 0, (byte) 0);
public synchronized static void allocate(final int t)
{
public synchronized static void allocate(final int t) {
allocate = t;
}
public static int getAllocate()
{
public static int getAllocate() {
return allocate;
}
public static void setSlow(final boolean value)
{
public static void setSlow(final boolean value) {
slow = value;
}
public synchronized static boolean addNotify(final Runnable whenDone)
{
if (runnables == null)
{
if ((blocks == null) || (blocks.size() == 0))
{
if (whenDone != null)
{
public synchronized static boolean addNotify(final Runnable whenDone) {
if (runnables == null) {
if ((blocks == null) || (blocks.size() == 0)) {
if (whenDone != null) {
whenDone.run();
}
slow = false;
@ -53,13 +45,11 @@ public class SetBlockQueue
}
runnables = new ArrayDeque<>();
}
if (whenDone != null)
{
if (whenDone != null) {
init();
runnables.add(whenDone);
}
if ((blocks == null) || (blocks.size() == 0) || !blocks.entrySet().iterator().hasNext())
{
if ((blocks == null) || (blocks.size() == 0) || !blocks.entrySet().iterator().hasNext()) {
final ArrayDeque<Runnable> tasks = runnables;
lastInt = -1;
lastBlock = null;
@ -67,42 +57,33 @@ public class SetBlockQueue
running = false;
blocks = null;
slow = false;
if (tasks != null)
{
for (final Runnable runnable : tasks)
{
if (tasks != null) {
for (final Runnable runnable : tasks) {
runnable.run();
}
}
}
return false;
}
public synchronized static void init()
{
if (blocks == null)
{
if (MainUtil.x_loc == null)
{
public synchronized static void init() {
if (blocks == null) {
if (MainUtil.x_loc == null) {
MainUtil.initCache();
}
blocks = new HashMap<>();
runnables = new ArrayDeque<>();
}
if (!running)
{
if (!running) {
TaskManager.index.incrementAndGet();
final int current = TaskManager.index.intValue();
final int task = TaskManager.runTaskRepeat(new Runnable()
{
final int task = TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run()
{
public void run() {
if (locked) {
return;
}
if ((blocks == null) || (blocks.size() == 0))
{
if ((blocks == null) || (blocks.size() == 0)) {
PS.get().TASK.cancelTask(TaskManager.tasks.get(current));
final ArrayDeque<Runnable> tasks = runnables;
lastInt = -1;
@ -111,10 +92,8 @@ public class SetBlockQueue
running = false;
blocks = null;
slow = false;
if (tasks != null)
{
for (final Runnable runnable : tasks)
{
if (tasks != null) {
for (final Runnable runnable : tasks) {
runnable.run();
}
}
@ -122,14 +101,12 @@ public class SetBlockQueue
}
final long newLast = System.currentTimeMillis();
last = Math.max(newLast - 50, last);
while ((blocks.size() > 0) && ((System.currentTimeMillis() - last) < (50 + allocate)))
{
while ((blocks.size() > 0) && ((System.currentTimeMillis() - last) < (50 + allocate))) {
if (locked) {
return;
}
final Iterator<Entry<ChunkWrapper, PlotBlock[][]>> iter = blocks.entrySet().iterator();
if (!iter.hasNext())
{
if (!iter.hasNext()) {
PS.get().TASK.cancelTask(TaskManager.tasks.get(current));
final ArrayDeque<Runnable> tasks = runnables;
lastInt = -1;
@ -138,10 +115,8 @@ public class SetBlockQueue
running = false;
blocks = null;
slow = false;
if (tasks != null)
{
for (final Runnable runnable : tasks)
{
if (tasks != null) {
for (final Runnable runnable : tasks) {
runnable.run();
}
}
@ -153,25 +128,19 @@ public class SetBlockQueue
final int X = chunk.x << 4;
final int Z = chunk.z << 4;
final String world = chunk.world;
if (slow)
{
if (slow) {
boolean once = false;
for (int j = 0; j < blocks.length; j++)
{
for (int j = 0; j < blocks.length; j++) {
final PlotBlock[] blocksj = blocks[j];
if (blocksj != null)
{
if (blocksj != null) {
final long start = System.currentTimeMillis();
for (int k = 0; k < blocksj.length; k++)
{
if (once && ((System.currentTimeMillis() - start) > allocate))
{
for (int k = 0; k < blocksj.length; k++) {
if (once && ((System.currentTimeMillis() - start) > allocate)) {
SetBlockQueue.blocks.put(n.getKey(), blocks);
return;
}
final PlotBlock block = blocksj[k];
if (block != null)
{
if (block != null) {
final int x = MainUtil.x_loc[j][k];
final int y = MainUtil.y_loc[j][k];
final int z = MainUtil.z_loc[j][k];
@ -186,16 +155,12 @@ public class SetBlockQueue
return;
}
SetBlockQueue.blocks.remove(n.getKey());
for (int j = 0; j < blocks.length; j++)
{
for (int j = 0; j < blocks.length; j++) {
final PlotBlock[] blocksj = blocks[j];
if (blocksj != null)
{
for (int k = 0; k < blocksj.length; k++)
{
if (blocksj != null) {
for (int k = 0; k < blocksj.length; k++) {
final PlotBlock block = blocksj[k];
if (block != null)
{
if (block != null) {
final int x = MainUtil.x_loc[j][k];
final int y = MainUtil.y_loc[j][k];
final int z = MainUtil.z_loc[j][k];
@ -211,171 +176,137 @@ public class SetBlockQueue
running = true;
}
}
public static void setChunk(final String world, final ChunkLoc loc, final PlotBlock[][] result)
{
public static void setChunk(final String world, final ChunkLoc loc, final PlotBlock[][] result) {
locked = true;
if (!running)
{
if (!running) {
init();
}
final ChunkWrapper wrap = new ChunkWrapper(world, loc.x, loc.z);
blocks.put(wrap, result);
locked = false;
}
public static void setBlock(final String world, int x, final int y, int z, final PlotBlock block)
{
public static void setBlock(final String world, int x, final int y, int z, final PlotBlock block) {
locked = true;
if (!running)
{
if (!running) {
init();
}
final int X = x >> 4;
final int Z = z >> 4;
x -= X << 4;
z -= Z << 4;
final ChunkWrapper wrap = new ChunkWrapper(world, X, Z);
PlotBlock[][] result;
result = blocks.get(wrap);
if (!blocks.containsKey(wrap))
{
result = new PlotBlock[16][];
blocks.put(wrap, result);
}
if ((y > 255) || (y < 0))
{
locked = false;
return;
}
if (result[y >> 4] == null)
{
result[y >> 4] = new PlotBlock[4096];
}
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = block;
locked = false;
final int Z = z >> 4;
x -= X << 4;
z -= Z << 4;
final ChunkWrapper wrap = new ChunkWrapper(world, X, Z);
PlotBlock[][] result;
result = blocks.get(wrap);
if (!blocks.containsKey(wrap)) {
result = new PlotBlock[16][];
blocks.put(wrap, result);
}
if ((y > 255) || (y < 0)) {
locked = false;
return;
}
if (result[y >> 4] == null) {
result[y >> 4] = new PlotBlock[4096];
}
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = block;
locked = false;
}
public static void setData(final String world, int x, final int y, int z, final byte data)
{
public static void setData(final String world, int x, final int y, int z, final byte data) {
locked = true;
if (!running)
{
if (!running) {
init();
}
final int X = x >> 4;
final int Z = z >> 4;
x -= X << 4;
z -= Z << 4;
final ChunkWrapper wrap = new ChunkWrapper(world, X, Z);
PlotBlock[][] result;
result = blocks.get(wrap);
if (result == null)
{
if (blocks == null)
{
init();
}
result = new PlotBlock[16][];
blocks.put(wrap, result);
}
if ((y > 255) || (y < 0))
{
locked = false;
return;
}
if (result[y >> 4] == null)
{
result[y >> 4] = new PlotBlock[4096];
}
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = new PlotBlock((short) -1, data);
locked = false;
final int Z = z >> 4;
x -= X << 4;
z -= Z << 4;
final ChunkWrapper wrap = new ChunkWrapper(world, X, Z);
PlotBlock[][] result;
result = blocks.get(wrap);
if (result == null) {
if (blocks == null) {
init();
}
result = new PlotBlock[16][];
blocks.put(wrap, result);
}
if ((y > 255) || (y < 0)) {
locked = false;
return;
}
if (result[y >> 4] == null) {
result[y >> 4] = new PlotBlock[4096];
}
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = new PlotBlock((short) -1, data);
locked = false;
}
public static void setBlock(final String world, int x, final int y, int z, final int id)
{
public static void setBlock(final String world, int x, final int y, int z, final int id) {
locked = true;
if (!running)
{
if (!running) {
init();
}
final int X = x >> 4;
final int Z = z >> 4;
x -= X << 4;
z -= Z << 4;
final ChunkWrapper wrap = new ChunkWrapper(world, X, Z);
PlotBlock[][] result;
result = blocks.get(wrap);
if (result == null)
{
if (blocks == null)
{
init();
}
result = new PlotBlock[16][];
blocks.put(wrap, result);
}
if ((y > 255) || (y < 0))
{
locked = false;
return;
}
if (result[y >> 4] == null)
{
result[y >> 4] = new PlotBlock[4096];
}
if (id == lastInt)
{
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = lastBlock;
}
else
{
lastInt = id;
lastBlock = new PlotBlock((short) id, (byte) 0);
}
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = lastBlock;
locked = false;
final int Z = z >> 4;
x -= X << 4;
z -= Z << 4;
final ChunkWrapper wrap = new ChunkWrapper(world, X, Z);
PlotBlock[][] result;
result = blocks.get(wrap);
if (result == null) {
if (blocks == null) {
init();
}
result = new PlotBlock[16][];
blocks.put(wrap, result);
}
if ((y > 255) || (y < 0)) {
locked = false;
return;
}
if (result[y >> 4] == null) {
result[y >> 4] = new PlotBlock[4096];
}
if (id == lastInt) {
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = lastBlock;
} else {
lastInt = id;
lastBlock = new PlotBlock((short) id, (byte) 0);
}
result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = lastBlock;
locked = false;
}
public static class ChunkWrapper
{
public static class ChunkWrapper {
public final int x;
public final int z;
public final String world;
public ChunkWrapper(final String world, final int x, final int z)
{
public ChunkWrapper(final String world, final int x, final int z) {
this.world = world;
this.x = x;
this.z = z;
}
@Override
public int hashCode()
{
public int hashCode() {
int result;
if (x >= 0)
{
if (z >= 0)
{
if (x >= 0) {
if (z >= 0) {
result = (x * x) + (3 * x) + (2 * x * z) + z + (z * z);
}
else
{
} else {
final int y1 = -z;
result = (x * x) + (3 * x) + (2 * x * y1) + y1 + (y1 * y1) + 1;
}
}
else
{
} else {
final int x1 = -x;
if (z >= 0)
{
if (z >= 0) {
result = -((x1 * x1) + (3 * x1) + (2 * x1 * z) + z + (z * z));
}
else
{
} else {
final int y1 = -z;
result = -((x1 * x1) + (3 * x1) + (2 * x1 * y1) + y1 + (y1 * y1) + 1);
}
@ -383,13 +314,18 @@ public class SetBlockQueue
result = (result * 31) + world.hashCode();
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; }
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ChunkWrapper other = (ChunkWrapper) obj;
return ((x == other.x) && (z == other.z) && (world.equals(other.world)));
}

View File

@ -8,19 +8,18 @@ import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.SetupObject;
public abstract class SetupUtils
{
public abstract class SetupUtils {
public static SetupUtils manager;
public final static Map<String, SetupObject> setupMap = new HashMap<>();
public static HashMap<String, PlotGenerator<?>> generators = new HashMap<>();
public abstract void updateGenerators();
public abstract String getGenerator(final PlotWorld plotworld);
public abstract String setupWorld(final SetupObject object);
public abstract void removePopulator(final String world, final PlotCluster cluster);
}

View File

@ -29,57 +29,49 @@ import java.util.Collections;
*
*/
@SuppressWarnings("unused")
public class StringComparison<T>
*/
@SuppressWarnings("unused")
public class StringComparison<T> {
private T bestMatch;
private double match = Integer.MAX_VALUE;
private double match = Integer.MAX_VALUE;
private T bestMatchObject;
/**
* Constructor
*
* @param input Input Base Value
* @param objects Objects to compare
*/
* @param objects Objects to compare
*/
public StringComparison(final String input, final T[] objects) {
init(input, objects);
}
init(input, objects);
}
public StringComparison(final String input, final Collection<T> objects) {
init(input, (T[]) objects.toArray());
init(input, (T[]) objects.toArray());
}
/**
* You should call init(...) when you are ready to get a String comparison value
*/
public StringComparison()
{}
* You should call init(...) when you are ready to get a String comparison value
*/
public StringComparison() {}
public void init(String input, final T[] objects) {
int c;
this.bestMatch = objects[0];
this.bestMatchObject = objects[0];
input = input.toLowerCase();
for (final T o : objects)
{
this.bestMatchObject = objects[0];
input = input.toLowerCase();
for (final T o : objects) {
if ((c = compare(input, getString(o).toLowerCase())) < this.match) {
this.match = c;
this.bestMatch = o;
this.bestMatchObject = o;
}
}
}
}
}
public String getString(final T o) {
return o.toString();
return o.toString();
}
/**
@ -88,20 +80,17 @@ public class StringComparison<T>
* @param s1 String Base
* @param s2 Object
*
* @return match
*/
* @return match
*/
{
int distance = StringMan.getLevenshteinDistance(s1, s2);
public static int compare(final String s1, final String s2) {
int distance = StringMan.getLevenshteinDistance(s1, s2);
if (s2.contains(s1)) {
distance -= (Math.min(s1.length(), s2.length()));
}
distance -= (Math.min(s1.length(), s2.length()));
}
if (s2.startsWith(s1)) {
distance -= 4;
}
return distance;
return distance;
}
/**
@ -109,18 +98,16 @@ public class StringComparison<T>
*
* @param s string to split
*
* @return ArrayList
*/
* @return ArrayList
*/
public static ArrayList<String> wLetterPair(final String s) {
final ArrayList<String> aPairs = new ArrayList<>();
final String[] wo = s.split("\\s");
final ArrayList<String> aPairs = new ArrayList<>();
final String[] wo = s.split("\\s");
for (final String aWo : wo) {
final String[] po = sLetterPair(aWo);
Collections.addAll(aPairs, po);
}
return aPairs;
return aPairs;
}
/**
@ -128,63 +115,56 @@ public class StringComparison<T>
*
* @param s string to split
*
* @return Array
*/
* @return Array
*/
public static String[] sLetterPair(final String s) {
final int numPair = s.length() - 1;
final String[] p = new String[numPair];
final int numPair = s.length() - 1;
final String[] p = new String[numPair];
for (int i = 0; i < numPair; i++) {
p[i] = s.substring(i, i + 2);
}
return p;
return p;
}
/**
* Get the object
*
* @return match object
*/
* @return match object
*/
public T getMatchObject() {
return this.bestMatchObject;
return this.bestMatchObject;
}
/**
* Get the best match value
*
* @return match value
*/
* @return match value
*/
public String getBestMatch() {
return getString(this.bestMatch);
return getString(this.bestMatch);
}
/**
* Will return both the match number, and the actual match string
*
* @return object[] containing: double, String
*/
* @return object[] containing: double, String
*/
public ComparisonResult getBestMatchAdvanced() {
return new ComparisonResult(this.match, this.bestMatch);
return new ComparisonResult(this.match, this.bestMatch);
}
/**
* The comparison result
*/
public class ComparisonResult
* The comparison result
*/
public class ComparisonResult {
public final T best;
public final T best;
public final double match;
/**
* The constructor
* @param match Match value
* @param best Best Match
*/
* @param best Best Match
*/
public ComparisonResult(final double match, final T best) {
this.match = match;

View File

@ -7,23 +7,18 @@ import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
public class StringMan
{
public static String replaceFromMap(final String string, final Map<String, String> replacements)
{
public class StringMan {
public static String replaceFromMap(final String string, final Map<String, String> replacements) {
final StringBuilder sb = new StringBuilder(string);
int size = string.length();
for (final Entry<String, String> entry : replacements.entrySet())
{
if (size == 0)
{
for (final Entry<String, String> entry : replacements.entrySet()) {
if (size == 0) {
break;
}
final String key = entry.getKey();
final String value = entry.getValue();
int start = sb.indexOf(key, 0);
while (start > -1)
{
while (start > -1) {
final int end = start + key.length();
final int nextSearchStart = start + value.length();
sb.replace(start, end, value);
@ -33,78 +28,69 @@ public class StringMan
}
return sb.toString();
}
public static String getString(final Object obj)
{
if (obj == null) { return "null"; }
if (obj.getClass() == String.class) { return (String) obj; }
if (obj.getClass().isArray())
{
public static String getString(final Object obj) {
if (obj == null) {
return "null";
}
if (obj.getClass() == String.class) {
return (String) obj;
}
if (obj.getClass().isArray()) {
String result = "";
String prefix = "";
for (int i = 0; i < Array.getLength(obj); i++)
{
for (int i = 0; i < Array.getLength(obj); i++) {
result += prefix + getString(Array.get(obj, i));
prefix = ",";
}
return "( " + result + " )";
}
else if (obj instanceof Collection<?>)
{
} else if (obj instanceof Collection<?>) {
String result = "";
String prefix = "";
for (final Object element : (Collection<?>) obj)
{
for (final Object element : (Collection<?>) obj) {
result += prefix + getString(element);
prefix = ",";
}
return "[ " + result + " ]";
}
else
{
} else {
return obj.toString();
}
}
public static String replaceFirst(final char c, final String s)
{
if (s == null) { return ""; }
if (s.isEmpty()) { return s; }
public static String replaceFirst(final char c, final String s) {
if (s == null) {
return "";
}
if (s.isEmpty()) {
return s;
}
char[] chars = s.toCharArray();
final char[] newChars = new char[chars.length];
int used = 0;
boolean found = false;
for (final char cc : chars)
{
if (!found && (c == cc))
{
for (final char cc : chars) {
if (!found && (c == cc)) {
found = true;
}
else
{
} else {
newChars[used++] = cc;
}
}
if (found)
{
if (found) {
chars = new char[newChars.length - 1];
System.arraycopy(newChars, 0, chars, 0, chars.length);
return String.valueOf(chars);
}
return s;
}
public static String replaceAll(final String string, final Object... pairs)
{
public static String replaceAll(final String string, final Object... pairs) {
final StringBuilder sb = new StringBuilder(string);
for (int i = 0; i < pairs.length; i += 2)
{
for (int i = 0; i < pairs.length; i += 2) {
final String key = pairs[i] + "";
final String value = pairs[i + 1] + "";
int start = sb.indexOf(key, 0);
while (start > -1)
{
while (start > -1) {
final int end = start + key.length();
final int nextSearchStart = start + value.length();
sb.replace(start, end, value);
@ -113,87 +99,79 @@ public class StringMan
}
return sb.toString();
}
public static boolean isAlphanumeric(final String str)
{
for (int i = 0; i < str.length(); i++)
{
public static boolean isAlphanumeric(final String str) {
for (int i = 0; i < str.length(); i++) {
final char c = str.charAt(i);
if ((c < 0x30) || ((c >= 0x3a) && (c <= 0x40)) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a)) { return false; }
if ((c < 0x30) || ((c >= 0x3a) && (c <= 0x40)) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a)) {
return false;
}
}
return true;
}
public static boolean isAlphanumericUnd(final String str)
{
for (int i = 0; i < str.length(); i++)
{
public static boolean isAlphanumericUnd(final String str) {
for (int i = 0; i < str.length(); i++) {
final char c = str.charAt(i);
if ((c < 0x30) || ((c >= 0x3a) && (c <= 0x40)) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a) || (c == '_')) { return false; }
if ((c < 0x30) || ((c >= 0x3a) && (c <= 0x40)) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a) || (c == '_')) {
return false;
}
}
return true;
}
public static boolean isAlpha(final String str)
{
for (int i = 0; i < str.length(); i++)
{
public static boolean isAlpha(final String str) {
for (int i = 0; i < str.length(); i++) {
final char c = str.charAt(i);
if ((c <= 0x40) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a)) { return false; }
if ((c <= 0x40) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a)) {
return false;
}
}
return true;
}
public static String join(final Collection<?> collection, final String delimiter)
{
public static String join(final Collection<?> collection, final String delimiter) {
return join(collection.toArray(), delimiter);
}
public static String joinOrdered(final Collection<?> collection, final String delimiter)
{
public static String joinOrdered(final Collection<?> collection, final String delimiter) {
final Object[] array = collection.toArray();
Arrays.sort(array, new Comparator<Object>()
{
Arrays.sort(array, new Comparator<Object>() {
@Override
public int compare(final Object a, final Object b)
{
public int compare(final Object a, final Object b) {
return a.hashCode() - b.hashCode();
}
});
return join(array, delimiter);
}
public static String join(final Collection<?> collection, final char delimiter)
{
public static String join(final Collection<?> collection, final char delimiter) {
return join(collection.toArray(), delimiter + "");
}
public static boolean isAsciiPrintable(final char c)
{
public static boolean isAsciiPrintable(final char c) {
return (c >= ' ') && (c < '');
}
public static boolean isAsciiPrintable(final String s)
{
for (final char c : s.toCharArray())
{
if (!isAsciiPrintable(c)) { return false; }
public static boolean isAsciiPrintable(final String s) {
for (final char c : s.toCharArray()) {
if (!isAsciiPrintable(c)) {
return false;
}
}
return true;
}
public static int getLevenshteinDistance(String s, String t)
{
public static int getLevenshteinDistance(String s, String t) {
int n = s.length();
int m = t.length();
if (n == 0)
{
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
else if (m == 0) { return n; }
if (n > m)
{
if (n > m) {
final String tmp = s;
s = t;
t = tmp;
@ -207,17 +185,14 @@ public class StringMan
int j;
char t_j;
int cost;
for (i = 0; i <= n; i++)
{
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++)
{
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++)
{
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
@ -227,64 +202,55 @@ public class StringMan
}
return p[n];
}
public static String join(final Object[] array, final String delimiter)
{
public static String join(final Object[] array, final String delimiter) {
final StringBuilder result = new StringBuilder();
for (int i = 0, j = array.length; i < j; i++)
{
if (i > 0)
{
for (int i = 0, j = array.length; i < j; i++) {
if (i > 0) {
result.append(delimiter);
}
result.append(array[i]);
}
return result.toString();
}
public static String join(final int[] array, final String delimiter)
{
public static String join(final int[] array, final String delimiter) {
final Integer[] wrapped = new Integer[array.length];
for (int i = 0; i < array.length; i++)
{
for (int i = 0; i < array.length; i++) {
wrapped[i] = array[i];
}
return join(wrapped, delimiter);
}
public static boolean isEqualToAny(final String a, final String... args)
{
for (final String arg : args)
{
if (StringMan.isEqual(a, arg)) { return true; }
public static boolean isEqualToAny(final String a, final String... args) {
for (final String arg : args) {
if (StringMan.isEqual(a, arg)) {
return true;
}
}
return false;
}
public static boolean isEqualIgnoreCaseToAny(final String a, final String... args)
{
for (final String arg : args)
{
if (StringMan.isEqualIgnoreCase(a, arg)) { return true; }
public static boolean isEqualIgnoreCaseToAny(final String a, final String... args) {
for (final String arg : args) {
if (StringMan.isEqualIgnoreCase(a, arg)) {
return true;
}
}
return false;
}
public static boolean isEqual(final String a, final String b)
{
public static boolean isEqual(final String a, final String b) {
return ((a == b) || ((a != null) && (b != null) && (a.length() == b.length()) && (a.hashCode() == b.hashCode()) && a.equals(b)));
}
public static boolean isEqualIgnoreCase(final String a, final String b)
{
public static boolean isEqualIgnoreCase(final String a, final String b) {
return ((a == b) || ((a != null) && (b != null) && (a.length() == b.length()) && a.equalsIgnoreCase(b)));
}
public static String repeat(final String s, final int n)
{
public static String repeat(final String s, final int n) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
{
for (int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();

View File

@ -6,101 +6,88 @@ import java.util.concurrent.atomic.AtomicInteger;
import com.intellectualcrafters.plot.PS;
public abstract class TaskManager
{
public abstract class TaskManager {
public static HashSet<String> TELEPORT_QUEUE = new HashSet<>();
public static AtomicInteger index = new AtomicInteger(0);
public static HashMap<Integer, Integer> tasks = new HashMap<>();
public static int runTaskRepeat(final Runnable r, final int interval)
{
if (r != null)
{
if (PS.get().TASK == null) { throw new IllegalArgumentException("disabled"); }
public static int runTaskRepeat(final Runnable r, final int interval) {
if (r != null) {
if (PS.get().TASK == null) {
throw new IllegalArgumentException("disabled");
}
return PS.get().TASK.taskRepeat(r, interval);
}
return -1;
}
public static int runTaskRepeatAsync(final Runnable r, final int interval)
{
if (r != null)
{
if (PS.get().TASK == null) { throw new IllegalArgumentException("disabled"); }
public static int runTaskRepeatAsync(final Runnable r, final int interval) {
if (r != null) {
if (PS.get().TASK == null) {
throw new IllegalArgumentException("disabled");
}
return PS.get().TASK.taskRepeat(r, interval);
}
return -1;
}
public static void runTaskAsync(final Runnable r)
{
if (r != null)
{
if (PS.get().TASK == null)
{
public static void runTaskAsync(final Runnable r) {
if (r != null) {
if (PS.get().TASK == null) {
r.run();
return;
}
PS.get().TASK.taskAsync(r);
}
}
public static void runTask(final Runnable r)
{
if (r != null)
{
if (PS.get().TASK == null)
{
public static void runTask(final Runnable r) {
if (r != null) {
if (PS.get().TASK == null) {
r.run();
return;
}
PS.get().TASK.task(r);
}
}
/**
* Run task later (delay in ticks)
* @param r
* @param delay
*/
public static void runTaskLater(final Runnable r, final int delay)
{
if (r != null)
{
if (PS.get().TASK == null)
{
public static void runTaskLater(final Runnable r, final int delay) {
if (r != null) {
if (PS.get().TASK == null) {
r.run();
return;
}
PS.get().TASK.taskLater(r, delay);
}
}
public static void runTaskLaterAsync(final Runnable r, final int delay)
{
if (r != null)
{
if (PS.get().TASK == null)
{
public static void runTaskLaterAsync(final Runnable r, final int delay) {
if (r != null) {
if (PS.get().TASK == null) {
r.run();
return;
}
PS.get().TASK.taskLaterAsync(r, delay);
}
}
public abstract int taskRepeat(final Runnable r, final int interval);
public abstract int taskRepeatAsync(final Runnable r, final int interval);
public abstract void taskAsync(final Runnable r);
public abstract void task(final Runnable r);
public abstract void taskLater(final Runnable r, final int delay);
public abstract void taskLaterAsync(final Runnable r, final int delay);
public abstract void cancelTask(final int task);
}

View File

@ -13,16 +13,14 @@ import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public class UUIDHandler
{
public class UUIDHandler {
public static UUIDHandlerImplementation implementation;
public static void add(final StringWrapper name, final UUID uuid)
{
public static void add(final StringWrapper name, final UUID uuid) {
implementation.add(name, uuid);
}
/**
* Get the map containing all names/uuids
*
@ -30,11 +28,10 @@ public class UUIDHandler
*
* @see com.google.common.collect.BiMap
*/
public static BiMap<StringWrapper, UUID> getUuidMap()
{
public static BiMap<StringWrapper, UUID> getUuidMap() {
return implementation.getUUIDMap();
}
/**
* Check if a uuid is cached
*
@ -44,11 +41,10 @@ public class UUIDHandler
*
* @see com.google.common.collect.BiMap#containsValue(Object)
*/
public static boolean uuidExists(final UUID uuid)
{
public static boolean uuidExists(final UUID uuid) {
return implementation.uuidExists(uuid);
}
/**
* Check if a name is cached
*
@ -58,18 +54,14 @@ public class UUIDHandler
*
* @see com.google.common.collect.BiMap#containsKey(Object)
*/
public static boolean nameExists(final StringWrapper name)
{
public static boolean nameExists(final StringWrapper name) {
return implementation.nameExists(name);
}
public static HashSet<UUID> getAllUUIDS()
{
public static HashSet<UUID> getAllUUIDS() {
final HashSet<UUID> uuids = new HashSet<>();
for (final Plot plot : PS.get().getPlotsRaw())
{
if (plot.owner != null)
{
for (final Plot plot : PS.get().getPlotsRaw()) {
if (plot.owner != null) {
uuids.add(plot.owner);
uuids.addAll(plot.getTrusted());
uuids.addAll(plot.getMembers());
@ -78,69 +70,56 @@ public class UUIDHandler
}
return uuids;
}
public static UUIDWrapper getUUIDWrapper()
{
public static UUIDWrapper getUUIDWrapper() {
return implementation.getUUIDWrapper();
}
public static void setUUIDWrapper(final UUIDWrapper wrapper)
{
public static void setUUIDWrapper(final UUIDWrapper wrapper) {
implementation.setUUIDWrapper(wrapper);
}
public static void startCaching(final Runnable whenDone)
{
public static void startCaching(final Runnable whenDone) {
implementation.startCaching(whenDone);
}
public static void cache(final BiMap<StringWrapper, UUID> toAdd)
{
public static void cache(final BiMap<StringWrapper, UUID> toAdd) {
implementation.add(toAdd);
}
public static UUID getUUID(final PlotPlayer player)
{
public static UUID getUUID(final PlotPlayer player) {
return implementation.getUUID(player);
}
public static UUID getUUID(final OfflinePlotPlayer player)
{
public static UUID getUUID(final OfflinePlotPlayer player) {
return implementation.getUUID(player);
}
public static String getName(final UUID uuid)
{
public static String getName(final UUID uuid) {
return implementation.getName(uuid);
}
public static PlotPlayer getPlayer(final UUID uuid)
{
public static PlotPlayer getPlayer(final UUID uuid) {
return implementation.getPlayer(uuid);
}
public static PlotPlayer getPlayer(final String name)
{
public static PlotPlayer getPlayer(final String name) {
return implementation.getPlayer(name);
}
public static UUID getUUID(final String name, final RunnableVal<UUID> ifFetch)
{
public static UUID getUUID(final String name, final RunnableVal<UUID> ifFetch) {
return implementation.getUUID(name, ifFetch);
}
public static UUID getCachedUUID(final String name, final RunnableVal<UUID> ifFetch)
{
public static UUID getCachedUUID(final String name, final RunnableVal<UUID> ifFetch) {
return implementation.getUUIDMap().get(new StringWrapper(name));
}
public static Map<String, PlotPlayer> getPlayers()
{
public static Map<String, PlotPlayer> getPlayers() {
return implementation.getPlayers();
}
public static void handleShutdown()
{
public static void handleShutdown() {
implementation.handleShutdown();
}
}

View File

@ -20,72 +20,62 @@ import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public abstract class UUIDHandlerImplementation
{
public abstract class UUIDHandlerImplementation {
private BiMap<StringWrapper, UUID> uuidMap = HashBiMap.create(new HashMap<StringWrapper, UUID>());
public boolean CACHED = false;
public UUIDWrapper uuidWrapper = null;
public final HashMap<String, PlotPlayer> players;
public UUIDHandlerImplementation(final UUIDWrapper wrapper)
{
public UUIDHandlerImplementation(final UUIDWrapper wrapper) {
uuidWrapper = wrapper;
players = new HashMap<>();
}
/**
* If the UUID is not found, some commands can request to fetch the UUID when possible
* @param player
* @param ifFetch
*/
public abstract void fetchUUID(final String name, final RunnableVal<UUID> ifFetch);
/**
* Start UUID caching (this should be an async task)
* Recommended to override this is you want to cache offline players
*/
public boolean startCaching(final Runnable whenDone)
{
if (CACHED) { return false; }
public boolean startCaching(final Runnable whenDone) {
if (CACHED) {
return false;
}
return CACHED = true;
}
public UUIDWrapper getUUIDWrapper()
{
public UUIDWrapper getUUIDWrapper() {
return uuidWrapper;
}
public void setUUIDWrapper(final UUIDWrapper wrapper)
{
public void setUUIDWrapper(final UUIDWrapper wrapper) {
uuidWrapper = wrapper;
}
public void rename(final UUID uuid, final StringWrapper name)
{
public void rename(final UUID uuid, final StringWrapper name) {
uuidMap.inverse().remove(uuid);
uuidMap.put(name, uuid);
}
public void add(final BiMap<StringWrapper, UUID> toAdd)
{
if (uuidMap.size() == 0)
{
public void add(final BiMap<StringWrapper, UUID> toAdd) {
if (uuidMap.size() == 0) {
uuidMap = toAdd;
}
for (final Map.Entry<StringWrapper, UUID> entry : toAdd.entrySet())
{
for (final Map.Entry<StringWrapper, UUID> entry : toAdd.entrySet()) {
final UUID uuid = entry.getValue();
final StringWrapper name = entry.getKey();
if ((uuid == null) || (name == null))
{
if ((uuid == null) || (name == null)) {
continue;
}
final BiMap<UUID, StringWrapper> inverse = uuidMap.inverse();
if (inverse.containsKey(uuid))
{
if (uuidMap.containsKey(name))
{
if (inverse.containsKey(uuid)) {
if (uuidMap.containsKey(name)) {
continue;
}
rename(uuid, name);
@ -95,49 +85,40 @@ public abstract class UUIDHandlerImplementation
}
PS.debug(C.PREFIX.s() + "&6Cached a total of: " + uuidMap.size() + " UUIDs");
}
public HashSet<UUID> unknown = new HashSet<>();
public boolean add(final StringWrapper name, final UUID uuid)
{
if ((uuid == null)) { return false; }
if (name == null)
{
try
{
public boolean add(final StringWrapper name, final UUID uuid) {
if ((uuid == null)) {
return false;
}
if (name == null) {
try {
unknown.add(uuid);
}
catch (final Exception e)
{
} catch (final Exception e) {
PS.log("&c(minor) Invalid UUID mapping: " + uuid);
e.printStackTrace();
}
return false;
}
/*
* lazy UUID conversion:
* - Useful if the person misconfigured the database, or settings before PlotMe conversion
*/
if (!Settings.OFFLINE_MODE)
{
if (!Settings.OFFLINE_MODE) {
UUID offline = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8));
if (!unknown.contains(offline) && !name.value.equals(name.value.toLowerCase()))
{
if (!unknown.contains(offline) && !name.value.equals(name.value.toLowerCase())) {
offline = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8));
if (!unknown.contains(offline))
{
if (!unknown.contains(offline)) {
offline = null;
}
}
if (offline != null)
{
if (offline != null) {
unknown.remove(offline);
final Set<Plot> plots = PS.get().getPlots(offline);
if (plots.size() > 0)
{
for (final Plot plot : PS.get().getPlots(offline))
{
if (plots.size() > 0) {
for (final Plot plot : PS.get().getPlots(offline)) {
plot.owner = uuid;
}
DBFunc.replaceUUID(offline, uuid);
@ -147,16 +128,12 @@ public abstract class UUIDHandlerImplementation
}
}
}
try
{
try {
final UUID offline = uuidMap.put(name, uuid);
if ((offline != null) && !offline.equals(uuid))
{
if ((offline != null) && !offline.equals(uuid)) {
final Set<Plot> plots = PS.get().getPlots(offline);
if (plots.size() > 0)
{
for (final Plot plot : PS.get().getPlots(offline))
{
if (plots.size() > 0) {
for (final Plot plot : PS.get().getPlots(offline)) {
plot.owner = uuid;
}
DBFunc.replaceUUID(offline, uuid);
@ -165,13 +142,12 @@ public abstract class UUIDHandlerImplementation
PS.debug("&6PlotSquared will update incorrect entries when the user logs in, or you can reconstruct your database.");
}
}
}
catch (final Exception e)
{
} catch (final Exception e) {
final BiMap<UUID, StringWrapper> inverse = uuidMap.inverse();
if (inverse.containsKey(uuid))
{
if (uuidMap.containsKey(name)) { return false; }
if (inverse.containsKey(uuid)) {
if (uuidMap.containsKey(name)) {
return false;
}
rename(uuid, name);
return false;
}
@ -179,93 +155,93 @@ public abstract class UUIDHandlerImplementation
}
return true;
}
public boolean uuidExists(final UUID uuid)
{
public boolean uuidExists(final UUID uuid) {
return uuidMap.containsValue(uuid);
}
public BiMap<StringWrapper, UUID> getUUIDMap()
{
public BiMap<StringWrapper, UUID> getUUIDMap() {
return uuidMap;
}
public boolean nameExists(final StringWrapper wrapper)
{
public boolean nameExists(final StringWrapper wrapper) {
return uuidMap.containsKey(wrapper);
}
public void handleShutdown()
{
public void handleShutdown() {
players.clear();
uuidMap.clear();
uuidWrapper = null;
}
public String getName(final UUID uuid)
{
if (uuid == null) { return null; }
public String getName(final UUID uuid) {
if (uuid == null) {
return null;
}
// check online
final PlotPlayer player = getPlayer(uuid);
if (player != null) { return player.getName(); }
if (player != null) {
return player.getName();
}
// check cache
final StringWrapper name = uuidMap.inverse().get(uuid);
if (name != null) { return name.value; }
if (name != null) {
return name.value;
}
return null;
}
public UUID getUUID(final String name, final RunnableVal<UUID> ifFetch)
{
if ((name == null) || (name.length() == 0)) { return null; }
public UUID getUUID(final String name, final RunnableVal<UUID> ifFetch) {
if ((name == null) || (name.length() == 0)) {
return null;
}
// check online
final PlotPlayer player = getPlayer(name);
if (player != null) { return player.getUUID(); }
if (player != null) {
return player.getUUID();
}
// check cache
final StringWrapper wrap = new StringWrapper(name);
UUID uuid = uuidMap.get(wrap);
if (uuid != null) { return uuid; }
if (uuid != null) {
return uuid;
}
// Read from disk OR convert directly to offline UUID
if (Settings.OFFLINE_MODE)
{
if (Settings.OFFLINE_MODE) {
uuid = uuidWrapper.getUUID(name);
add(new StringWrapper(name), uuid);
return uuid;
}
if (Settings.UUID_FROM_DISK && (ifFetch != null))
{
if (Settings.UUID_FROM_DISK && (ifFetch != null)) {
fetchUUID(name, ifFetch);
return null;
}
return null;
}
public UUID getUUID(final PlotPlayer player)
{
public UUID getUUID(final PlotPlayer player) {
return uuidWrapper.getUUID(player);
}
public UUID getUUID(final OfflinePlotPlayer player)
{
public UUID getUUID(final OfflinePlotPlayer player) {
return uuidWrapper.getUUID(player);
}
public PlotPlayer getPlayer(final UUID uuid)
{
for (final PlotPlayer player : players.values())
{
if (player.getUUID().equals(uuid)) { return player; }
public PlotPlayer getPlayer(final UUID uuid) {
for (final PlotPlayer player : players.values()) {
if (player.getUUID().equals(uuid)) {
return player;
}
}
return null;
}
public PlotPlayer getPlayer(final String name)
{
public PlotPlayer getPlayer(final String name) {
return players.get(name);
}
public Map<String, PlotPlayer> getPlayers()
{
public Map<String, PlotPlayer> getPlayers() {
return players;
}
}

View File

@ -7,62 +7,52 @@ import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.Command;
public class HelpMenu
{
public class HelpMenu {
public static final int PER_PAGE = 5;
private final PlotPlayer _player;
private HelpPage _page = new HelpPage(CommandCategory.ACTIONS, 0, 0);
private int _maxPage;
private CommandCategory _commandCategory;
private List<Command<PlotPlayer>> _commands;
public HelpMenu(final PlotPlayer player)
{
public HelpMenu(final PlotPlayer player) {
_player = player;
}
public HelpMenu setCategory(final CommandCategory commandCategory)
{
public HelpMenu setCategory(final CommandCategory commandCategory) {
_commandCategory = commandCategory;
return this;
}
public HelpMenu getCommands()
{
public HelpMenu getCommands() {
_commands = MainCommand.getCommands(_commandCategory, _player);
return this;
}
public HelpMenu generateMaxPages()
{
public HelpMenu generateMaxPages() {
_maxPage = Math.max((_commands.size() - 1) / PER_PAGE, 0);
return this;
}
public HelpMenu generatePage(int currentPage, final String label)
{
if (currentPage > _maxPage)
{
public HelpMenu generatePage(int currentPage, final String label) {
if (currentPage > _maxPage) {
currentPage = _maxPage;
}
if (currentPage < 0)
{
if (currentPage < 0) {
currentPage = 0;
}
_page = new HelpPage(_commandCategory, currentPage, _maxPage);
final int max = Math.min((currentPage * PER_PAGE) + (PER_PAGE - 1), _commands.size());
for (int i = currentPage * PER_PAGE; i < max; i++)
{
for (int i = currentPage * PER_PAGE; i < max; i++) {
_page.addHelpItem(new HelpObject(_commands.get(i), label));
}
return this;
}
public void render()
{
public void render() {
_page.render(_player);
}
}

View File

@ -5,32 +5,29 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.Command;
public class HelpObject
{
public class HelpObject {
private final Command _command;
private final String _rendered;
public HelpObject(final Command command, final String label)
{
public HelpObject(final Command command, final String label) {
_command = command;
_rendered = StringMan.replaceAll(C.HELP_ITEM.s(), "%usage%", _command.getUsage().replaceAll("\\{label\\}", label), "[%alias%]",
_command.getAliases().size() > 0 ? "(" + StringMan.join(_command.getAliases(), "|") + ")" : "", "%desc%", _command.getDescription(), "%arguments%",
buildArgumentList(_command.getRequiredArguments()), "{label}", label);
}
@Override
public String toString()
{
public String toString() {
return _rendered;
}
private String buildArgumentList(final Argument[] arguments)
{
if (arguments == null) { return ""; }
private String buildArgumentList(final Argument[] arguments) {
if (arguments == null) {
return "";
}
final StringBuilder builder = new StringBuilder();
for (final Argument<?> argument : arguments)
{
for (final Argument<?> argument : arguments) {
builder.append("[").append(argument.getName()).append(" (").append(argument.getExample()).append(")],");
}
return arguments.length > 0 ? builder.substring(0, builder.length() - 1) : "";

View File

@ -8,41 +8,30 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
public class HelpPage
{
public class HelpPage {
private final List<HelpObject> _helpObjecs;
private final String _header;
public HelpPage(final CommandCategory category, final int currentPage, final int maxPages)
{
public HelpPage(final CommandCategory category, final int currentPage, final int maxPages) {
_helpObjecs = new ArrayList<>();
_header = C.HELP_PAGE_HEADER.s()
.replace("%category%", category == null ? "ALL" : category.toString())
.replace("%current%", (currentPage + 1) + "")
.replace("%max%", (maxPages + 1) + "");
_header = C.HELP_PAGE_HEADER.s().replace("%category%", category == null ? "ALL" : category.toString()).replace("%current%", (currentPage + 1) + "").replace("%max%", (maxPages + 1) + "");
}
public void render(final PlotPlayer player)
{
if (_helpObjecs.size() < 1)
{
public void render(final PlotPlayer player) {
if (_helpObjecs.size() < 1) {
MainUtil.sendMessage(player, C.NOT_VALID_NUMBER, "(0)");
}
else
{
} else {
MainUtil.sendMessage(player, C.HELP_HEADER.s(), false);
MainUtil.sendMessage(player, _header, false);
for (final HelpObject object : _helpObjecs)
{
for (final HelpObject object : _helpObjecs) {
MainUtil.sendMessage(player, object.toString(), false);
}
MainUtil.sendMessage(player, C.HELP_FOOTER.s(), false);
}
}
public void addHelpItem(final HelpObject object)
{
public void addHelpItem(final HelpObject object) {
_helpObjecs.add(object);
}
}