Revert dors commit

This commit is contained in:
Sauilitired 2018-12-27 17:29:35 +01:00
parent 76113cb0ab
commit 249b5d4068
No known key found for this signature in database
GPG Key ID: C0207FF7EA146678
112 changed files with 2254 additions and 1800 deletions

View File

@ -72,7 +72,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
pluginsField.setAccessible(true); pluginsField.setAccessible(true);
lookupNamesField.setAccessible(true); lookupNamesField.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) pluginsField.get(manager); List<Plugin> plugins = (List<Plugin>) pluginsField.get(manager);
plugins.removeIf(plugin -> plugin.getName().startsWith("PlotMe")); Iterator<Plugin> iter = plugins.iterator();
while (iter.hasNext()) {
if (iter.next().getName().startsWith("PlotMe")) {
iter.remove();
}
}
Map<String, Plugin> lookupNames = Map<String, Plugin> lookupNames =
(Map<String, Plugin>) lookupNamesField.get(manager); (Map<String, Plugin>) lookupNamesField.get(manager);
lookupNames.remove("PlotMe"); lookupNames.remove("PlotMe");
@ -196,8 +201,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
this.methodUnloadChunk0 = classCraftWorld.getRealClass() this.methodUnloadChunk0 = classCraftWorld.getRealClass()
.getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); .getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class);
this.methodUnloadChunk0.setAccessible(true); this.methodUnloadChunk0.setAccessible(true);
} catch (Throwable e) { } catch (Throwable ignore) {
e.printStackTrace(); ignore.printStackTrace();
} }
} }
final PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); final PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
@ -221,7 +226,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
if (id != null) { if (id != null) {
final Plot plot = area.getOwnedPlot(id); final Plot plot = area.getOwnedPlot(id);
if (plot != null) { if (plot != null) {
if (PlotPlayer.wrap(plot.guessOwner()) == null) { if (PlotPlayer.wrap(plot.owner) == null) {
if (world.getKeepSpawnInMemory()) { if (world.getKeepSpawnInMemory()) {
world.setKeepSpawnInMemory(false); world.setKeepSpawnInMemory(false);
return; return;
@ -646,8 +651,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override public boolean initPlotMeConverter() { @Override public boolean initPlotMeConverter() {
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) { if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return true; return true;
} else } else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
return new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017()); return true;
}
return false;
} }
@Override @Nullable public GeneratorWrapper<?> getGenerator(@NonNull final String world, @Override @Nullable public GeneratorWrapper<?> getGenerator(@NonNull final String world,

View File

@ -26,7 +26,7 @@ public final class ArrayWrapper<E> {
* *
* @param elements The elements of the array. * @param elements The elements of the array.
*/ */
@SafeVarargs public ArrayWrapper(E... elements) { public ArrayWrapper(E... elements) {
setArray(elements); setArray(elements);
} }

View File

@ -56,7 +56,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
String clickActionData = null; String clickActionData = null;
String hoverActionName = null; String hoverActionName = null;
JsonRepresentedObject hoverActionData = null; JsonRepresentedObject hoverActionData = null;
TextualComponent text; TextualComponent text = null;
String insertionData = null; String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>(); ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
@ -123,7 +123,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
if (insertionData != null) { if (insertionData != null) {
json.name("insertion").value(insertionData); json.name("insertion").value(insertionData);
} }
if (translationReplacements.size() > 0 && TextualComponent.isTranslatableText(text)) { if (translationReplacements.size() > 0 && text != null && TextualComponent
.isTranslatableText(text)) {
json.name("with").beginArray(); json.name("with").beginArray();
for (JsonRepresentedObject obj : translationReplacements) { for (JsonRepresentedObject obj : translationReplacements) {
obj.writeJson(json); obj.writeJson(json);

View File

@ -181,13 +181,13 @@ public final class Reflection {
*/ */
public synchronized static Method getMethod(Class<?> clazz, String name, Class<?>... args) { public synchronized static Method getMethod(Class<?> clazz, String name, Class<?>... args) {
if (!_loadedMethods.containsKey(clazz)) { if (!_loadedMethods.containsKey(clazz)) {
_loadedMethods.put(clazz, new HashMap<>()); _loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
} }
Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames =
_loadedMethods.get(clazz); _loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name)) { if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<>()); loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
} }
Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name); Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);

View File

@ -207,7 +207,7 @@ public abstract class TextualComponent implements Cloneable {
this.value = value; this.value = value;
} }
@Override public TextualComponent clone() { @Override public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue()); return new ArbitraryTextTypeComponent(getKey(), getValue());
} }

View File

@ -171,7 +171,8 @@ import java.util.Map.Entry;
} }
MainUtil.sendMessage(player, "&7 - Replacing cache"); MainUtil.sendMessage(player, "&7 - Replacing cache");
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
for (Entry<UUID, UUID> entry : uCMap.entrySet()) { for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
String name = UUIDHandler.getName(entry.getKey()); String name = UUIDHandler.getName(entry.getKey());
if (name != null) { if (name != null) {
@ -184,7 +185,8 @@ import java.util.Map.Entry;
File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) { if (file.exists()) {
try { try {
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); List<String> lines =
Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) { for (String line : lines) {
try { try {
line = line.trim(); line = line.trim();
@ -221,9 +223,9 @@ import java.util.Map.Entry;
MainUtil.sendMessage(player, "&7 - Updating plot objects"); MainUtil.sendMessage(player, "&7 - Updating plot objects");
for (Plot plot : PlotSquared.get().getPlots()) { for (Plot plot : PlotSquared.get().getPlots()) {
UUID value = uCMap.get(plot.guessOwner()); UUID value = uCMap.get(plot.owner);
if (value != null) { if (value != null) {
plot.setOwner(value); plot.owner = value;
} }
plot.getTrusted().clear(); plot.getTrusted().clear();
plot.getMembers().clear(); plot.getMembers().clear();
@ -240,13 +242,17 @@ import java.util.Map.Entry;
if (!result) { if (!result) {
MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery");
for (Plot plot : PlotSquared.get().getPlots()) { for (Plot plot : PlotSquared.get().getPlots()) {
UUID value = uCReverse.get(plot.guessOwner()); UUID value = uCReverse.get(plot.owner);
if (value != null) { if (value != null) {
plot.setOwner(value); plot.owner = value;
} }
} }
DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()), DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()),
() -> MainUtil.sendMessage(player, "&6Recovery was successful!")); new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Recovery was successful!");
}
});
return; return;
} }
} catch (Exception e) { } catch (Exception e) {
@ -270,15 +276,21 @@ import java.util.Map.Entry;
MainUtil.sendMessage(player, "&7 - Populating tables"); MainUtil.sendMessage(player, "&7 - Populating tables");
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots()); ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots());
DBFunc.createPlotsAndData(plots, DBFunc.createPlotsAndData(plots, new Runnable() {
() -> MainUtil.sendMessage(player, "&aConversion complete!")); @Override public void run() {
MainUtil.sendMessage(player, "&aConversion complete!");
}
});
}
}); });
MainUtil.sendMessage(player, "&aIt is now safe for players to join"); MainUtil.sendMessage(player, "&aIt is now safe for players to join");
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"&cConversion is still in progress, you will be notified when it is complete"); "&cConversion is still in progress, you will be notified when it is complete");
}
}); });
return true; return true;
} }

View File

@ -66,13 +66,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
String name = resultSet.getString("owner"); String name = resultSet.getString("owner");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
if (!plots.containsKey(world)) { if (!plots.containsKey(world)) {
plots.put(world, new HashMap<>()); plots.put(world, new HashMap<PlotId, Plot>());
if (merge) { if (merge) {
int plot = PlotSquared.get().worlds.getInt("worlds." + world + ".plot.size"); int plot = PlotSquared.get().worlds.getInt("worlds." + world + ".plot.size");
int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width"); int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot); plotWidth.put(world, plot);
roadWidth.put(world, path); roadWidth.put(world, path);
merges.put(world, new HashMap<>()); merges.put(world, new HashMap<PlotId, boolean[]>());
} }
} }
if (merge) { if (merge) {

View File

@ -48,7 +48,7 @@ public class LikePlotMeConverter {
private void sendMessage(String message) { private void sendMessage(String message) {
PlotSquared PlotSquared
.debug("&3PlotMe&8->&3" + PlotSquared.get().IMP.getPluginName() + "&8: &7" + message); .debug("&3PlotMe&8->&3" + PlotSquared.imp().getPluginName() + "&8: &7" + message);
} }
public String getPlotMePath() { public String getPlotMePath() {
@ -97,7 +97,7 @@ public class LikePlotMeConverter {
return; return;
} }
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
String pluginName = PlotSquared.get().IMP.getPluginName(); String pluginName = PlotSquared.imp().getPluginName();
content = content.replace("PlotMe-DefaultGenerator", pluginName); content = content.replace("PlotMe-DefaultGenerator", pluginName);
content = content.replace("PlotMe", pluginName); content = content.replace("PlotMe", pluginName);
content = content.replace("AthionPlots", pluginName); content = content.replace("AthionPlots", pluginName);
@ -220,8 +220,8 @@ public class LikePlotMeConverter {
for (String world : allWorlds) { for (String world : allWorlds) {
copyConfig(plotmeDgYml, world); copyConfig(plotmeDgYml, world);
} }
} catch (IOException e) { } catch (IOException ignored) {
e.printStackTrace(); ignored.printStackTrace();
} }
} }
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
@ -266,7 +266,8 @@ public class LikePlotMeConverter {
sendMessage("Creating plot DB"); sendMessage("Creating plot DB");
Thread.sleep(1000); Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false); final AtomicBoolean done = new AtomicBoolean(false);
DBFunc.createPlotsAndData(createdPlots, () -> { DBFunc.createPlotsAndData(createdPlots, new Runnable() {
@Override public void run() {
if (done.get()) { if (done.get()) {
done(); done();
sendMessage("&aDatabase conversion is now complete!"); sendMessage("&aDatabase conversion is now complete!");
@ -282,6 +283,7 @@ public class LikePlotMeConverter {
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true); done.set(true);
} }
}
}); });
sendMessage("Saving configuration..."); sendMessage("Saving configuration...");
try { try {
@ -289,25 +291,28 @@ public class LikePlotMeConverter {
} catch (IOException ignored) { } catch (IOException ignored) {
sendMessage(" - &cFailed to save configuration."); sendMessage(" - &cFailed to save configuration.");
} }
TaskManager.runTask(() -> { TaskManager.runTask(new Runnable() {
@Override public void run() {
try { try {
boolean mv = false; boolean mv = false;
boolean mw = false; boolean mw = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null)
.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
mv = true; mv = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null)
.getPluginManager().getPlugin("MultiWorld").isEnabled()) { && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
mw = true; mw = true;
} }
for (String worldName : worlds) { for (String worldName : worlds) {
World world = Bukkit.getWorld(getWorld(worldName)); World world = Bukkit.getWorld(getWorld(worldName));
if (world == null) { if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldName); sendMessage(
"&cInvalid world in PlotMe configuration: " + worldName);
continue; continue;
} }
String actualWorldName = world.getName(); String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); sendMessage(
"Reloading generator for world: '" + actualWorldName + "'...");
if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName() if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName()
.equals(worldName)) { .equals(worldName)) {
sendMessage( sendMessage(
@ -327,8 +332,8 @@ public class LikePlotMeConverter {
// load world with MV // load world with MV
Bukkit.getServer() Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), .dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g " + PlotSquared "mv import " + actualWorldName + " normal -g "
.get().IMP.getPluginName()); + PlotSquared.imp().getPluginName());
} else if (mw) { } else if (mw) {
// unload world with MW // unload world with MW
Bukkit.getServer() Bukkit.getServer()
@ -342,15 +347,16 @@ public class LikePlotMeConverter {
// load world with MW // load world with MW
Bukkit.getServer() Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), .dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:" + PlotSquared "mw create " + actualWorldName + " plugin:"
.get().IMP.getPluginName()); + PlotSquared.imp().getPluginName());
} else { } else {
// Load using Bukkit API // Load using Bukkit API
// - User must set generator manually // - User must set generator manually
Bukkit.getServer().unloadWorld(world, true); Bukkit.getServer().unloadWorld(world, true);
World myWorld = WorldCreator.name(actualWorldName).generator( World myWorld = WorldCreator.name(actualWorldName).generator(
new BukkitPlotGenerator( new BukkitPlotGenerator(
PlotSquared.get().IMP.getDefaultGenerator())).createWorld(); PlotSquared.get().IMP.getDefaultGenerator()))
.createWorld();
myWorld.save(); myWorld.save();
} }
} }
@ -372,6 +378,7 @@ public class LikePlotMeConverter {
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true); done.set(true);
} }
}
}); });
} catch (InterruptedException | SQLException e) { } catch (InterruptedException | SQLException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -75,7 +75,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width"); int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot); plotWidth.put(world, plot);
roadWidth.put(world, path); roadWidth.put(world, path);
merges.put(world, new HashMap<>()); merges.put(world, new HashMap<PlotId, boolean[]>());
} }
if (merge) { if (merge) {
int tx = resultSet.getInt("topX"); int tx = resultSet.getInt("topX");
@ -178,8 +178,11 @@ public class PlotMeConnector_017 extends APlotMeConnector {
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>(); HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (Plot plot : plots.values()) { for (Plot plot : plots.values()) {
HashMap<PlotId, Plot> map = HashMap<PlotId, Plot> map = processed.get(plot.getWorldName());
processed.computeIfAbsent(plot.getWorldName(), k -> new HashMap<>()); if (map == null) {
map = new HashMap<>();
processed.put(plot.getWorldName(), map);
}
map.put(plot.getId(), plot); map.put(plot.getId(), plot);
} }
return processed; return processed;

View File

@ -19,10 +19,7 @@ import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator public class BukkitPlotGenerator extends ChunkGenerator
implements GeneratorWrapper<ChunkGenerator> { implements GeneratorWrapper<ChunkGenerator> {
@ -31,6 +28,7 @@ public class BukkitPlotGenerator extends ChunkGenerator
private final IndependentPlotGenerator plotGenerator; private final IndependentPlotGenerator plotGenerator;
private final ChunkGenerator platformGenerator; private final ChunkGenerator platformGenerator;
private final boolean full; private final boolean full;
private final HashMap<ChunkLoc, byte[][]> dataMap = new HashMap<>();
private List<BlockPopulator> populators; private List<BlockPopulator> populators;
private boolean loaded = false; private boolean loaded = false;
@ -201,13 +199,11 @@ public class BukkitPlotGenerator extends ChunkGenerator
if (populators == null && platformGenerator != null) { if (populators == null && platformGenerator != null) {
populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world)); populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world));
} }
if (this.populators != null) {
for (BlockPopulator populator : this.populators) { for (BlockPopulator populator : this.populators) {
if (!existing.contains(populator)) { if (!existing.contains(populator)) {
toAdd.add(populator); toAdd.add(populator);
} }
} }
}
return toAdd; return toAdd;
} }

View File

@ -50,6 +50,7 @@ public class ChunkListener implements Listener {
} catch (Throwable ignored) { } catch (Throwable ignored) {
PlotSquared.debug(PlotSquared.get().IMP.getPluginName() PlotSquared.debug(PlotSquared.get().IMP.getPluginName()
+ "/Server not compatible for chunk processor trim/gc"); + "/Server not compatible for chunk processor trim/gc");
Settings.Chunk_Processor.AUTO_TRIM = false; Settings.Chunk_Processor.AUTO_TRIM = false;
} }
} }
@ -59,7 +60,8 @@ public class ChunkListener implements Listener {
for (World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false); world.setAutoSave(false);
} }
TaskManager.runTaskRepeat(() -> { TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
try { try {
HashSet<Chunk> toUnload = new HashSet<>(); HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
@ -68,9 +70,10 @@ public class ChunkListener implements Listener {
continue; continue;
} }
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world); Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); Object chunkMap =
Method methodIsChunkInUse = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class); Method methodIsChunkInUse = chunkMap.getClass()
.getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks(); Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) { for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse if ((boolean) methodIsChunkInUse
@ -99,6 +102,7 @@ public class ChunkListener implements Listener {
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}, 1); }, 1);
} }
@ -108,7 +112,7 @@ public class ChunkListener implements Listener {
} }
Object c = this.methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c); RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get()) { if ((Boolean) field.get() == true) {
field.set(false); field.set(false);
if (chunk.isLoaded()) { if (chunk.isLoaded()) {
ignoreUnload = true; ignoreUnload = true;
@ -222,11 +226,13 @@ public class ChunkListener implements Listener {
private void cleanChunk(final Chunk chunk) { private void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet(); TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get(); final Integer currentIndex = TaskManager.index.get();
Integer task = TaskManager.runTaskRepeat(() -> { Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex); TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true); chunk.unload(true, true);
return; return;
} }
@ -234,7 +240,8 @@ public class ChunkListener implements Listener {
if (tiles.length == 0) { if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex); TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true); chunk.unload(true, true);
return; return;
} }
@ -252,6 +259,7 @@ public class ChunkListener implements Listener {
tiles[i].getBlock().setType(Material.AIR, false); tiles[i].getBlock().setType(Material.AIR, false);
i++; i++;
} }
}
}, 5); }, 5);
TaskManager.tasks.put(currentIndex, task); TaskManager.tasks.put(currentIndex, task);
} }

View File

@ -129,7 +129,7 @@ import java.util.List;
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void vehicleMove(VehicleMoveEvent event) { public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException {
test(event.getVehicle()); test(event.getVehicle());
} }

View File

@ -602,11 +602,13 @@ public class PlayerEvents extends PlotListener implements Listener {
// Delayed // Delayed
// Async // Async
TaskManager.runTaskLaterAsync(() -> { TaskManager.runTaskLaterAsync(new Runnable() {
@Override public void run() {
if (!player.hasPlayedBefore() && player.isOnline()) { if (!player.hasPlayedBefore() && player.isOnline()) {
player.saveData(); player.saveData();
} }
EventUtil.manager.doJoinTask(pp); EventUtil.manager.doJoinTask(pp);
}
}, 20); }, 20);
} }
@ -2211,7 +2213,7 @@ public class PlayerEvents extends PlotListener implements Listener {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
event.setCancelled(true); event.setCancelled(true);
} else if (!plot.isAdded(pp.getUUID())) { } else if (!plot.isAdded(pp.getUUID())) {
if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket()))) { if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket().getId(), 0))) {
return; return;
} }
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
@ -2524,7 +2526,7 @@ public class PlayerEvents extends PlotListener implements Listener {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange; EntityDamageByEntityEvent eventChange = null;
eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
onEntityDamageByEntityEvent(eventChange); onEntityDamageByEntityEvent(eventChange);

View File

@ -37,7 +37,8 @@ public class PlotPlusListener extends PlotListener implements Listener {
private static final HashMap<UUID, Interval> healRunnable = new HashMap<>(); private static final HashMap<UUID, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) { public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override public void run() {
if (!healRunnable.isEmpty()) { if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator = for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) { healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
@ -78,6 +79,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
} }
} }
} }
}
}, 0L, 20L); }, 0L, 20L);
} }

View File

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

View File

@ -10,7 +10,7 @@ public class BukkitLazyBlock extends LazyBlock {
private StringPlotBlock pb; private StringPlotBlock pb;
public BukkitLazyBlock(Block block) { public BukkitLazyBlock(Block block) {
this.pb = PlotBlock.get(block.getType().toString()); this.pb = (StringPlotBlock) PlotBlock.get(block.getType().toString());
} }
public BukkitLazyBlock(StringPlotBlock pb) { public BukkitLazyBlock(StringPlotBlock pb) {

View File

@ -77,7 +77,7 @@ public class BukkitPlayer extends PlotPlayer {
private void callEvent(final Event event) { private void callEvent(final Event event) {
RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners(); RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (RegisteredListener listener : listeners) { for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PlotSquared.get().IMP.getPluginName())) { if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) {
continue; continue;
} }
try { try {
@ -144,7 +144,7 @@ public class BukkitPlayer extends PlotPlayer {
} }
@Override public void sendMessage(String message) { @Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (
System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) { System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message); setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis()); setMeta("lastMessageTime", System.currentTimeMillis());

View File

@ -38,7 +38,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
if (depth == 0) { if (depth == 0) {
return; return;
} }
Entity passenger = entity.getPassengers().get(0); Entity passenger = entity.getPassenger();
if (passenger != null) { if (passenger != null) {
this.base.passenger = new ReplicatingEntityWrapper(passenger, depth); this.base.passenger = new ReplicatingEntityWrapper(passenger, depth);
} }

View File

@ -101,8 +101,10 @@ public class BukkitChunkManager extends ChunkManager {
Set<ChunkLoc> chunks = super.getChunkChunks(world); Set<ChunkLoc> chunks = super.getChunkChunks(world);
for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) {
ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5);
if (!chunks.contains(loc)) {
chunks.add(loc); chunks.add(loc);
} }
}
return chunks; return chunks;
} }
@ -113,6 +115,10 @@ public class BukkitChunkManager extends ChunkManager {
final Runnable whenDone) { final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX(); final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ(); final int relZ = newPos.getZ() - pos1.getZ();
com.github.intellectualsites.plotsquared.plot.object.Location pos4 =
new com.github.intellectualsites.plotsquared.plot.object.Location(newPos.getWorld(),
newPos.getX() + relX, 256, newPos.getZ() + relZ);
final RegionWrapper region = final RegionWrapper region =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld()); final World oldWorld = Bukkit.getWorld(pos1.getWorld());

View File

@ -83,6 +83,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
// int id = item.getTypeId(); // int id = item.getTypeId();
Material id = item.getType(); Material id = item.getType();
short data = item.getDurability();
int amount = item.getAmount(); int amount = item.getAmount();
String name = null; String name = null;
String[] lore = null; String[] lore = null;

View File

@ -208,6 +208,8 @@ public class BukkitSetupUtils extends SetupUtils {
return world; return world;
} }
} }
World bw =
Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
} }
return object.world; return object.world;
} }

View File

@ -215,7 +215,7 @@ import java.util.*;
public static List<Entity> getEntities(@NonNull final String worldName) { public static List<Entity> getEntities(@NonNull final String worldName) {
World world = getWorld(worldName); World world = getWorld(worldName);
return world != null ? world.getEntities() : new ArrayList<>(); return world != null ? world.getEntities() : new ArrayList<Entity>();
} }
public static Location getLocation(@NonNull final Entity entity) { public static Location getLocation(@NonNull final Entity entity) {
@ -233,7 +233,7 @@ import java.util.*;
} }
public static BukkitLegacyMappings getBukkitLegacyMappings() { public static BukkitLegacyMappings getBukkitLegacyMappings() {
return (BukkitLegacyMappings) PlotSquared.get().IMP.getLegacyMappings(); return (BukkitLegacyMappings) PlotSquared.imp().getLegacyMappings();
} }
public static Material getMaterial(@NonNull final PlotBlock plotBlock) { public static Material getMaterial(@NonNull final PlotBlock plotBlock) {

View File

@ -117,7 +117,7 @@ public class NbtFactory {
* *
* @return The NBT list. * @return The NBT list.
*/ */
public static NbtList createList(Iterable<?> iterable) { public static NbtList createList(Iterable<? extends Object> iterable) {
NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null));
// Add the content as well // Add the content as well
@ -951,7 +951,8 @@ public class NbtFactory {
@Override public Entry<String, Object> next() { @Override public Entry<String, Object> next() {
Entry<String, Object> entry = proxy.next(); Entry<String, Object> entry = proxy.next();
return new SimpleEntry<>(entry.getKey(), wrapOutgoing(entry.getValue())); return new SimpleEntry<String, Object>(entry.getKey(),
wrapOutgoing(entry.getValue()));
} }
@Override public void remove() { @Override public void remove() {

View File

@ -65,7 +65,11 @@ public class SendChunk {
int view = Bukkit.getServer().getViewDistance(); int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) { for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName(); String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.computeIfAbsent(world, k -> new ArrayList<>()); ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
list.add(chunk); list.add(chunk);
Object c = this.methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
this.methodInitLighting.of(c).call(); this.methodInitLighting.of(c).call();
@ -114,18 +118,21 @@ public class SendChunk {
} }
} }
for (final Chunk chunk : chunks) { for (final Chunk chunk : chunks) {
TaskManager.runTask(() -> { TaskManager.runTask(new Runnable() {
@Override public void run() {
try { try {
chunk.unload(true, false); chunk.unload(true, false);
} catch (Throwable ignored) { } catch (Throwable ignored) {
String worldName = chunk.getWorld().getName(); String worldName = chunk.getWorld().getName();
PlotSquared.debug( PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk "$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";"
.getZ()); + chunk.getZ());
PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); PlotSquared
.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)"); + "/level_old.dat may be corrupt (try repairing or removing these)");
} }
}
}); });
} }
} }

View File

@ -5,10 +5,12 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
public class SetGenCB { public class SetGenCB {
@ -43,8 +45,12 @@ public class SetGenCB {
} }
} }
if (!set) { if (!set) {
world.getPopulators() Iterator<BlockPopulator> iterator = world.getPopulators().iterator();
.removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator); while (iterator.hasNext()) {
if (iterator.next() instanceof BukkitAugmentedGenerator) {
iterator.remove();
}
}
} }
PlotSquared.get() PlotSquared.get()
.loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null)); .loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null));

View File

@ -189,11 +189,11 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
for (int x = 0; x < lc.biomes.length; x++) { for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x]; String[] biomes2 = lc.biomes[x];
if (biomes2 != null) { if (biomes2 != null) {
for (String biomeStr : biomes2) { for (int y = 0; y < biomes2.length; y++) {
String biomeStr = biomes2[y];
if (biomeStr != null) { if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) { if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = Biome.valueOf(biomeStr.toUpperCase()); biome = Biome.valueOf(biomeStr.toUpperCase());
last = biomeStr;
} }
worldObj.setBiome(bx, bz, biome); worldObj.setBiome(bx, bz, biome);
} }
@ -244,8 +244,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
if (disableResult != null) { if (disableResult != null) {
try { try {
fieldNeighbors.set(disableResult[0], disableResult[1]); fieldNeighbors.set(disableResult[0], disableResult[1]);
} catch (Throwable e) { } catch (Throwable ignore) {
e.printStackTrace(); ignore.printStackTrace();
} }
} }
} }

View File

@ -47,7 +47,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} else { } else {
world = worlds.get(0).getName(); world = worlds.get(0).getName();
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world); PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) { if (uuidFile.exists()) {
@ -80,11 +81,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace(); e.printStackTrace();
} }
} }
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>()); HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) { if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS(); HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!"); PlotSquared.debug("&aFast mode UUID caching enabled!");
File playerDataFolder = new File(container, world + File.separator + "playerdata"); File playerDataFolder =
new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter()); String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty(); boolean check = all.isEmpty();
if (dat != null) { if (dat != null) {
@ -126,17 +129,18 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} }
return; return;
} else { } else {
PlotSquared.debug( PlotSquared.debug("Failed to cache: " + all.size()
"Failed to cache: " + all.size() + " uuids - slowly processing all files"); + " uuids - slowly processing all files");
} }
} }
HashSet<String> worlds1 = Sets.newHashSet(world, "world"); HashSet<String> worlds = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>(); HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>(); HashSet<String> names = new HashSet<>();
File playerDataFolder = null; File playerDataFolder = null;
for (String worldName : worlds1) { for (String worldName : worlds) {
// Getting UUIDs // Getting UUIDs
playerDataFolder = new File(container, worldName + File.separator + "playerdata"); playerDataFolder =
new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter()); String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) { if ((dat != null) && (dat.length != 0)) {
for (String current : dat) { for (String current : dat) {
@ -210,7 +214,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} }
if (getUUIDMap().isEmpty()) { if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper
.getOfflinePlayers()) {
long last = op.getLastPlayed(); long last = op.getLastPlayed();
if (last != 0) { if (last != 0) {
String name = op.getName(); String name = op.getName();
@ -229,14 +234,17 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }
}
}); });
return true; return true;
} }
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) { @Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
}
}); });
} }
} }

View File

@ -34,6 +34,7 @@ import java.util.UUID;
public class SQLUUIDHandler extends UUIDHandlerImplementation { public class SQLUUIDHandler extends UUIDHandlerImplementation {
final int MAX_REQUESTS = 500;
private final String PROFILE_URL = private final String PROFILE_URL =
"https://sessionserver.mojang.com/session/minecraft/profile/"; "https://sessionserver.mojang.com/session/minecraft/profile/";
private final int INTERVAL = 12000; private final int INTERVAL = 12000;
@ -70,14 +71,17 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) { if (!super.startCaching(whenDone)) {
return false; return false;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try { try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>()); HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
try (PreparedStatement statement = getConnection() try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); .prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) { ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) { while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username")); StringWrapper username =
new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid")); UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid); toAdd.put(new StringWrapper(username.value), uuid);
} }
@ -96,8 +100,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
return; return;
} }
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); FileUUIDHandler fileHandler =
fileHandler.startCaching(() -> { new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode // If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does // Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) { if (Settings.UUID.OFFLINE) {
@ -107,16 +113,22 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
return; return;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
while (!toFetch.isEmpty()) { while (!toFetch.isEmpty()) {
try { try {
for (int i = 0; i < Math.min(500, toFetch.size()); i++) { for (int i = 0;
i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop(); UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL( HttpURLConnection connection =
SQLUUIDHandler.this.PROFILE_URL + uuid.toString() (HttpURLConnection) new URL(
.replace("-", "")).openConnection(); SQLUUIDHandler.this.PROFILE_URL + uuid
try (InputStream con = connection.getInputStream()) { .toString().replace("-", ""))
InputStreamReader reader = new InputStreamReader(con); .openConnection();
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
JSONObject response = JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser (JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader); .parse(reader);
@ -141,11 +153,15 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }
return;
}
}); });
}
}); });
} catch (SQLException e) { } catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e); throw new SQLUUIDHandlerException("Couldn't select :s", e);
} }
}
}); });
return true; return true;
} }
@ -156,7 +172,8 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (ifFetch == null) { if (ifFetch == null) {
return; return;
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try { try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
@ -174,7 +191,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
.parse(new InputStreamReader(connection.getInputStream())); .parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0); JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id"); String id = (String) jsonProfile.get("id");
String name1 = (String) jsonProfile.get("name"); String name = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString( ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32)); + '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
@ -182,6 +199,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
}
}); });
} }
@ -197,16 +215,19 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override public boolean add(final StringWrapper name, final UUID uuid) { @Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates // Ignoring duplicates
if (super.add(name, uuid)) { if (super.add(name, uuid)) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
try (PreparedStatement statement = getConnection() @Override public void run() {
.prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setString(2, name.toString()); statement.setString(2, name.toString());
statement.execute(); statement.execute();
PlotSquared.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); PlotSquared
.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
return true; return true;
} }
@ -218,17 +239,19 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
*/ */
@Override public void rename(final UUID uuid, final StringWrapper name) { @Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name); super.rename(uuid, name);
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try (PreparedStatement statement = getConnection() try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value); statement.setString(1, name.value);
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.execute(); statement.execute();
PlotSquared PlotSquared.debug(
.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }

View File

@ -10,10 +10,7 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotMessage;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.github.intellectualsites.plotsquared.plot.util.StringComparison;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
@ -50,7 +47,7 @@ public abstract class Command {
this.perm = perm; this.perm = perm;
this.required = required; this.required = required;
this.category = cat; this.category = cat;
this.aliases = Collections.singletonList(id); this.aliases = Arrays.asList(id);
if (this.parent != null) { if (this.parent != null) {
this.parent.register(this); this.parent.register(this);
} }
@ -117,7 +114,12 @@ public abstract class Command {
public List<Command> getCommands(CommandCategory cat, PlotPlayer player) { public List<Command> getCommands(CommandCategory cat, PlotPlayer player) {
List<Command> commands = getCommands(player); List<Command> commands = getCommands(player);
if (cat != null) { if (cat != null) {
commands.removeIf(command -> command.category != cat); Iterator<Command> iterator = commands.iterator();
while (iterator.hasNext()) {
if (iterator.next().category != cat) {
iterator.remove();
}
}
} }
return commands; return commands;
} }
@ -247,7 +249,8 @@ public abstract class Command {
} }
if (page == 0 && totalPages != 0) { // Next if (page == 0 && totalPages != 0) { // Next
new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1") new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1")
.command(baseCommand + " " + 2).text(C.CLICKABLE.s()).color("$2").send(player); .command(baseCommand + " " + (0 + 2)).text(C.CLICKABLE.s()).color("$2")
.send(player);
return; return;
} }
if (page == totalPages && totalPages != 0) { // Back if (page == totalPages && totalPages != 0) { // Back
@ -273,7 +276,7 @@ public abstract class Command {
} }
return; return;
} }
if (this.allCommands.isEmpty()) { if (this.allCommands == null || this.allCommands.isEmpty()) {
player.sendMessage( player.sendMessage(
"Not Implemented: https://github.com/IntellectualSites/PlotSquared/issues/new"); "Not Implemented: https://github.com/IntellectualSites/PlotSquared/issues/new");
return; return;
@ -286,10 +289,13 @@ public abstract class Command {
} }
// Help command // Help command
try { try {
if (args.length == 0 || MathMan.isInteger(args[0])
|| CommandCategory.valueOf(args[0].toUpperCase()) != null) {
// This will default certain syntax to the help command // This will default certain syntax to the help command
// e.g. /plot, /plot 1, /plot claiming // e.g. /plot, /plot 1, /plot claiming
MainCommand.getInstance().help.execute(player, args, null, null); MainCommand.getInstance().help.execute(player, args, null, null);
return; return;
}
} catch (IllegalArgumentException ignored) { } catch (IllegalArgumentException ignored) {
} }
// Command recommendation // Command recommendation
@ -335,6 +341,7 @@ public abstract class Command {
boolean failed = args.length < reqArgs.length; boolean failed = args.length < reqArgs.length;
String[] baseSplit = getCommandString().split(" "); String[] baseSplit = getCommandString().split(" ");
String[] fullSplit = getUsage().split(" "); String[] fullSplit = getUsage().split(" ");
String base = getCommandString();
if (fullSplit.length - baseSplit.length < reqArgs.length) { if (fullSplit.length - baseSplit.length < reqArgs.length) {
String[] tmp = new String[baseSplit.length + reqArgs.length]; String[] tmp = new String[baseSplit.length + reqArgs.length];
System.arraycopy(fullSplit, 0, tmp, 0, fullSplit.length); System.arraycopy(fullSplit, 0, tmp, 0, fullSplit.length);
@ -450,6 +457,7 @@ public abstract class Command {
} }
public String getCommandString() { public String getCommandString() {
String base;
if (this.parent == null) { if (this.parent == null) {
return "/" + toString(); return "/" + toString();
} else { } else {
@ -482,7 +490,7 @@ public abstract class Command {
return null; return null;
} }
List<Command> result = new ArrayList<>(); List<Command> result = new ArrayList<>();
int index = input.length; int index = input.length - (space ? 0 : 1);
for (String arg : args) { for (String arg : args) {
arg = arg.replace(getCommandString() + " ", ""); arg = arg.replace(getCommandString() + " ", "");
String[] split = arg.split(" "); String[] split = arg.split(" ");
@ -511,7 +519,7 @@ public abstract class Command {
return null; return null;
} }
} else { } else {
Set<Command> commands = new HashSet<>(); Set<Command> commands = new HashSet<Command>();
for (Map.Entry<String, Command> entry : this.staticCommands.entrySet()) { for (Map.Entry<String, Command> entry : this.staticCommands.entrySet()) {
if (entry.getKey().startsWith(arg) && entry.getValue() if (entry.getKey().startsWith(arg) && entry.getValue()
.canExecute(player, false)) { .canExecute(player, false)) {
@ -558,7 +566,7 @@ public abstract class Command {
} }
} }
public <T> T check(T object, C message, Object... args) { public <T extends Object> T check(T object, C message, Object... args) {
if (object == null) { if (object == null) {
throw new CommandException(message, args); throw new CommandException(message, args);
} }

View File

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

View File

@ -48,7 +48,8 @@ import java.util.zip.ZipInputStream;
* An implementation of the core, with a static getter for easy access. * An implementation of the core, with a static getter for easy access.
*/ */
@SuppressWarnings({"unused", "WeakerAccess"}) public class PlotSquared { @SuppressWarnings({"unused", "WeakerAccess"}) public class PlotSquared {
private static final Set<Plot> EMPTY_SET = Collections.unmodifiableSet(Collections.emptySet()); private static final Set<Plot> EMPTY_SET =
Collections.unmodifiableSet(Collections.<Plot>emptySet());
private static PlotSquared instance; private static PlotSquared instance;
// Implementation // Implementation
public final IPlotMain IMP; public final IPlotMain IMP;
@ -215,16 +216,26 @@ import java.util.zip.ZipInputStream;
} }
// Economy // Economy
if (Settings.Enabled_Components.ECONOMY) { if (Settings.Enabled_Components.ECONOMY) {
TaskManager TaskManager.runTask(new Runnable() {
.runTask(() -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler()); @Override public void run() {
EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler();
}
});
} }
// Check for updates // Check for updates
if (Settings.Enabled_Components.UPDATER) { if (Settings.Enabled_Components.UPDATER) {
updater = new Updater(); updater = new Updater();
TaskManager.IMP.taskAsync(() -> updater.update(getPlatform(), getVersion())); TaskManager.IMP.taskAsync(new Runnable() {
TaskManager.IMP @Override public void run() {
.taskRepeatAsync(() -> updater.update(getPlatform(), getVersion()), 36000); updater.update(getPlatform(), getVersion());
}
});
TaskManager.IMP.taskRepeatAsync(new Runnable() {
@Override public void run() {
updater.update(getPlatform(), getVersion());
}
}, 36000);
} }
// World generators: // World generators:
@ -238,15 +249,15 @@ import java.util.zip.ZipInputStream;
this.IMP.setGenerator(world); this.IMP.setGenerator(world);
} }
} }
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
for (String world : section.getKeys(false)) { for (String world : section.getKeys(false)) {
if (world.equals("CheckingPlotSquaredGenerator")) { if (world.equals("CheckingPlotSquaredGenerator")) {
continue; continue;
} }
if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) {
debug( debug("&c`" + world + "` was not properly loaded - " + IMP
"&c`" + world + "` was not properly loaded - " + IMP.getPluginName() .getPluginName() + " will now try to load it properly: ");
+ " will now try to load it properly: ");
debug( debug(
"&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); "&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml");
debug( debug(
@ -254,6 +265,7 @@ import java.util.zip.ZipInputStream;
PlotSquared.this.IMP.setGenerator(world); PlotSquared.this.IMP.setGenerator(world);
} }
} }
}
}, 1); }, 1);
} }
@ -326,22 +338,26 @@ import java.util.zip.ZipInputStream;
} }
private void startUuidCatching() { private void startUuidCatching() {
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
debug("Starting UUID caching"); debug("Starting UUID caching");
UUIDHandler.startCaching(() -> { UUIDHandler.startCaching(new Runnable() {
@Override public void run() {
UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE);
foreachPlotRaw(new RunnableVal<Plot>() { foreachPlotRaw(new RunnableVal<Plot>() {
@Override public void run(Plot plot) { @Override public void run(Plot plot) {
if (plot.hasOwner() && plot.temp != -1) { if (plot.hasOwner() && plot.temp != -1) {
if (UUIDHandler.getName(plot.guessOwner()) == null) { if (UUIDHandler.getName(plot.owner) == null) {
UUIDHandler.implementation.unknown.add(plot.guessOwner()); UUIDHandler.implementation.unknown.add(plot.owner);
} }
} }
} }
}); });
startExpiryTasks(); startExpiryTasks();
startPlotMeConversion(); startPlotMeConversion();
}
}); });
}
}, 20); }, 20);
} }
@ -358,12 +374,14 @@ import java.util.zip.ZipInputStream;
private void startPlotMeConversion() { private void startPlotMeConversion() {
if (Settings.Enabled_Components.PLOTME_CONVERTER || Settings.PlotMe.CACHE_UUDS) { if (Settings.Enabled_Components.PLOTME_CONVERTER || Settings.PlotMe.CACHE_UUDS) {
TaskManager.IMP.taskAsync(() -> { TaskManager.IMP.taskAsync(new Runnable() {
@Override public void run() {
if (PlotSquared.this.IMP.initPlotMeConverter()) { if (PlotSquared.this.IMP.initPlotMeConverter()) {
PlotSquared.log("&c=== IMPORTANT ==="); PlotSquared.log("&c=== IMPORTANT ===");
PlotSquared.log( PlotSquared.log(
"&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); "&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!");
PlotSquared.log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); PlotSquared
.log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!");
PlotSquared.log( PlotSquared.log(
"&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); "&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!");
PlotSquared.log( PlotSquared.log(
@ -371,6 +389,7 @@ import java.util.zip.ZipInputStream;
+ "'settings.yml'"); + "'settings.yml'");
} }
Settings.Enabled_Components.PLOTME_CONVERTER = false; Settings.Enabled_Components.PLOTME_CONVERTER = false;
}
}); });
} }
} }
@ -495,8 +514,11 @@ import java.util.zip.ZipInputStream;
if (this.plots_tmp == null) { if (this.plots_tmp == null) {
this.plots_tmp = new HashMap<>(); this.plots_tmp = new HashMap<>();
} }
HashMap<PlotId, Plot> map = HashMap<PlotId, Plot> map = this.plots_tmp.get(area.toString());
this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>()); if (map == null) {
map = new HashMap<>();
this.plots_tmp.put(area.toString(), map);
}
for (Plot plot : area.getPlots()) { for (Plot plot : area.getPlots()) {
map.put(plot.getId(), plot); map.put(plot.getId(), plot);
} }
@ -564,7 +586,11 @@ import java.util.zip.ZipInputStream;
result.add(plot); result.add(plot);
} }
} }
overflow.sort(Comparator.comparingInt(Plot::hashCode)); Collections.sort(overflow, new Comparator<Plot>() {
@Override public int compare(Plot a, Plot b) {
return a.hashCode() - b.hashCode();
}
});
result.addAll(overflow); result.addAll(overflow);
return result; return result;
} }
@ -620,7 +646,9 @@ import java.util.zip.ZipInputStream;
} }
} }
Collections.addAll(result, overflowArray); Collections.addAll(result, overflowArray);
result.addAll(extra); for (Plot plot : extra) {
result.add(plot);
}
return result; return result;
} }
@ -699,7 +727,9 @@ import java.util.zip.ZipInputStream;
} }
} }
Collections.addAll(result, overflowArray); Collections.addAll(result, overflowArray);
result.addAll(extra); for (Plot plot : extra) {
result.add(plot);
}
return result; return result;
} }
@ -718,7 +748,12 @@ import java.util.zip.ZipInputStream;
} else { } else {
list = new ArrayList<>(input); list = new ArrayList<>(input);
} }
list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.guessOwner()))); Collections.sort(list, new Comparator<Plot>() {
@Override public int compare(Plot a, Plot b) {
return Long.compare(ExpireManager.IMP.getTimestamp(a.owner),
ExpireManager.IMP.getTimestamp(b.owner));
}
});
return list; return list;
} }
@ -744,7 +779,7 @@ import java.util.zip.ZipInputStream;
} }
} else { } else {
for (PlotArea area : plotAreaManager.getAllPlotAreas()) { for (PlotArea area : plotAreaManager.getAllPlotAreas()) {
map.put(area, new ArrayList<>(0)); map.put(area, new ArrayList<Plot>(0));
} }
Collection<Plot> lastList = null; Collection<Plot> lastList = null;
PlotArea lastWorld = null; PlotArea lastWorld = null;
@ -759,7 +794,8 @@ import java.util.zip.ZipInputStream;
} }
} }
List<PlotArea> areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); List<PlotArea> areas = Arrays.asList(plotAreaManager.getAllPlotAreas());
areas.sort((a, b) -> { Collections.sort(areas, new Comparator<PlotArea>() {
@Override public int compare(PlotArea a, PlotArea b) {
if (priorityArea != null) { if (priorityArea != null) {
if (a.equals(priorityArea)) { if (a.equals(priorityArea)) {
return -1; return -1;
@ -768,6 +804,7 @@ import java.util.zip.ZipInputStream;
} }
} }
return a.hashCode() - b.hashCode(); return a.hashCode() - b.hashCode();
}
}); });
ArrayList<Plot> toReturn = new ArrayList<>(plots.size()); ArrayList<Plot> toReturn = new ArrayList<>(plots.size());
for (PlotArea area : areas) { for (PlotArea area : areas) {
@ -846,8 +883,11 @@ import java.util.zip.ZipInputStream;
String world = entry.getKey(); String world = entry.getKey();
PlotArea area = getPlotArea(world, null); PlotArea area = getPlotArea(world, null);
if (area == null) { if (area == null) {
HashMap<PlotId, Plot> map = HashMap<PlotId, Plot> map = this.plots_tmp.get(world);
this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>()); if (map == null) {
map = new HashMap<>();
this.plots_tmp.put(world, map);
}
map.putAll(entry.getValue()); map.putAll(entry.getValue());
} else { } else {
for (Plot plot : entry.getValue().values()) { for (Plot plot : entry.getValue().values()) {
@ -1162,8 +1202,9 @@ import java.util.zip.ZipInputStream;
PlotSquared.log(C.PREFIX + "&aDetected world load for '" + world + "'"); PlotSquared.log(C.PREFIX + "&aDetected world load for '" + world + "'");
String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName()); String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName());
if (type == 2) { if (type == 2) {
Set<PlotCluster> clusters = Set<PlotCluster> clusters = this.clusters_tmp != null ?
this.clusters_tmp != null ? this.clusters_tmp.get(world) : new HashSet<>(); this.clusters_tmp.get(world) :
new HashSet<PlotCluster>();
if (clusters == null) { if (clusters == null) {
throw new IllegalArgumentException("No cluster exists for world: " + world); throw new IllegalArgumentException("No cluster exists for world: " + world);
} }
@ -1572,8 +1613,8 @@ import java.util.zip.ZipInputStream;
// Close the connection // Close the connection
DBFunc.close(); DBFunc.close();
UUIDHandler.handleShutdown(); UUIDHandler.handleShutdown();
} catch (NullPointerException e) { } catch (NullPointerException ignored) {
e.printStackTrace(); ignored.printStackTrace();
PlotSquared.log("&cCould not close database connection!"); PlotSquared.log("&cCould not close database connection!");
} }
} }
@ -1631,8 +1672,10 @@ import java.util.zip.ZipInputStream;
/** /**
* Setup the default configuration. * Setup the default configuration.
*
* @throws IOException if the config failed to save
*/ */
public void setupConfig() { public void setupConfig() throws IOException {
String lastVersionString = this.config.getString("version"); String lastVersionString = this.config.getString("version");
if (lastVersionString != null) { if (lastVersionString != null) {
String[] split = lastVersionString.split("\\."); String[] split = lastVersionString.split("\\.");
@ -1665,8 +1708,8 @@ import java.util.zip.ZipInputStream;
Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer
.toHexString(version.hash); .toHexString(version.hash);
System.out.println("Version is " + this.version); System.out.println("Version is " + this.version);
} catch (Throwable e) { } catch (Throwable ignore) {
e.printStackTrace(); ignore.printStackTrace();
} }
Settings.save(configFile); Settings.save(configFile);
config = YamlConfiguration.loadConfiguration(configFile); config = YamlConfiguration.loadConfiguration(configFile);

View File

@ -33,8 +33,8 @@ public class PlotVersion {
public static PlotVersion tryParse(String version) { public static PlotVersion tryParse(String version) {
try { try {
return new PlotVersion(version); return new PlotVersion(version);
} catch (Exception e) { } catch (Exception ignore) {
e.printStackTrace(); ignore.printStackTrace();
return new PlotVersion(0, 0, 0, 0, 0); return new PlotVersion(0, 0, 0, 0, 0);
} }
} }

View File

@ -61,8 +61,9 @@ import java.util.UUID;
checkTrue(!uuids.isEmpty(), null); checkTrue(!uuids.isEmpty(), null);
checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS); .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS);
// Success confirm.run(this, new Runnable() {
confirm.run(this, () -> { @Override // Success
public void run() {
for (UUID uuid : uuids) { for (UUID uuid : uuids) {
if (uuid != DBFunc.EVERYONE) { if (uuid != DBFunc.EVERYONE) {
if (!plot.removeTrusted(uuid)) { if (!plot.removeTrusted(uuid)) {
@ -75,6 +76,7 @@ import java.util.UUID;
EventUtil.manager.callMember(player, plot, uuid, true); EventUtil.manager.callMember(player, plot, uuid, true);
MainUtil.sendMessage(player, C.MEMBER_ADDED); MainUtil.sendMessage(player, C.MEMBER_ADDED);
} }
}
}, null); }, null);
} }
} }

View File

@ -98,13 +98,14 @@ import java.util.Set;
object.type = area.TYPE; object.type = area.TYPE;
object.min = new PlotId(1, 1); object.min = new PlotId(1, 1);
object.max = new PlotId(numX, numZ); object.max = new PlotId(numX, numZ);
object.plotManager = PlotSquared.get().IMP.getPluginName(); object.plotManager = PlotSquared.imp().getPluginName();
object.setupGenerator = PlotSquared.get().IMP.getPluginName(); object.setupGenerator = PlotSquared.imp().getPluginName();
object.step = area.getSettingNodes(); object.step = area.getSettingNodes();
final String path = final String path =
"worlds." + area.worldname + ".areas." + area.id + '-' "worlds." + area.worldname + ".areas." + area.id + '-'
+ object.min + '-' + object.max; + object.min + '-' + object.max;
Runnable run = () -> { Runnable run = new Runnable() {
@Override public void run() {
if (offsetX != 0) { if (offsetX != 0) {
PlotSquared.get().worlds PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX); .set(path + ".road.offset.x", offsetX);
@ -133,6 +134,7 @@ import java.util.Set;
"An error occurred while creating the world: " "An error occurred while creating the world: "
+ area.worldname); + area.worldname);
} }
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, CmdConfirm.addPending(player,
@ -226,7 +228,8 @@ import java.util.Set;
C.SETUP_WORLD_TAKEN.send(player, pa.worldname); C.SETUP_WORLD_TAKEN.send(player, pa.worldname);
return false; return false;
} }
Runnable run = () -> { Runnable run = new Runnable() {
@Override public void run() {
String path = "worlds." + pa.worldname; String path = "worlds." + pa.worldname;
if (!PlotSquared.get().worlds.contains(path)) { if (!PlotSquared.get().worlds.contains(path)) {
PlotSquared.get().worlds.createSection(path); PlotSquared.get().worlds.createSection(path);
@ -235,8 +238,8 @@ import java.util.Set;
PlotSquared.get().worlds.getConfigurationSection(path); PlotSquared.get().worlds.getConfigurationSection(path);
pa.saveConfiguration(section); pa.saveConfiguration(section);
pa.loadConfiguration(section); pa.loadConfiguration(section);
object.plotManager = PlotSquared.get().IMP.getPluginName(); object.plotManager = PlotSquared.imp().getPluginName();
object.setupGenerator = PlotSquared.get().IMP.getPluginName(); object.setupGenerator = PlotSquared.imp().getPluginName();
String world = SetupUtils.manager.setupWorld(object); String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) { if (WorldUtil.IMP.isWorld(world)) {
C.SETUP_FINISHED.send(player); C.SETUP_FINISHED.send(player);
@ -251,6 +254,7 @@ import java.util.Set;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, CmdConfirm.addPending(player,
@ -418,7 +422,11 @@ import java.util.Set;
@Override public void run(ChunkLoc value) { @Override public void run(ChunkLoc value) {
AugmentedUtils.generate(area.worldname, value.x, value.z, null); AugmentedUtils.generate(area.worldname, value.x, value.z, null);
} }
}, () -> player.sendMessage("Regen complete")); }, new Runnable() {
@Override public void run() {
player.sendMessage("Regen complete");
}
});
return true; return true;
} }
case "goto": case "goto":
@ -456,7 +464,7 @@ import java.util.Set;
case "remove": case "remove":
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"$1World creation settings may be stored in multiple locations:" "$1World creation settings may be stored in multiple locations:"
+ "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.get().IMP + "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.imp()
.getPluginName() + " settings.yml" .getPluginName() + " settings.yml"
+ "\n$3 - $2Multiverse worlds.yml (or any world management plugin)" + "\n$3 - $2Multiverse worlds.yml (or any world management plugin)"
+ "\n$1Stop the server and delete it from these locations."); + "\n$1Stop the server and delete it from these locations.");

View File

@ -16,6 +16,10 @@ import java.util.Set;
description = "Claim the nearest plot", aliases = "a", usage = "/plot auto [length,width]") description = "Claim the nearest plot", aliases = "a", usage = "/plot auto [length,width]")
public class Auto extends SubCommand { public class Auto extends SubCommand {
@Deprecated public static PlotId getNextPlotId(PlotId id, int step) {
return id.getNextId(step);
}
private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea,
@Nullable Integer allowed_plots, int size_x, int size_z) { @Nullable Integer allowed_plots, int size_x, int size_z) {
if (allowed_plots == null) if (allowed_plots == null)
@ -124,9 +128,12 @@ public class Auto extends SubCommand {
return; return;
} }
whenDone.value = plot; whenDone.value = plot;
plot.setOwner(player.getUUID()); plot.owner = player.getUUID();
DBFunc.createPlotSafe(plot, whenDone, DBFunc.createPlotSafe(plot, whenDone, new Runnable() {
() -> autoClaimFromDatabase(player, area, plot.getId(), whenDone)); @Override public void run() {
autoClaimFromDatabase(player, area, plot.getId(), whenDone);
}
});
} }
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override public boolean onCommand(final PlotPlayer player, String[] args) {

View File

@ -27,9 +27,11 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil;
return false; return false;
} }
plot.addRunning(); plot.addRunning();
plot.setBiome(value.toUpperCase(), () -> { plot.setBiome(value.toUpperCase(), new Runnable() {
@Override public void run() {
plot.removeRunning(); plot.removeRunning();
MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase()); MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase());
}
}); });
return true; return true;
} }

View File

@ -46,14 +46,13 @@ import java.util.Set;
final double price = flag.get(); final double price = flag.get();
checkTrue(player.getMoney() >= price, C.CANNOT_AFFORD_PLOT); checkTrue(player.getMoney() >= price, C.CANNOT_AFFORD_PLOT);
player.withdraw(price); player.withdraw(price);
// Failure confirm.run(this, new Runnable() {
// Success @Override // Success
confirm.run(this, () -> { public void run() {
C.REMOVED_BALANCE.send(player, price); C.REMOVED_BALANCE.send(player, price);
EconHandler.manager EconHandler.manager
.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.guessOwner()), .depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price);
price); PlotPlayer owner = UUIDHandler.getPlayer(plot.owner);
PlotPlayer owner = UUIDHandler.getPlayer(plot.guessOwner());
if (owner != null) { if (owner != null) {
C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price);
} }
@ -61,9 +60,13 @@ import java.util.Set;
plot.setOwner(player.getUUID()); plot.setOwner(player.getUUID());
C.CLAIMED.send(player); C.CLAIMED.send(player);
whenDone.run(Buy.this, CommandResult.SUCCESS); whenDone.run(Buy.this, CommandResult.SUCCESS);
}, () -> { }
}, new Runnable() {
@Override // Failure
public void run() {
player.deposit(price); player.deposit(price);
whenDone.run(Buy.this, CommandResult.FAILURE); whenDone.run(Buy.this, CommandResult.FAILURE);
}
}); });
} }
} }

View File

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

View File

@ -35,11 +35,14 @@ import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue
checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER); checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER);
checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions
.hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE); .hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE);
confirm.run(this, () -> { confirm.run(this, new Runnable() {
@Override public void run() {
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
boolean result = plot.clear(true, false, () -> { boolean result = plot.clear(true, false, new Runnable() {
@Override public void run() {
plot.unlink(); plot.unlink();
GlobalBlockQueue.IMP.addTask(() -> { GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override public void run() {
plot.removeRunning(); plot.removeRunning();
// If the state changes, then mark it as no longer done // If the state changes, then mark it as no longer done
if (plot.getFlag(Flags.DONE).isPresent()) { if (plot.getFlag(Flags.DONE).isPresent()) {
@ -50,13 +53,16 @@ import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue
} }
MainUtil.sendMessage(player, C.CLEARING_DONE, MainUtil.sendMessage(player, C.CLEARING_DONE,
"" + (System.currentTimeMillis() - start)); "" + (System.currentTimeMillis() - start));
}
}); });
}
}); });
if (!result) { if (!result) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
} else { } else {
plot.addRunning(); plot.addRunning();
} }
}
}, null); }, null);
} }
} }

View File

@ -148,9 +148,9 @@ import java.util.UUID;
// Add any existing plots to the current cluster // Add any existing plots to the current cluster
for (Plot plot : plots) { for (Plot plot : plots) {
if (plot.hasOwner()) { if (plot.hasOwner()) {
if (!cluster.isAdded(plot.guessOwner())) { if (!cluster.isAdded(plot.owner)) {
cluster.invited.add(plot.guessOwner()); cluster.invited.add(plot.owner);
DBFunc.setInvited(cluster, plot.guessOwner()); DBFunc.setInvited(cluster, plot.owner);
} }
} }
} }

View File

@ -97,7 +97,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
if (plot != null && !plot.hasOwner()) { if (plot != null && !plot.hasOwner()) {
free.add(plot.getId()); free.add(plot.getId());
} }
start = start.getNextId(1); start = Auto.getNextPlotId(start, 1);
} }
if (free.isEmpty() || toMove.isEmpty()) { if (free.isEmpty() || toMove.isEmpty()) {
MainUtil.sendMessage(player, "NO FREE PLOTS FOUND"); MainUtil.sendMessage(player, "NO FREE PLOTS FOUND");
@ -126,12 +126,14 @@ import java.util.concurrent.atomic.AtomicBoolean;
} }
i++; i++;
final AtomicBoolean result = new AtomicBoolean(false); final AtomicBoolean result = new AtomicBoolean(false);
result.set(origin.move(possible, () -> { result.set(origin.move(possible, new Runnable() {
@Override public void run() {
if (result.get()) { if (result.get()) {
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"Moving: " + origin + " -> " + possible); "Moving: " + origin + " -> " + possible);
TaskManager.runTaskLater(task, 1); TaskManager.runTaskLater(task, 1);
} }
}
}, false)); }, false));
if (result.get()) { if (result.get()) {
break; break;

View File

@ -40,7 +40,11 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions;
C.PLOTWORLD_INCOMPATIBLE.send(player); C.PLOTWORLD_INCOMPATIBLE.send(player);
return false; return false;
} }
if (plot1.copy(plot2, () -> MainUtil.sendMessage(player, C.COPY_SUCCESS))) { if (plot1.copy(plot2, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, C.COPY_SUCCESS);
}
})) {
return true; return true;
} else { } else {
MainUtil.sendMessage(player, C.REQUIRES_UNOWNED); MainUtil.sendMessage(player, C.REQUIRES_UNOWNED);

View File

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

View File

@ -34,6 +34,8 @@ public class DebugClaimTest extends SubCommand {
} }
PlotId min, max; PlotId min, max;
try { try {
args[1].split(";");
args[2].split(";");
min = PlotId.fromString(args[1]); min = PlotId.fromString(args[1]);
max = PlotId.fromString(args[2]); max = PlotId.fromString(args[2]);
} catch (Exception ignored) { } catch (Exception ignored) {
@ -94,8 +96,11 @@ public class DebugClaimTest extends SubCommand {
if (!plots.isEmpty()) { if (!plots.isEmpty()) {
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlotsAndData(plots, DBFunc.createPlotsAndData(plots, new Runnable() {
() -> MainUtil.sendMessage(player, "&6Database update finished!")); @Override public void run() {
MainUtil.sendMessage(player, "&6Database update finished!");
}
});
for (Plot plot : plots) { for (Plot plot : plots) {
plot.create(); plot.create();
} }

View File

@ -46,8 +46,8 @@ import java.util.*;
this.engine.eval(script, this.scope); this.engine.eval(script, this.scope);
} }
} }
} catch (IOException | ScriptException e) { } catch (IOException | ScriptException ignored) {
e.printStackTrace(); ignored.printStackTrace();
} }
} }
@ -164,8 +164,11 @@ import java.util.*;
"$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100"); "$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100");
return false; return false;
} }
PlotAnalysis.calcOptimalModifiers(() -> MainUtil PlotAnalysis.calcOptimalModifiers(new Runnable() {
.sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold); @Override public void run() {
MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry");
}
}, threshold);
return true; return true;
case "stop-expire": case "stop-expire":
if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) { if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) {
@ -401,7 +404,8 @@ import java.util.*;
try { try {
if (async) { if (async) {
final String toExec = script; final String toExec = script;
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Object result = null; Object result = null;
try { try {
@ -409,8 +413,9 @@ import java.util.*;
} catch (ScriptException e) { } catch (ScriptException e) {
e.printStackTrace(); e.printStackTrace();
} }
PlotSquared PlotSquared.log(
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result); "> " + (System.currentTimeMillis() - start) + "ms -> " + result);
}
}); });
} else { } else {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();

View File

@ -35,7 +35,7 @@ import java.util.UUID;
} }
SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea(); SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea();
PlotId id = new PlotId(0, 0); PlotId id = new PlotId(0, 0);
File container = PlotSquared.get().IMP.getWorldContainer(); File container = PlotSquared.imp().getWorldContainer();
for (File folder : container.listFiles()) { for (File folder : container.listFiles()) {
String name = folder.getName(); String name = folder.getName();
if (!WorldUtil.IMP.isWorld(name) && PlotId.fromString(name) == null) { if (!WorldUtil.IMP.isWorld(name) && PlotId.fromString(name) == null) {
@ -45,7 +45,7 @@ import java.util.UUID;
UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
} }
while (new File(container, id.toCommaSeparatedString()).exists()) { while (new File(container, id.toCommaSeparatedString()).exists()) {
id = id.getNextId(1); id = Auto.getNextPlotId(id, 1);
} }
File newDir = new File(container, id.toCommaSeparatedString()); File newDir = new File(container, id.toCommaSeparatedString());
if (folder.renameTo(newDir)) { if (folder.renameTo(newDir)) {

View File

@ -19,7 +19,8 @@ import java.io.IOException;
extends SubCommand { extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override public boolean onCommand(final PlotPlayer player, String[] args) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try { try {
String settingsYML = HastebinUtility.upload(PlotSquared.get().configFile); String settingsYML = HastebinUtility.upload(PlotSquared.get().configFile);
String worldsYML = HastebinUtility.upload(PlotSquared.get().worldsFile); String worldsYML = HastebinUtility.upload(PlotSquared.get().worldsFile);
@ -27,10 +28,11 @@ import java.io.IOException;
String latestLOG; String latestLOG;
try { try {
latestLOG = HastebinUtility.upload( latestLOG = HastebinUtility.upload(
new File(PlotSquared.get().IMP.getDirectory(), "../../logs/latest.log")); new File(PlotSquared.get().IMP.getDirectory(),
"../../logs/latest.log"));
} catch (IOException ignored) { } catch (IOException ignored) {
MainUtil MainUtil.sendMessage(player,
.sendMessage(player, "&clatest.log is too big to be pasted, will ignore"); "&clatest.log is too big to be pasted, will ignore");
latestLOG = "too big :("; latestLOG = "too big :(";
} }
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
@ -63,12 +65,14 @@ import java.io.IOException;
b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); b.append("memory.max: ").append(runtime.maxMemory()).append('\n');
b.append("java.specification.version: '") b.append("java.specification.version: '")
.append(System.getProperty("java.specification.version")).append("'\n"); .append(System.getProperty("java.specification.version")).append("'\n");
b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n"); b.append("java.vendor: '").append(System.getProperty("java.vendor"))
.append("'\n");
b.append("java.version: '").append(System.getProperty("java.version")) b.append("java.version: '").append(System.getProperty("java.version"))
.append("'\n"); .append("'\n");
b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n");
b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); b.append("os.name: '").append(System.getProperty("os.name")).append("'\n");
b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); b.append("os.version: '").append(System.getProperty("os.version"))
.append("'\n\n");
b.append("# Okay :D Great. You are now ready to create your bug report!"); b.append("# Okay :D Great. You are now ready to create your bug report!");
b.append( b.append(
"\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); "\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues");
@ -78,6 +82,7 @@ import java.io.IOException;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
return true; return true;
} }

View File

@ -16,10 +16,14 @@ import java.util.ArrayList;
public class DebugSaveTest extends SubCommand { public class DebugSaveTest extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override public boolean onCommand(final PlotPlayer player, String[] args) {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots()); ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotSquared.get().getPlots());
MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`"); MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots, DBFunc.createPlotsAndData(plots, new Runnable() {
() -> MainUtil.sendMessage(player, "&6Database sync finished!")); @Override public void run() {
MainUtil.sendMessage(player, "&6Database sync finished!");
}
});
return true; return true;
} }
} }

View File

@ -33,13 +33,15 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
final java.util.Set<Plot> plots = plot.getConnectedPlots(); final java.util.Set<Plot> plots = plot.getConnectedPlots();
final int currentPlots = final int currentPlots =
Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld());
Runnable run = () -> { Runnable run = new Runnable() {
@Override public void run() {
if (plot.getRunning() > 0) { if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
return; return;
} }
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
boolean result = plot.deletePlot(() -> { boolean result = plot.deletePlot(new Runnable() {
@Override public void run() {
plot.removeRunning(); plot.removeRunning();
if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) { if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) {
Expression<Double> valueExr = plotArea.PRICES.get("sell"); Expression<Double> valueExr = plotArea.PRICES.get("sell");
@ -49,13 +51,16 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
sendMessage(player, C.ADDED_BALANCE, String.valueOf(value)); sendMessage(player, C.ADDED_BALANCE, String.valueOf(value));
} }
} }
MainUtil.sendMessage(player, C.DELETING_DONE, System.currentTimeMillis() - start); MainUtil.sendMessage(player, C.DELETING_DONE,
System.currentTimeMillis() - start);
}
}); });
if (result) { if (result) {
plot.addRunning(); plot.addRunning();
} else { } else {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
} }
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, getCommandString() + ' ' + plot.getId(), run); CmdConfirm.addPending(player, getCommandString() + ' ' + plot.getId(), run);

View File

@ -10,6 +10,7 @@ import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.*;
import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -43,7 +44,9 @@ import java.util.UUID;
MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]);
return false; return false;
} }
for (UUID uuid : uuids) { Iterator<UUID> iter = uuids.iterator();
while (iter.hasNext()) {
UUID uuid = iter.next();
if (uuid == DBFunc.EVERYONE && !( if (uuid == DBFunc.EVERYONE && !(
Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) { .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) {

View File

@ -247,21 +247,20 @@ import java.util.*;
for (Flag<?> flag1 : Flags.getFlags()) { for (Flag<?> flag1 : Flags.getFlags()) {
String type = flag1.getClass().getSimpleName(); String type = flag1.getClass().getSimpleName();
if (!flags.containsKey(type)) { if (!flags.containsKey(type)) {
flags.put(type, new ArrayList<>()); flags.put(type, new ArrayList<String>());
} }
flags.get(type).add(flag1.getName()); flags.get(type).add(flag1.getName());
} }
StringBuilder message = new StringBuilder(); String message = "";
String prefix = ""; String prefix = "";
for (Map.Entry<String, ArrayList<String>> entry : flags.entrySet()) { for (Map.Entry<String, ArrayList<String>> entry : flags.entrySet()) {
String category = entry.getKey(); String category = entry.getKey();
List<String> flagNames = entry.getValue(); List<String> flagNames = entry.getValue();
Collections.sort(flagNames); Collections.sort(flagNames);
message.append(prefix).append("&6").append(category).append(": &7") message += prefix + "&6" + category + ": &7" + StringMan.join(flagNames, ", ");
.append(StringMan.join(flagNames, ", "));
prefix = "\n"; prefix = "\n";
} }
MainUtil.sendMessage(player, message.toString()); MainUtil.sendMessage(player, message);
return true; return true;
} }
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>"); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>");

View File

@ -209,7 +209,7 @@ public class GenerateDocs {
line = line =
line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "") line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "")
.trim(); .trim();
result.append(line).append('\n'); result.append(line + '\n');
} }
} }
return result.toString().trim(); return result.toString().trim();

View File

@ -57,7 +57,9 @@ public class Help extends Command {
public void displayHelp(PlotPlayer player, String cat, int page) { public void displayHelp(PlotPlayer player, String cat, int page) {
CommandCategory catEnum = null; CommandCategory catEnum = null;
if (cat != null) { if (cat != null) {
if (!StringMan.isEqualIgnoreCase(cat, "all")) { if (StringMan.isEqualIgnoreCase(cat, "all")) {
catEnum = null;
} else {
for (CommandCategory c : CommandCategory.values()) { for (CommandCategory c : CommandCategory.values()) {
if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) {
catEnum = c; catEnum = c;
@ -74,13 +76,13 @@ public class Help extends Command {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(C.HELP_HEADER.s()); builder.append(C.HELP_HEADER.s());
for (CommandCategory c : CommandCategory.values()) { for (CommandCategory c : CommandCategory.values()) {
builder.append("\n").append(StringMan builder.append("\n" + StringMan
.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), .replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(),
"%category_desc%", c.toString())); "%category_desc%", c.toString()));
} }
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all") builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all")
.replaceAll("%category_desc%", "Display all commands")); .replaceAll("%category_desc%", "Display all commands"));
builder.append("\n").append(C.HELP_FOOTER.s()); builder.append("\n" + C.HELP_FOOTER.s());
MainUtil.sendMessage(player, builder.toString(), false); MainUtil.sendMessage(player, builder.toString(), false);
return; return;
} }

View File

@ -43,7 +43,7 @@ import java.util.List;
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();
string.append(StringMan string.append(StringMan
.replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur",
page + 1, "%max", totalPages + 1, "%word", "all")).append('\n'); page + 1, "%max", totalPages + 1, "%word", "all") + '\n');
// This might work xD // This might work xD
for (int x = page * 12; x < max; x++) { for (int x = page * 12; x < max; x++) {

View File

@ -69,24 +69,24 @@ import java.util.UUID;
} }
}; };
UUID uuid = player.getUUID(); UUID uuid = player.getUUID();
String name = MainUtil.getName(plot.guessOwner()); String name = MainUtil.getName(plot.owner);
inv.setItem(1, inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info",
new PlotItemStack("emerald", 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(), "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name,
"&cOwner: &6" + name, "&cAlias: &6" + plot.getAlias(), "&cAlias: &6" + plot.getAlias(),
"&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(),
"&cCan Build: &6" + plot.isAdded(uuid), "&cSeen: &6" + MainUtil "&cCan Build: &6" + plot.isAdded(uuid),
.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)),
"&cIs Denied: &6" + plot.isDenied(uuid))); "&cIs Denied: &6" + plot.isDenied(uuid)));
inv.setItem(1, new PlotItemStack("emerald", 1, "&cTrusted", inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted",
"&cAmount: &6" + plot.getTrusted().size(), "&cAmount: &6" + plot.getTrusted().size(),
"&8Click to view a list of the trusted users")); "&8Click to view a list of the trusted users"));
inv.setItem(1, new PlotItemStack("emerald", 1, "&cMembers", inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers",
"&cAmount: &6" + plot.getMembers().size(), "&cAmount: &6" + plot.getMembers().size(),
"&8Click to view a list of plot members")); "&8Click to view a list of plot members"));
inv.setItem(1, new PlotItemStack("emerald", 1, "&cDenied", "&cDenied", inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied",
"&cAmount: &6" + plot.getDenied().size(), "&cAmount: &6" + plot.getDenied().size(),
"&8Click to view a list of denied players")); "&8Click to view a list of denied players"));
inv.setItem(1, new PlotItemStack("emerald", 1, "&cFlags", "&cFlags", inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags",
"&cAmount: &6" + plot.getFlags().size(), "&8Click to view a list of plot flags")); "&cAmount: &6" + plot.getFlags().size(), "&8Click to view a list of plot flags"));
inv.openInventory(); inv.openInventory();
return true; return true;

View File

@ -10,11 +10,8 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager;
import com.google.common.base.Optional; import com.google.common.base.Optional;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(command = "list", aliases = {"l", "find", "search"}, description = "List plots", @CommandDeclaration(command = "list", aliases = {"l", "find", "search"}, description = "List plots",
permission = "plots.list", category = CommandCategory.INFO, permission = "plots.list", category = CommandCategory.INFO,
@ -135,7 +132,7 @@ public class ListCmd extends SubCommand {
return false; return false;
} }
plots = ExpireManager.IMP == null ? plots = ExpireManager.IMP == null ?
new ArrayList<>() : new ArrayList<Plot>() :
new ArrayList<>(ExpireManager.IMP.getPendingExpired()); new ArrayList<>(ExpireManager.IMP.getPendingExpired());
break; break;
case "area": case "area":
@ -148,7 +145,7 @@ public class ListCmd extends SubCommand {
C.PERMISSION_LIST_WORLD_NAME.f(world)); C.PERMISSION_LIST_WORLD_NAME.f(world));
return false; return false;
} }
plots = area == null ? new ArrayList<>() : new ArrayList<>(area.getPlots()); plots = area == null ? new ArrayList<Plot>() : new ArrayList<>(area.getPlots());
break; break;
case "all": case "all":
if (!Permissions.hasPermission(player, C.PERMISSION_LIST_ALL)) { if (!Permissions.hasPermission(player, C.PERMISSION_LIST_ALL)) {
@ -170,7 +167,8 @@ public class ListCmd extends SubCommand {
} }
plots.add(plot); plots.add(plot);
} }
plots.sort((a, b) -> { Collections.sort(plots, new Comparator<Plot>() {
@Override public int compare(Plot a, Plot b) {
String va = "" + a.getFlags().get(Flags.DONE); String va = "" + a.getFlags().get(Flags.DONE);
String vb = "" + b.getFlags().get(Flags.DONE); String vb = "" + b.getFlags().get(Flags.DONE);
if (MathMan.isInteger(va)) { if (MathMan.isInteger(va)) {
@ -180,6 +178,7 @@ public class ListCmd extends SubCommand {
return -1; return -1;
} }
return 1; return 1;
}
}); });
sort = false; sort = false;
break; break;
@ -189,7 +188,8 @@ public class ListCmd extends SubCommand {
return false; return false;
} }
plots = new ArrayList<>(PlotSquared.get().getPlots()); plots = new ArrayList<>(PlotSquared.get().getPlots());
plots.sort((p1, p2) -> { Collections.sort(plots, new Comparator<Plot>() {
@Override public int compare(Plot p1, Plot p2) {
double v1 = 0; double v1 = 0;
int p1s = p1.getSettings().getRatings().size(); int p1s = p1.getSettings().getRatings().size();
int p2s = p2.getRatings().size(); int p2s = p2.getRatings().size();
@ -214,6 +214,7 @@ public class ListCmd extends SubCommand {
return p2s - p1s; return p2s - p1s;
} }
return (int) Math.signum(v2 - v1); return (int) Math.signum(v2 - v1);
}
}); });
sort = false; sort = false;
break; break;
@ -240,7 +241,7 @@ public class ListCmd extends SubCommand {
} }
plots = new ArrayList<>(); plots = new ArrayList<>();
for (Plot plot : PlotSquared.get().getPlots()) { for (Plot plot : PlotSquared.get().getPlots()) {
if (plot.guessOwner() == null) { if (plot.owner == null) {
plots.add(plot); plots.add(plot);
} }
} }
@ -252,10 +253,10 @@ public class ListCmd extends SubCommand {
} }
plots = new ArrayList<>(); plots = new ArrayList<>();
for (Plot plot : PlotSquared.get().getPlots()) { for (Plot plot : PlotSquared.get().getPlots()) {
if (plot.guessOwner() == null) { if (plot.owner == null) {
continue; continue;
} }
if (UUIDHandler.getName(plot.guessOwner()) == null) { if (UUIDHandler.getName(plot.owner) == null) {
plots.add(plot); plots.add(plot);
} }
} }
@ -329,7 +330,12 @@ public class ListCmd extends SubCommand {
public void displayPlots(final PlotPlayer player, List<Plot> plots, int pageSize, int page, public void displayPlots(final PlotPlayer player, List<Plot> plots, int pageSize, int page,
PlotArea area, String[] args, boolean sort) { PlotArea area, String[] args, boolean sort) {
// Header // Header
plots.removeIf(plot -> !plot.isBasePlot()); Iterator<Plot> iterator = plots.iterator();
while (iterator.hasNext()) {
if (!iterator.next().isBasePlot()) {
iterator.remove();
}
}
if (sort) { if (sort) {
plots = PlotSquared.get().sortPlots(plots, SortType.CREATION_DATE, area); plots = PlotSquared.get().sortPlots(plots, SortType.CREATION_DATE, area);
} }
@ -337,7 +343,7 @@ public class ListCmd extends SubCommand {
new RunnableVal3<Integer, Plot, PlotMessage>() { new RunnableVal3<Integer, Plot, PlotMessage>() {
@Override public void run(Integer i, Plot plot, PlotMessage message) { @Override public void run(Integer i, Plot plot, PlotMessage message) {
String color; String color;
if (plot.guessOwner() == null) { if (plot.owner == null) {
color = "$3"; color = "$3";
} else if (plot.isOwner(player.getUUID())) { } else if (plot.isOwner(player.getUUID())) {
color = "$1"; color = "$1";

View File

@ -103,15 +103,17 @@ import java.util.List;
List<String> schematics = player.getMeta("plot_schematics"); List<String> schematics = player.getMeta("plot_schematics");
if (schematics == null) { if (schematics == null) {
plot.addRunning(); plot.addRunning();
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
List<String> schematics1 = SchematicHandler.manager.getSaves(player.getUUID()); @Override public void run() {
List<String> schematics = SchematicHandler.manager.getSaves(player.getUUID());
plot.removeRunning(); plot.removeRunning();
if ((schematics1 == null) || schematics1.isEmpty()) { if ((schematics == null) || schematics.isEmpty()) {
MainUtil.sendMessage(player, C.LOAD_FAILED); MainUtil.sendMessage(player, C.LOAD_FAILED);
return; return;
} }
player.setMeta("plot_schematics", schematics1); player.setMeta("plot_schematics", schematics);
displaySaves(player); displaySaves(player);
}
}); });
} else { } else {
displaySaves(player); displaySaves(player);
@ -149,30 +151,30 @@ import java.util.List;
if (time >= 33868800) { if (time >= 33868800) {
int years = (int) (time / 33868800); int years = (int) (time / 33868800);
time -= years * 33868800; time -= years * 33868800;
toreturn.append(years).append("y "); toreturn.append(years + "y ");
} }
if (time >= 604800) { if (time >= 604800) {
int weeks = (int) (time / 604800); int weeks = (int) (time / 604800);
time -= weeks * 604800; time -= weeks * 604800;
toreturn.append(weeks).append("w "); toreturn.append(weeks + "w ");
} }
if (time >= 86400) { if (time >= 86400) {
int days = (int) (time / 86400); int days = (int) (time / 86400);
time -= days * 86400; time -= days * 86400;
toreturn.append(days).append("d "); toreturn.append(days + "d ");
} }
if (time >= 3600) { if (time >= 3600) {
int hours = (int) (time / 3600); int hours = (int) (time / 3600);
time -= hours * 3600; time -= hours * 3600;
toreturn.append(hours).append("h "); toreturn.append(hours + "h ");
} }
if (time >= 60) { if (time >= 60) {
int minutes = (int) (time / 60); int minutes = (int) (time / 60);
time -= minutes * 60; time -= minutes * 60;
toreturn.append(minutes).append("m "); toreturn.append(minutes + "m ");
} }
if (toreturn.length() == 0 || (time > 0)) { if (toreturn.length() == 0 || (time > 0)) {
toreturn.append(time).append("s "); toreturn.append(time + "s ");
} }
return toreturn.toString().trim(); return toreturn.toString().trim();
} }

View File

@ -127,12 +127,15 @@ public class MainCommand extends Command {
@Override @Override
public void run(final Command cmd, final Runnable success, final Runnable failure) { public void run(final Command cmd, final Runnable success, final Runnable failure) {
if (cmd.hasConfirmation(player)) { if (cmd.hasConfirmation(player)) {
CmdConfirm.addPending(player, cmd.getUsage(), () -> { CmdConfirm.addPending(player, cmd.getUsage(), new Runnable() {
@Override public void run() {
if (EconHandler.manager != null) { if (EconHandler.manager != null) {
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
if (area != null) { if (area != null) {
Expression<Double> priceEval = area.PRICES.get(cmd.getFullId()); Expression<Double> priceEval =
Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; area.PRICES.get(cmd.getFullId());
Double price =
priceEval != null ? priceEval.evaluate(0d) : 0d;
if (price != null if (price != null
&& EconHandler.manager.getMoney(player) < price) { && EconHandler.manager.getMoney(player) < price) {
if (failure != null) { if (failure != null) {
@ -145,6 +148,7 @@ public class MainCommand extends Command {
if (success != null) { if (success != null) {
success.run(); success.run();
} }
}
}); });
return; return;
} }

View File

@ -55,11 +55,12 @@ public class Merge extends SubCommand {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS); MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
return false; return false;
} else { } else {
uuid = plot.guessOwner(); uuid = plot.owner;
} }
} }
final PlotArea plotArea = plot.getArea(); final PlotArea plotArea = plot.getArea();
Expression<Double> priceExr = plotArea.PRICES.getOrDefault("merge", null); Expression<Double> priceExr =
plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null;
final int size = plot.getConnectedPlots().size(); final int size = plot.getConnectedPlots().size();
final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); final double price = priceExr == null ? 0d : priceExr.evaluate((double) size);
if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d
@ -154,7 +155,8 @@ public class Merge extends SubCommand {
} }
isOnline = true; isOnline = true;
final int dir = direction; final int dir = direction;
Runnable run = () -> { Runnable run = new Runnable() {
@Override public void run() {
MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED);
plot.autoMerge(dir, maxSize - size, owner, terrain); plot.autoMerge(dir, maxSize - size, owner, terrain);
PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID()); PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID());
@ -171,6 +173,7 @@ public class Merge extends SubCommand {
sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price)); sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price));
} }
MainUtil.sendMessage(player, C.SUCCESS_MERGE); MainUtil.sendMessage(player, C.SUCCESS_MERGE);
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(accepter, CmdConfirm.addPending(accepter,

View File

@ -54,7 +54,11 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions;
C.PLOTWORLD_INCOMPATIBLE.send(player); C.PLOTWORLD_INCOMPATIBLE.send(player);
return false; return false;
} }
if (plot1.move(plot2, () -> MainUtil.sendMessage(player, C.MOVE_SUCCESS), false)) { if (plot1.move(plot2, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, C.MOVE_SUCCESS);
}
}, false)) {
return true; return true;
} else { } else {
MainUtil.sendMessage(player, C.REQUIRES_UNOWNED); MainUtil.sendMessage(player, C.REQUIRES_UNOWNED);

View File

@ -71,17 +71,20 @@ import java.util.UUID;
final String finalName = name; final String finalName = name;
final UUID finalUUID = uuid; final UUID finalUUID = uuid;
final boolean removeDenied = plot.isDenied(finalUUID); final boolean removeDenied = plot.isDenied(finalUUID);
Runnable run = () -> { Runnable run = new Runnable() {
@Override public void run() {
if (plot.setOwner(finalUUID, player)) { if (plot.setOwner(finalUUID, player)) {
if (removeDenied) if (removeDenied)
plot.removeDenied(finalUUID); plot.removeDenied(finalUUID);
plot.setSign(finalName); plot.setSign(finalName);
MainUtil.sendMessage(player, C.SET_OWNER); MainUtil.sendMessage(player, C.SET_OWNER);
if (other != null) { if (other != null) {
MainUtil.sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId()); MainUtil
.sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId());
} }
} else } else
MainUtil.sendMessage(player, C.SET_OWNER_CANCELLED); MainUtil.sendMessage(player, C.SET_OWNER_CANCELLED);
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, "/plot set owner " + value, run); CmdConfirm.addPending(player, "/plot set owner " + value, run);

View File

@ -13,16 +13,18 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
category = CommandCategory.INFO) public class PluginCmd extends SubCommand { category = CommandCategory.INFO) public class PluginCmd extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override public boolean onCommand(final PlotPlayer player, String[] args) {
TaskManager.IMP.taskAsync(() -> { TaskManager.IMP.taskAsync(new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, String.format( MainUtil.sendMessage(player, String.format(
"$2>> $1&l" + PlotSquared.get().IMP.getPluginName() + " $2($1Version$2: $1%s$2)", "$2>> $1&l" + PlotSquared.imp().getPluginName() + " $2($1Version$2: $1%s$2)",
PlotSquared.get().getVersion())); PlotSquared.get().getVersion()));
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev $2& $1dordsor21"); "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev $2& $1dordsor21");
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki");
MainUtil MainUtil.sendMessage(player,
.sendMessage(player, "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); "$2>> $1&lNewest Version$2: $1" + getNewestVersionString());
}
}); });
return true; return true;
} }

View File

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

View File

@ -10,11 +10,8 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.*;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot", @CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot",
usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO, usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO,
@ -25,7 +22,8 @@ import java.util.UUID;
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "next": { case "next": {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getBasePlots()); ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getBasePlots());
Collections.sort(plots, (p1, p2) -> { Collections.sort(plots, new Comparator<Plot>() {
@Override public int compare(Plot p1, Plot p2) {
double v1 = 0; double v1 = 0;
if (!p1.getRatings().isEmpty()) { if (!p1.getRatings().isEmpty()) {
for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) { for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
@ -42,6 +40,7 @@ import java.util.UUID;
return -0; return -0;
} }
return v2 > v1 ? 1 : -1; return v2 > v1 ? 1 : -1;
}
}); });
UUID uuid = player.getUUID(); UUID uuid = player.getUUID();
for (Plot p : plots) { for (Plot p : plots) {
@ -124,23 +123,25 @@ import java.util.UUID;
return true; return true;
} }
}; };
inventory.setItem(0, new PlotItemStack("brown_wool", 0, "0/8")); inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8"));
inventory.setItem(1, new PlotItemStack("red_wool", 1, "1/8")); inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8"));
inventory.setItem(2, new PlotItemStack("orange_wool", 2, "2/8")); inventory.setItem(2, new PlotItemStack(35, (short) 1, 2, "2/8"));
inventory.setItem(3, new PlotItemStack("yellow_wool", 3, "3/8")); inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8"));
inventory.setItem(4, new PlotItemStack("lime_wool", 4, "4/8")); inventory.setItem(4, new PlotItemStack(35, (short) 5, 4, "4/8"));
inventory.setItem(5, new PlotItemStack("cyan_wool", 5, "5/8")); inventory.setItem(5, new PlotItemStack(35, (short) 9, 5, "5/8"));
inventory.setItem(6, new PlotItemStack("blue_wool", 6, "6/8")); inventory.setItem(6, new PlotItemStack(35, (short) 11, 6, "6/8"));
inventory.setItem(7, new PlotItemStack("purple_wool", 7, "7/8")); inventory.setItem(7, new PlotItemStack(35, (short) 10, 7, "7/8"));
inventory.setItem(8, new PlotItemStack("magenta_wool", 8, "8/8")); inventory.setItem(8, new PlotItemStack(35, (short) 2, 8, "8/8"));
inventory.openInventory(); inventory.openInventory();
} }
}; };
if (plot.getSettings().ratings == null) { if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) { if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot); plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run(); run.run();
}
}); });
return true; return true;
} }
@ -166,7 +167,8 @@ import java.util.UUID;
return false; return false;
} }
final UUID uuid = player.getUUID(); final UUID uuid = player.getUUID();
final Runnable run = () -> { final Runnable run = new Runnable() {
@Override public void run() {
if (plot.getRatings().containsKey(uuid)) { if (plot.getRatings().containsKey(uuid)) {
sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
return; return;
@ -176,12 +178,15 @@ import java.util.UUID;
plot.addRating(uuid, result); plot.addRating(uuid, result);
sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
} }
}
}; };
if (plot.getSettings().ratings == null) { if (plot.getSettings().ratings == null) {
if (!Settings.Enabled_Components.RATING_CACHE) { if (!Settings.Enabled_Components.RATING_CACHE) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
plot.getSettings().ratings = DBFunc.getRatings(plot); plot.getSettings().ratings = DBFunc.getRatings(plot);
run.run(); run.run();
}
}); });
return true; return true;
} }

View File

@ -7,6 +7,8 @@ import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
import java.util.HashSet;
@CommandDeclaration(command = "relight", description = "Relight your plot", usage = "/plot relight", @CommandDeclaration(command = "relight", description = "Relight your plot", usage = "/plot relight",
category = CommandCategory.DEBUG) public class Relight extends Command { category = CommandCategory.DEBUG) public class Relight extends Command {
public Relight() { public Relight() {
@ -21,14 +23,17 @@ import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
C.NOT_IN_PLOT.send(player); C.NOT_IN_PLOT.send(player);
return; return;
} }
HashSet<RegionWrapper> regions = plot.getRegions();
final LocalBlockQueue queue = plot.getArea().getQueue(false); final LocalBlockQueue queue = plot.getArea().getQueue(false);
ChunkManager.chunkTask(plot, new RunnableVal<int[]>() { ChunkManager.chunkTask(plot, new RunnableVal<int[]>() {
@Override public void run(int[] value) { @Override public void run(int[] value) {
queue.fixChunkLighting(value[0], value[1]); queue.fixChunkLighting(value[0], value[1]);
} }
}, () -> { }, new Runnable() {
@Override public void run() {
plot.refreshChunks(); plot.refreshChunks();
C.SET_BLOCK_ACTION_FINISHED.send(player); C.SET_BLOCK_ACTION_FINISHED.send(player);
}
}, 5); }, 5);
} }
} }

View File

@ -189,6 +189,7 @@ public class SchematicCmd extends SubCommand {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS); MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
return false; return false;
} }
location.getWorld();
Collection<Plot> plots = new ArrayList<>(); Collection<Plot> plots = new ArrayList<>();
plots.add(plot); plots.add(plot);
boolean result = SchematicHandler.manager.exportAll(plots, null, null, () -> { boolean result = SchematicHandler.manager.exportAll(plots, null, null, () -> {

View File

@ -58,6 +58,8 @@ import java.util.HashSet;
MainUtil.sendMessage(player, C.NEED_BLOCK); MainUtil.sendMessage(player, C.NEED_BLOCK);
return true; return true;
} }
String[] split = material.split(",");
// blocks = Configuration.BLOCKLIST.parseString(material);
try { try {
bucket = Configuration.BLOCK_BUCKET.parseString(material); bucket = Configuration.BLOCK_BUCKET.parseString(material);
@ -98,7 +100,11 @@ import java.util.HashSet;
current.setComponent(component, bucket); current.setComponent(component, bucket);
} }
MainUtil.sendMessage(player, C.GENERATING_COMPONENT); MainUtil.sendMessage(player, C.GENERATING_COMPONENT);
GlobalBlockQueue.IMP.addTask(() -> plot.removeRunning()); GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override public void run() {
plot.removeRunning();
}
});
return true; return true;
} }
} }
@ -108,8 +114,8 @@ import java.util.HashSet;
} }
public boolean noArgs(PlotPlayer player) { public boolean noArgs(PlotPlayer player) {
ArrayList<String> newValues = ArrayList<String> newValues = new ArrayList<>();
new ArrayList<>(Arrays.asList("biome", "alias", "home", "flag")); newValues.addAll(Arrays.asList("biome", "alias", "home", "flag"));
Plot plot = player.getCurrentPlot(); Plot plot = player.getCurrentPlot();
if (plot != null) { if (plot != null) {
newValues.addAll( newValues.addAll(

View File

@ -25,7 +25,7 @@ import java.util.Map.Entry;
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.append("&6What generator do you want?"); message.append("&6What generator do you want?");
for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) { for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) {
if (entry.getKey().equals(PlotSquared.get().IMP.getPluginName())) { if (entry.getKey().equals(PlotSquared.imp().getPluginName())) {
message.append("\n&8 - &2").append(entry.getKey()).append(" (Default Generator)"); message.append("\n&8 - &2").append(entry.getKey()).append(" (Default Generator)");
} else if (entry.getValue().isFull()) { } else if (entry.getValue().isFull()) {
message.append("\n&8 - &7").append(entry.getKey()).append(" (Plot Generator)"); message.append("\n&8 - &7").append(entry.getKey()).append(" (Plot Generator)");
@ -73,8 +73,8 @@ import java.util.Map.Entry;
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"&cYou must choose a generator!" + prefix + StringMan "&cYou must choose a generator!" + prefix + StringMan
.join(SetupUtils.generators.keySet(), prefix) .join(SetupUtils.generators.keySet(), prefix)
.replaceAll(PlotSquared.get().IMP.getPluginName(), .replaceAll(PlotSquared.imp().getPluginName(),
"&2" + PlotSquared.get().IMP.getPluginName())); "&2" + PlotSquared.imp().getPluginName()));
sendMessage(player, C.SETUP_INIT); sendMessage(player, C.SETUP_INIT);
return false; return false;
} }
@ -142,7 +142,7 @@ import java.util.Map.Entry;
SetupUtils.generators.get(object.plotManager).getPlotGenerator() SetupUtils.generators.get(object.plotManager).getPlotGenerator()
.processSetup(object); .processSetup(object);
} else { } else {
object.plotManager = PlotSquared.get().IMP.getPluginName(); object.plotManager = PlotSquared.imp().getPluginName();
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator");
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
@ -282,7 +282,7 @@ import java.util.Map.Entry;
} }
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
"&cThe world you specified already exists. After restarting, new terrain will use " "&cThe world you specified already exists. After restarting, new terrain will use "
+ PlotSquared.get().IMP.getPluginName() + ", however you may need to " + PlotSquared.imp().getPluginName() + ", however you may need to "
+ "reset the world for it to generate correctly!"); + "reset the world for it to generate correctly!");
} }
object.world = args[0]; object.world = args[0];
@ -318,7 +318,7 @@ import java.util.Map.Entry;
messages.add(new PlotMessage("What generator do you want?").color("$6")); messages.add(new PlotMessage("What generator do you want?").color("$6"));
for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) { for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) {
final PlotMessage plotMessage = new PlotMessage(" - ").color("$8"); final PlotMessage plotMessage = new PlotMessage(" - ").color("$8");
if (entry.getKey().equals(PlotSquared.get().IMP.getPluginName())) { if (entry.getKey().equals(PlotSquared.imp().getPluginName())) {
plotMessage.text(entry.getKey()).color("$8").tooltip("Select this generator") plotMessage.text(entry.getKey()).color("$8").tooltip("Select this generator")
.color("$2").command("/plot setup generator " + entry.getKey()) .color("$2").command("/plot setup generator " + entry.getKey())
.text(" (Default Generator)").color("$7"); .text(" (Default Generator)").color("$7");

View File

@ -40,7 +40,11 @@ public class Swap extends SubCommand {
C.PLOTWORLD_INCOMPATIBLE.send(player); C.PLOTWORLD_INCOMPATIBLE.send(player);
return false; return false;
} }
if (plot1.move(plot2, () -> MainUtil.sendMessage(player, C.SWAP_SUCCESS), true)) { if (plot1.move(plot2, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, C.SWAP_SUCCESS);
}
}, true)) {
return true; return true;
} else { } else {
MainUtil.sendMessage(player, C.SWAP_OVERLAP); MainUtil.sendMessage(player, C.SWAP_OVERLAP);

View File

@ -15,10 +15,7 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil;
import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue;
import java.io.File; import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
@ -66,6 +63,9 @@ import java.util.zip.ZipOutputStream;
zis.closeEntry(); zis.closeEntry();
} }
return true; return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
@ -147,8 +147,8 @@ import java.util.zip.ZipOutputStream;
} catch (InvalidConfigurationException | IOException e) { } catch (InvalidConfigurationException | IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
String manager = worldConfig String manager =
.getString("generator.plugin", PlotSquared.get().IMP.getPluginName()); worldConfig.getString("generator.plugin", PlotSquared.imp().getPluginName());
String generator = worldConfig.getString("generator.init", manager); String generator = worldConfig.getString("generator.init", manager);
int type = worldConfig.getInt("generator.type"); int type = worldConfig.getInt("generator.type");
int terrain = worldConfig.getInt("generator.terrain"); int terrain = worldConfig.getInt("generator.terrain");
@ -161,9 +161,11 @@ import java.util.zip.ZipOutputStream;
setup.step = new ConfigurationNode[0]; setup.step = new ConfigurationNode[0];
setup.world = world; setup.world = world;
SetupUtils.manager.setupWorld(setup); SetupUtils.manager.setupWorld(setup);
GlobalBlockQueue.IMP.addTask(() -> { GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "Done!"); MainUtil.sendMessage(player, "Done!");
player.teleport(WorldUtil.IMP.getSpawn(world)); player.teleport(WorldUtil.IMP.getSpawn(world));
}
}); });
return true; return true;
} }
@ -178,7 +180,8 @@ import java.util.zip.ZipOutputStream;
return false; return false;
} }
final PlotManager manager = area.getPlotManager(); final PlotManager manager = area.getPlotManager();
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try { try {
manager.exportTemplate(area); manager.exportTemplate(area);
} catch (Exception e) { // Must recover from any exception thrown a third party template manager } catch (Exception e) { // Must recover from any exception thrown a third party template manager
@ -187,6 +190,7 @@ import java.util.zip.ZipOutputStream;
return; return;
} }
MainUtil.sendMessage(player, "Done!"); MainUtil.sendMessage(player, "Done!");
}
}); });
return true; return true;
default: default:

View File

@ -70,7 +70,7 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
RunnableVal3<Command, Runnable, Runnable> confirm, RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone) { RunnableVal2<Command, CommandResult> whenDone) {
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
boolean chat = area != null && area.PLOT_CHAT; boolean chat = area == null ? false : area.PLOT_CHAT;
if (toggle(player, "disabletitles") != chat) { if (toggle(player, "disabletitles") != chat) {
MainUtil.sendMessage(player, C.TOGGLE_ENABLED, command.toString()); MainUtil.sendMessage(player, C.TOGGLE_ENABLED, command.toString());
} else { } else {

View File

@ -95,7 +95,8 @@ import java.util.Set;
return false; return false;
} }
MainUtil.sendMessage(null, "Collecting region data..."); MainUtil.sendMessage(null, "Collecting region data...");
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots(world)); ArrayList<Plot> plots = new ArrayList<>();
plots.addAll(PlotSquared.get().getPlots(world));
if (ExpireManager.IMP != null) { if (ExpireManager.IMP != null) {
plots.removeAll(ExpireManager.IMP.getPendingExpired()); plots.removeAll(ExpireManager.IMP.getPendingExpired());
} }
@ -197,9 +198,11 @@ import java.util.Set;
} }
}; };
} else { } else {
regenTask = () -> { regenTask = new Runnable() {
@Override public void run() {
Trim.TASK = false; Trim.TASK = false;
player.sendMessage("Trim done!"); player.sendMessage("Trim done!");
}
}; };
} }
ChunkManager.manager.deleteRegionFiles(world, viable, regenTask); ChunkManager.manager.deleteRegionFiles(world, viable, regenTask);

View File

@ -39,12 +39,14 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
} else { } else {
createRoad = true; createRoad = true;
} }
Runnable runnable = () -> { Runnable runnable = new Runnable() {
@Override public void run() {
if (!plot.unlinkPlot(createRoad, createRoad)) { if (!plot.unlinkPlot(createRoad, createRoad)) {
MainUtil.sendMessage(player, "&cUnlink has been cancelled"); MainUtil.sendMessage(player, "&cUnlink has been cancelled");
return; return;
} }
MainUtil.sendMessage(player, C.UNLINK_SUCCESS); MainUtil.sendMessage(player, C.UNLINK_SUCCESS);
}
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, "/plot unlink " + plot.getId(), runnable); CmdConfirm.addPending(player, "/plot unlink " + plot.getId(), runnable);

View File

@ -915,9 +915,10 @@ public enum C {
return m; return m;
} }
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
if (args.length > 0) {
for (int i = args.length - 1; i >= 0; i--) { for (int i = args.length - 1; i >= 0; i--) {
String arg = "" + args[i]; String arg = "" + args[i];
if (arg.isEmpty()) { if (arg == null || arg.isEmpty()) {
map.put("%s" + i, ""); map.put("%s" + i, "");
} else { } else {
arg = C.color(arg); arg = C.color(arg);
@ -927,6 +928,7 @@ public enum C {
map.put("%s", arg); map.put("%s", arg);
} }
} }
}
m = StringMan.replaceFromMap(m, map); m = StringMan.replaceFromMap(m, map);
return m; return m;
} }

View File

@ -120,8 +120,7 @@ public class Config {
* @param clazz * @param clazz
* @return * @return
*/ */
public static Map<String, Object> getFields( public static Map<String, Object> getFields(Class clazz) {
Class<? extends Settings.Enabled_Components> clazz) {
HashMap<String, Object> map = new HashMap<>(); HashMap<String, Object> map = new HashMap<>();
for (Field field : clazz.getFields()) { for (Field field : clazz.getFields()) {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
@ -143,8 +142,7 @@ public class Config {
} }
StringBuilder m = new StringBuilder(); StringBuilder m = new StringBuilder();
for (Object obj : listValue) { for (Object obj : listValue) {
m.append(System.lineSeparator()).append(spacing).append("- ") m.append(System.lineSeparator() + spacing + "- " + toYamlString(obj, spacing));
.append(toYamlString(obj, spacing));
} }
return m.toString(); return m.toString();
} }
@ -178,7 +176,7 @@ public class Config {
if (value == null && field.getType() != ConfigBlock.class) { if (value == null && field.getType() != ConfigBlock.class) {
setAccessible(field); setAccessible(field);
Class<?>[] classes = clazz.getDeclaredClasses(); Class<?>[] classes = clazz.getDeclaredClasses();
for (Class<? extends Object> current : classes) { for (Class current : classes) {
if (StringMan.isEqual(current.getSimpleName(), field.getName())) { if (StringMan.isEqual(current.getSimpleName(), field.getName())) {
field.set(instance, current.newInstance()); field.set(instance, current.newInstance());
break; break;

View File

@ -45,7 +45,7 @@ public class MySQL extends Database {
return this.connection; return this.connection;
} }
@Override public Connection openConnection() throws SQLException { @Override public Connection openConnection() throws SQLException, ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
return this.connection; return this.connection;
} }
@ -69,7 +69,7 @@ public class MySQL extends Database {
return true; return true;
} }
@Override public ResultSet querySQL(String query) throws SQLException { @Override public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
openConnection(); openConnection();
} }
@ -78,7 +78,7 @@ public class MySQL extends Database {
} }
} }
@Override public int updateSQL(String query) throws SQLException { @Override public int updateSQL(String query) throws SQLException, ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
openConnection(); openConnection();
} }

View File

@ -121,7 +121,8 @@ import java.util.concurrent.atomic.AtomicInteger;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
long last = System.currentTimeMillis(); long last = System.currentTimeMillis();
while (true) { while (true) {
if (SQLManager.this.closed) { if (SQLManager.this.closed) {
@ -157,6 +158,7 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
} }
}
}); });
} }
@ -513,10 +515,12 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
@Override public void createPlotsAndData(final List<Plot> myList, final Runnable whenDone) { @Override public void createPlotsAndData(final List<Plot> myList, final Runnable whenDone) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
try { try {
// Create the plots // Create the plots
createPlots(myList, () -> { createPlots(myList, new Runnable() {
@Override public void run() {
try { try {
// Creating datastructures // Creating datastructures
HashMap<PlotId, Plot> plotMap = new HashMap<>(); HashMap<PlotId, Plot> plotMap = new HashMap<>();
@ -552,18 +556,32 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
} }
createSettings(settings, () -> createTiers(helpers, "helpers", createSettings(settings, new Runnable() {
() -> createTiers(trusted, "trusted", @Override public void run() {
() -> createTiers(denied, "denied", () -> { createTiers(helpers, "helpers", new Runnable() {
@Override public void run() {
createTiers(trusted, "trusted", new Runnable() {
@Override public void run() {
createTiers(denied, "denied",
new Runnable() {
@Override public void run() {
try { try {
SQLManager.this.connection.commit(); SQLManager.this.connection
.commit();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }
})))); }
});
}
});
}
});
}
});
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots"); PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
@ -573,6 +591,7 @@ import java.util.concurrent.atomic.AtomicInteger;
e1.printStackTrace(); e1.printStackTrace();
} }
} }
}
}); });
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -583,6 +602,7 @@ import java.util.concurrent.atomic.AtomicInteger;
e1.printStackTrace(); e1.printStackTrace();
} }
} }
}
}); });
} }
@ -656,7 +676,7 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(i * 5 + 1, plot.getId().x); stmt.setInt(i * 5 + 1, plot.getId().x);
stmt.setInt(i * 5 + 2, plot.getId().y); stmt.setInt(i * 5 + 2, plot.getId().y);
try { try {
stmt.setString(i * 5 + 3, plot.guessOwner().toString()); stmt.setString(i * 5 + 3, plot.owner.toString());
} catch (SQLException ignored) { } catch (SQLException ignored) {
stmt.setString(i * 5 + 3, everyone.toString()); stmt.setString(i * 5 + 3, everyone.toString());
} }
@ -670,7 +690,7 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(i * 6 + 2, plot.getId().x); stmt.setInt(i * 6 + 2, plot.getId().x);
stmt.setInt(i * 6 + 3, plot.getId().y); stmt.setInt(i * 6 + 3, plot.getId().y);
try { try {
stmt.setString(i * 6 + 4, plot.guessOwner().toString()); stmt.setString(i * 6 + 4, plot.owner.toString());
} catch (SQLException ignored) { } catch (SQLException ignored) {
stmt.setString(i * 6 + 4, everyone.toString()); stmt.setString(i * 6 + 4, everyone.toString());
} }
@ -681,7 +701,7 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override public void setSQL(PreparedStatement stmt, Plot plot) throws SQLException { @Override public void setSQL(PreparedStatement stmt, Plot plot) throws SQLException {
stmt.setInt(1, plot.getId().x); stmt.setInt(1, plot.getId().x);
stmt.setInt(2, plot.getId().y); stmt.setInt(2, plot.getId().y);
stmt.setString(3, plot.guessOwner().toString()); stmt.setString(3, plot.owner.toString());
stmt.setString(4, plot.getArea().toString()); stmt.setString(4, plot.getArea().toString());
stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp()));
@ -909,7 +929,11 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(1, pair.id); stmt.setInt(1, pair.id);
} }
}; };
addGlobalTask(() -> setBulk(myList, mod, whenDone)); addGlobalTask(new Runnable() {
@Override public void run() {
setBulk(myList, mod, whenDone);
}
});
} }
public void createEmptySettings(final ArrayList<Integer> myList, final Runnable whenDone) { public void createEmptySettings(final ArrayList<Integer> myList, final Runnable whenDone) {
@ -953,15 +977,20 @@ import java.util.concurrent.atomic.AtomicInteger;
stmt.setInt(1, id); stmt.setInt(1, id);
} }
}; };
addGlobalTask(() -> setBulk(myList, mod, whenDone)); addGlobalTask(new Runnable() {
@Override public void run() {
setBulk(myList, mod, whenDone);
}
});
} }
public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) { public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) {
final long timestamp = plot.getTimestamp();
addPlotTask(plot, new UniqueStatement("createPlotSafe_" + plot.hashCode()) { addPlotTask(plot, new UniqueStatement("createPlotSafe_" + plot.hashCode()) {
@Override public void set(PreparedStatement stmt) throws SQLException { @Override public void set(PreparedStatement stmt) throws SQLException {
stmt.setInt(1, plot.getId().x); stmt.setInt(1, plot.getId().x);
stmt.setInt(2, plot.getId().y); stmt.setInt(2, plot.getId().y);
stmt.setString(3, plot.guessOwner().toString()); stmt.setString(3, plot.owner.toString());
stmt.setString(4, plot.getArea().toString()); stmt.setString(4, plot.getArea().toString());
stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp()));
stmt.setString(6, plot.getArea().toString()); stmt.setString(6, plot.getArea().toString());
@ -1028,7 +1057,7 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override public void set(PreparedStatement stmt) throws SQLException { @Override public void set(PreparedStatement stmt) throws SQLException {
stmt.setInt(1, plot.getId().x); stmt.setInt(1, plot.getId().x);
stmt.setInt(2, plot.getId().y); stmt.setInt(2, plot.getId().y);
stmt.setString(3, plot.guessOwner().toString()); stmt.setString(3, plot.owner.toString());
stmt.setString(4, plot.getArea().toString()); stmt.setString(4, plot.getArea().toString());
stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp()));
} }
@ -1322,7 +1351,7 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override public void delete(final Plot plot) { @Override public void delete(final Plot plot) {
PlotSquared.debug( PlotSquared.debug(
"Deleting plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: " "Deleting plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: "
+ plot.guessOwner() + " Index: " + plot.temp); + plot.owner + " Index: " + plot.temp);
deleteSettings(plot); deleteSettings(plot);
deleteDenied(plot); deleteDenied(plot);
deleteHelpers(plot); deleteHelpers(plot);
@ -1350,7 +1379,7 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override public void createPlotSettings(final int id, Plot plot) { @Override public void createPlotSettings(final int id, Plot plot) {
PlotSquared.debug( PlotSquared.debug(
"Creating plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: " "Creating plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: "
+ plot.guessOwner() + " Index: " + id); + plot.owner + " Index: " + id);
addPlotTask(plot, new UniqueStatement("createPlotSettings") { addPlotTask(plot, new UniqueStatement("createPlotSettings") {
@Override public void set(PreparedStatement stmt) throws SQLException { @Override public void set(PreparedStatement stmt) throws SQLException {
stmt.setInt(1, id); stmt.setInt(1, id);
@ -1656,8 +1685,8 @@ import java.util.concurrent.atomic.AtomicInteger;
time = System.currentTimeMillis() + id; time = System.currentTimeMillis() + id;
} }
} }
Plot p = new Plot(plot_id, user, new HashSet<>(), new HashSet<>(), Plot p = new Plot(plot_id, user, new HashSet<UUID>(), new HashSet<UUID>(),
new HashSet<>(), "", null, null, null, new HashSet<UUID>(), "", null, null, null,
new boolean[] {false, false, false, false}, time, id); new boolean[] {false, false, false, false}, time, id);
HashMap<PlotId, Plot> map = newPlots.get(areaid); HashMap<PlotId, Plot> map = newPlots.get(areaid);
if (map != null) { if (map != null) {
@ -2007,14 +2036,17 @@ import java.util.concurrent.atomic.AtomicInteger;
* Purge all plots with the following database IDs * Purge all plots with the following database IDs
*/ */
@Override public void purgeIds(final Set<Integer> uniqueIds) { @Override public void purgeIds(final Set<Integer> uniqueIds) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
if (!uniqueIds.isEmpty()) { if (!uniqueIds.isEmpty()) {
try { try {
ArrayList<Integer> uniqueIdsList = new ArrayList<>(uniqueIds); ArrayList<Integer> uniqueIdsList = new ArrayList<Integer>(uniqueIds);
String stmt_prefix = ""; String stmt_prefix = "";
int size = uniqueIdsList.size(); int size = uniqueIdsList.size();
int packet = 990; int packet = 990;
int amount = size / packet; int amount = size / packet;
int count = 0;
int last = -1;
for (int j = 0; j <= amount; j++) { for (int j = 0; j <= amount; j++) {
PlotSquared.debug("Purging " + (j * packet) + " / " + size); PlotSquared.debug("Purging " + (j * packet) + " / " + size);
List<Integer> subList = List<Integer> subList =
@ -2068,11 +2100,13 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
} }
PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!");
}
}); });
} }
@Override public void purge(final PlotArea area, final Set<PlotId> plots) { @Override public void purge(final PlotArea area, final Set<PlotId> plots) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix "SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + SQLManager.this.prefix
+ "plot` WHERE `world` = ?")) { + "plot` WHERE `world` = ?")) {
@ -2081,7 +2115,8 @@ import java.util.concurrent.atomic.AtomicInteger;
try (ResultSet r = stmt.executeQuery()) { try (ResultSet r = stmt.executeQuery()) {
ids = new HashSet<>(); ids = new HashSet<>();
while (r.next()) { while (r.next()) {
PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); PlotId plot_id =
new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z"));
if (plots.contains(plot_id)) { if (plots.contains(plot_id)) {
ids.add(r.getInt("id")); ids.add(r.getInt("id"));
} }
@ -2098,6 +2133,7 @@ import java.util.concurrent.atomic.AtomicInteger;
PlotId id = new PlotId(plotId.x, plotId.y); PlotId id = new PlotId(plotId.x, plotId.y);
area.removePlot(id); area.removePlot(id);
} }
}
}); });
} }
@ -2487,7 +2523,11 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
resultSet.close(); resultSet.close();
TaskManager.runTaskAsync(() -> result.run(metaMap)); TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
result.run(metaMap);
}
});
} }
}); });
@ -2551,8 +2591,11 @@ import java.util.concurrent.atomic.AtomicInteger;
} }
cluster = new PlotCluster(null, pos1, pos2, user, id); cluster = new PlotCluster(null, pos1, pos2, user, id);
clusters.put(id, cluster); clusters.put(id, cluster);
Set<PlotCluster> set = Set<PlotCluster> set = newClusters.get(areaid);
newClusters.computeIfAbsent(areaid, k -> new HashSet<>()); if (set == null) {
set = new HashSet<>();
newClusters.put(areaid, set);
}
set.add(cluster); set.add(cluster);
} }
//Getting helpers //Getting helpers
@ -2930,10 +2973,10 @@ import java.util.concurrent.atomic.AtomicInteger;
continue; continue;
} }
// owner // owner
if (!plot.guessOwner().equals(dataPlot.guessOwner())) { if (!plot.owner.equals(dataPlot.owner)) {
PlotSquared.debug( PlotSquared
"&8 - &7Setting owner: " + plot + " -> " + MainUtil.getName(plot.guessOwner())); .debug("&8 - &7Setting owner: " + plot + " -> " + MainUtil.getName(plot.owner));
setOwner(plot, plot.guessOwner()); setOwner(plot, plot.owner);
} }
// trusted // trusted
if (!plot.getTrusted().equals(dataPlot.getTrusted())) { if (!plot.getTrusted().equals(dataPlot.getTrusted())) {
@ -3026,7 +3069,8 @@ import java.util.concurrent.atomic.AtomicInteger;
@Override @Override
public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min, public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min,
final PlotId max) { final PlotId max) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
if (min == null) { if (min == null) {
try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement( try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(
"UPDATE `" + SQLManager.this.prefix "UPDATE `" + SQLManager.this.prefix
@ -3074,11 +3118,13 @@ import java.util.concurrent.atomic.AtomicInteger;
e.printStackTrace(); e.printStackTrace();
} }
} }
}
}); });
} }
@Override public void replaceUUID(final UUID old, final UUID now) { @Override public void replaceUUID(final UUID old, final UUID now) {
addGlobalTask(() -> { addGlobalTask(new Runnable() {
@Override public void run() {
try (Statement stmt = SQLManager.this.connection.createStatement()) { try (Statement stmt = SQLManager.this.connection.createStatement()) {
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now "UPDATE `" + SQLManager.this.prefix + "cluster` SET `owner` = '" + now
@ -3090,20 +3136,21 @@ import java.util.concurrent.atomic.AtomicInteger;
"UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '" "UPDATE `" + SQLManager.this.prefix + "cluster_invited` SET `user_uuid` = '"
+ now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now.toString() "UPDATE `" + SQLManager.this.prefix + "plot` SET `owner` = '" + now
+ "' WHERE `owner` = '" + old.toString() + '\''); .toString() + "' WHERE `owner` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '" + now "UPDATE `" + SQLManager.this.prefix + "plot_denied` SET `user_uuid` = '"
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '" + now "UPDATE `" + SQLManager.this.prefix + "plot_helpers` SET `user_uuid` = '"
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
stmt.executeUpdate( stmt.executeUpdate(
"UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '" + now "UPDATE `" + SQLManager.this.prefix + "plot_trusted` SET `user_uuid` = '"
.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\''); + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + '\'');
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }

View File

@ -146,7 +146,7 @@ public class FlagManager {
* @return * @return
*/ */
public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) { public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
if (plot.guessOwner() == null) { if (plot.owner == null) {
return null; return null;
} }
return getSettingFlag(plot.getArea(), plot.getSettings(), flag); return getSettingFlag(plot.getArea(), plot.getSettings(), flag);

View File

@ -244,6 +244,7 @@ public class ClassicPlotManager extends SquarePlotManager {
Location bot = plot.getExtendedBottomAbs() Location bot = plot.getExtendedBottomAbs()
.subtract(plot.getMerged(3) ? 0 : 1, 0, plot.getMerged(0) ? 0 : 1); .subtract(plot.getMerged(3) ? 0 : 1, 0, plot.getMerged(0) ? 0 : 1);
Location top = plot.getExtendedTopAbs().add(1, 0, 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1);
PseudoRandom random = new PseudoRandom();
LocalBlockQueue queue = plotArea.getQueue(false); LocalBlockQueue queue = plotArea.getQueue(false);
int y = dpw.WALL_HEIGHT + 1; int y = dpw.WALL_HEIGHT + 1;
if (!plot.getMerged(0)) { if (!plot.getMerged(0)) {

View File

@ -6,10 +6,12 @@ import com.github.intellectualsites.plotsquared.plot.util.MathMan;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import java.util.HashMap;
public class HybridGen extends IndependentPlotGenerator { public class HybridGen extends IndependentPlotGenerator {
@Override public String getName() { @Override public String getName() {
return PlotSquared.get().IMP.getPluginName(); return PlotSquared.imp().getPluginName();
} }
private void placeSchem(HybridPlotWorld world, ScopedLocalBlockQueue result, short relativeX, private void placeSchem(HybridPlotWorld world, ScopedLocalBlockQueue result, short relativeX,
@ -39,6 +41,8 @@ public class HybridGen extends IndependentPlotGenerator {
} }
// Coords // Coords
Location min = result.getMin(); Location min = result.getMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
int bx = (min.getX()) - hpw.ROAD_OFFSET_X; int bx = (min.getX()) - hpw.ROAD_OFFSET_X;
int bz = (min.getZ()) - hpw.ROAD_OFFSET_Z; int bz = (min.getZ()) - hpw.ROAD_OFFSET_Z;
short rbx; short rbx;
@ -82,6 +86,7 @@ public class HybridGen extends IndependentPlotGenerator {
} }
} }
// generation // generation
HashMap<Integer, BaseBlock[]> sch = hpw.G_SCH;
for (short x = 0; x < 16; x++) { for (short x = 0; x < 16; x++) {
if (gx[x]) { if (gx[x]) {
for (short z = 0; z < 16; z++) { for (short z = 0; z < 16; z++) {

View File

@ -197,10 +197,12 @@ public class HybridPlotManager extends ClassicPlotManager {
// And finally set the schematic, the y value is unimportant for this function // And finally set the schematic, the y value is unimportant for this function
pastePlotSchematic(dpw, queue, bot, top); pastePlotSchematic(dpw, queue, bot, top);
} }
}, () -> { }, new Runnable() {
@Override public void run() {
queue.enqueue(); queue.enqueue();
// And notify whatever called this when plot clearing is done // And notify whatever called this when plot clearing is done
GlobalBlockQueue.IMP.addTask(whenDone); GlobalBlockQueue.IMP.addTask(whenDone);
}
}, 10); }, 10);
return true; return true;
} }

View File

@ -212,7 +212,11 @@ public abstract class HybridUtils {
PlotSquared.debug("&d - Potentially skipping 1024 chunks"); PlotSquared.debug("&d - Potentially skipping 1024 chunks");
PlotSquared.debug("&d - TODO: recommend chunkster if corrupt"); PlotSquared.debug("&d - TODO: recommend chunkster if corrupt");
} }
GlobalBlockQueue.IMP.addTask(() -> TaskManager.runTaskLater(task, 20)); GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override public void run() {
TaskManager.runTaskLater(task, 20);
}
});
} }
}); });
} }

View File

@ -158,7 +158,8 @@ public class PlotListener {
if (titles) { if (titles) {
if (!C.TITLE_ENTERED_PLOT.s().isEmpty() || !C.TITLE_ENTERED_PLOT_SUB.s() if (!C.TITLE_ENTERED_PLOT.s().isEmpty() || !C.TITLE_ENTERED_PLOT_SUB.s()
.isEmpty()) { .isEmpty()) {
TaskManager.runTaskLaterAsync(() -> { TaskManager.runTaskLaterAsync(new Runnable() {
@Override public void run() {
Plot lastPlot = player.getMeta(PlotPlayer.META_LAST_PLOT); Plot lastPlot = player.getMeta(PlotPlayer.META_LAST_PLOT);
if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) {
Map<String, String> replacements = new HashMap<>(); Map<String, String> replacements = new HashMap<>();
@ -167,13 +168,14 @@ public class PlotListener {
replacements.put("%world%", plot.getArea().toString()); replacements.put("%world%", plot.getArea().toString());
replacements.put("%greeting%", greeting); replacements.put("%greeting%", greeting);
replacements.put("%alias", plot.toString()); replacements.put("%alias", plot.toString());
replacements.put("%s", MainUtil.getName(plot.guessOwner())); replacements.put("%s", MainUtil.getName(plot.owner));
String main = String main = StringMan
StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements); .replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements);
String sub = StringMan String sub = StringMan
.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements); .replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements);
AbstractTitle.sendTitle(player, main, sub); AbstractTitle.sendTitle(player, main, sub);
} }
}
}, 20); }, 20);
} }
} }

View File

@ -805,12 +805,14 @@ public class Plot {
Runnable run = new Runnable() { Runnable run = new Runnable() {
@Override public void run() { @Override public void run() {
if (queue.isEmpty()) { if (queue.isEmpty()) {
Runnable run = () -> { Runnable run = new Runnable() {
@Override public void run() {
for (RegionWrapper region : regions) { for (RegionWrapper region : regions) {
Location[] corners = region.getCorners(getWorldName()); Location[] corners = region.getCorners(getWorldName());
ChunkManager.manager.clearAllEntities(corners[0], corners[1]); ChunkManager.manager.clearAllEntities(corners[0], corners[1]);
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
}
}; };
for (Plot current : plots) { for (Plot current : plots) {
if (isDelete || current.owner == null) { if (isDelete || current.owner == null) {
@ -925,10 +927,12 @@ public class Plot {
current.setMerged(merged); current.setMerged(merged);
} }
if (createSign) { if (createSign) {
GlobalBlockQueue.IMP.addTask(() -> { GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override public void run() {
for (Plot current : plots) { for (Plot current : plots) {
current.setSign(MainUtil.getName(current.owner)); current.setSign(MainUtil.getName(current.owner));
} }
}
}); });
} }
if (createRoad) { if (createRoad) {
@ -946,7 +950,11 @@ public class Plot {
if (!isLoaded()) if (!isLoaded())
return; return;
if (!PlotSquared.get().isMainThread(Thread.currentThread())) { if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
TaskManager.runTask(() -> Plot.this.setSign(name)); TaskManager.runTask(new Runnable() {
@Override public void run() {
Plot.this.setSign(name);
}
});
return; return;
} }
PlotManager manager = this.area.getPlotManager(); PlotManager manager = this.area.getPlotManager();
@ -1036,11 +1044,13 @@ public class Plot {
return false; return false;
} }
final Set<Plot> plots = this.getConnectedPlots(); final Set<Plot> plots = this.getConnectedPlots();
this.clear(false, true, () -> { this.clear(false, true, new Runnable() {
@Override public void run() {
for (Plot current : plots) { for (Plot current : plots) {
current.unclaim(); current.unclaim();
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
}
}); });
return true; return true;
} }
@ -1474,11 +1484,13 @@ public class Plot {
this.getDenied().clear(); this.getDenied().clear();
this.settings = new PlotSettings(); this.settings = new PlotSettings();
if (this.area.addPlot(this)) { if (this.area.addPlot(this)) {
DBFunc.createPlotAndSettings(this, () -> { DBFunc.createPlotAndSettings(this, new Runnable() {
@Override public void run() {
PlotArea plotworld = Plot.this.area; PlotArea plotworld = Plot.this.area;
if (notify && plotworld.AUTO_MERGE) { if (notify && plotworld.AUTO_MERGE) {
Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true); Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true);
} }
}
}); });
return true; return true;
} }
@ -1826,7 +1838,8 @@ public class Plot {
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
} }
} else { } else {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
String name = Plot.this.id + "," + Plot.this.area + ',' + MainUtil String name = Plot.this.id + "," + Plot.this.area + ',' + MainUtil
.getName(Plot.this.owner); .getName(Plot.this.owner);
boolean result = SchematicHandler.manager.save(value, boolean result = SchematicHandler.manager.save(value,
@ -1835,6 +1848,7 @@ public class Plot {
whenDone.value = result; whenDone.value = result;
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
} }
}
}); });
} }
} }
@ -2543,7 +2557,9 @@ public class Plot {
} }
Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gtopabs = this.area.getPlotAbs(top).getTopAbs();
Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs();
visited.addAll(MainUtil.getPlotSelectionIds(bot, top)); for (PlotId id : MainUtil.getPlotSelectionIds(bot, top)) {
visited.add(id);
}
for (int x = bot.x; x <= top.x; x++) { for (int x = bot.x; x <= top.x; x++) {
Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); Plot plot = this.area.getPlotAbs(new PlotId(x, top.y));
if (plot.getMerged(2)) { if (plot.getMerged(2)) {
@ -2610,11 +2626,13 @@ public class Plot {
* - Usually called when the plot state changes (unclaimed/claimed/flag change etc) * - Usually called when the plot state changes (unclaimed/claimed/flag change etc)
*/ */
public void reEnter() { public void reEnter() {
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
for (PlotPlayer pp : Plot.this.getPlayersInPlot()) { for (PlotPlayer pp : Plot.this.getPlayersInPlot()) {
PlotListener.plotExit(pp, Plot.this); PlotListener.plotExit(pp, Plot.this);
PlotListener.plotEntry(pp, Plot.this); PlotListener.plotEntry(pp, Plot.this);
} }
}
}, 1); }, 1);
} }
@ -2669,7 +2687,8 @@ public class Plot {
MainUtil.sendMessage(player, C.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + ""); MainUtil.sendMessage(player, C.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + "");
final String name = player.getName(); final String name = player.getName();
TaskManager.TELEPORT_QUEUE.add(name); TaskManager.TELEPORT_QUEUE.add(name);
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
if (!TaskManager.TELEPORT_QUEUE.contains(name)) { if (!TaskManager.TELEPORT_QUEUE.contains(name)) {
MainUtil.sendMessage(player, C.TELEPORT_FAILED); MainUtil.sendMessage(player, C.TELEPORT_FAILED);
return; return;
@ -2679,6 +2698,7 @@ public class Plot {
MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT);
player.teleport(location); player.teleport(location);
} }
}
}, Settings.Teleport.DELAY * 20); }, Settings.Teleport.DELAY * 20);
return true; return true;
} }
@ -2864,8 +2884,11 @@ public class Plot {
final Location pos2 = corners[1]; final Location pos2 = corners[1];
Location newPos = pos1.clone().add(offsetX, 0, offsetZ); Location newPos = pos1.clone().add(offsetX, 0, offsetZ);
newPos.setWorld(destination.getWorldName()); newPos.setWorld(destination.getWorldName());
ChunkManager.manager.copyRegion(pos1, pos2, newPos, ChunkManager.manager.copyRegion(pos1, pos2, newPos, new Runnable() {
() -> ChunkManager.manager.regenerateRegion(pos1, pos2, false, task)); @Override public void run() {
ChunkManager.manager.regenerateRegion(pos1, pos2, false, task);
}
});
} }
}; };
Runnable swap = new Runnable() { Runnable swap = new Runnable() {

View File

@ -179,7 +179,7 @@ public abstract class PlotArea {
} }
public Set<PlotCluster> getClusters() { public Set<PlotCluster> getClusters() {
return this.clusters == null ? new HashSet<>() : this.clusters.getAll(); return this.clusters == null ? new HashSet<PlotCluster>() : this.clusters.getAll();
} }
/** /**
@ -496,7 +496,7 @@ public abstract class PlotArea {
final HashSet<Plot> myPlots = new HashSet<>(); final HashSet<Plot> myPlots = new HashSet<>();
foreachPlotAbs(new RunnableVal<Plot>() { foreachPlotAbs(new RunnableVal<Plot>() {
@Override public void run(Plot value) { @Override public void run(Plot value) {
if (uuid.equals(value.guessOwner())) { if (uuid.equals(value.owner)) {
myPlots.add(value); myPlots.add(value);
} }
} }
@ -657,7 +657,12 @@ public abstract class PlotArea {
public Set<Plot> getBasePlots() { public Set<Plot> getBasePlots() {
HashSet<Plot> myPlots = new HashSet<>(getPlots()); HashSet<Plot> myPlots = new HashSet<>(getPlots());
myPlots.removeIf(plot -> !plot.isBasePlot()); Iterator<Plot> iterator = myPlots.iterator();
while (iterator.hasNext()) {
if (!iterator.next().isBasePlot()) {
iterator.remove();
}
}
return myPlots; return myPlots;
} }

View File

@ -78,7 +78,7 @@ public abstract class PlotBlock implements ConfigurationSerializable {
public static PlotBlock get(@NonNull final Object type) { public static PlotBlock get(@NonNull final Object type) {
if (blockRegistry == null) { if (blockRegistry == null) {
blockRegistry = PlotSquared.get().IMP.getBlockRegistry(); blockRegistry = PlotSquared.imp().getBlockRegistry();
if (blockRegistry == null) { if (blockRegistry == null) {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"The PlotSquared implementation has not registered a custom block registry." "The PlotSquared implementation has not registered a custom block registry."
@ -99,7 +99,7 @@ public abstract class PlotBlock implements ConfigurationSerializable {
public <T> T to(@NonNull final Class<T> clazz) { public <T> T to(@NonNull final Class<T> clazz) {
if (blockRegistry == null) { if (blockRegistry == null) {
blockRegistry = PlotSquared.get().IMP.getBlockRegistry(); blockRegistry = PlotSquared.imp().getBlockRegistry();
if (blockRegistry == null) { if (blockRegistry == null) {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"The PlotSquared implementation has not registered a custom block registry." "The PlotSquared implementation has not registered a custom block registry."

View File

@ -5,7 +5,7 @@ import java.util.UUID;
public class PlotHandler { public class PlotHandler {
public static boolean sameOwners(final Plot plot1, final Plot plot2) { public static boolean sameOwners(final Plot plot1, final Plot plot2) {
if (plot1.guessOwner() == null || plot2.guessOwner() == null) { if (plot1.owner == null || plot2.owner == null) {
return false; return false;
} }
final Set<UUID> owners = plot1.getOwners(); final Set<UUID> owners = plot1.getOwners();

View File

@ -5,8 +5,6 @@ import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.object.chat.PlainChatManager; import com.github.intellectualsites.plotsquared.plot.object.chat.PlainChatManager;
import com.github.intellectualsites.plotsquared.plot.util.ChatManager; import com.github.intellectualsites.plotsquared.plot.util.ChatManager;
import java.util.Arrays;
public class PlotMessage { public class PlotMessage {
private Object builder; private Object builder;
@ -16,8 +14,8 @@ public class PlotMessage {
reset(ChatManager.manager); reset(ChatManager.manager);
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug( PlotSquared.debug(
PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + Arrays PlotSquared.imp().getPluginName() + " doesn't support fancy chat for " + PlotSquared
.toString(PlotSquared.get().IMP.getServerVersion())); .get().IMP.getServerVersion());
ChatManager.manager = new PlainChatManager(); ChatManager.manager = new PlainChatManager();
reset(ChatManager.manager); reset(ChatManager.manager);
} }

View File

@ -222,6 +222,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
return getClusterCount(getLocation().getWorld()); return getClusterCount(getLocation().getWorld());
} }
final AtomicInteger count = new AtomicInteger(0); final AtomicInteger count = new AtomicInteger(0);
final UUID uuid = getUUID();
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() { PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) { @Override public void run(PlotArea value) {
for (PlotCluster cluster : value.getClusters()) { for (PlotCluster cluster : value.getClusters()) {
@ -258,6 +259,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
public int getClusterCount(String world) { public int getClusterCount(String world) {
UUID uuid = getUUID();
int count = 0; int count = 0;
for (PlotArea area : PlotSquared.get().getPlotAreas(world)) { for (PlotArea area : PlotSquared.get().getPlotAreas(world)) {
for (PlotCluster cluster : area.getClusters()) { for (PlotCluster cluster : area.getClusters()) {
@ -567,27 +569,31 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
final Location loc = final Location loc =
new Location(plot.getWorldName(), x, y, z); new Location(plot.getWorldName(), x, y, z);
if (plot.isLoaded()) { if (plot.isLoaded()) {
TaskManager.runTask(() -> { TaskManager.runTask(new Runnable() {
@Override public void run() {
if (getMeta("teleportOnLogin", true)) { if (getMeta("teleportOnLogin", true)) {
teleport(loc); teleport(loc);
sendMessage(C.TELEPORTED_TO_PLOT.f() sendMessage(C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc) (" + plotX + "," + " (quitLoc) (" + plotX + ","
+ plotZ + ")"); + plotZ + ")");
} }
}
}); });
} else if (!PlotSquared.get() } else if (!PlotSquared.get()
.isMainThread(Thread.currentThread())) { .isMainThread(Thread.currentThread())) {
if (getMeta("teleportOnLogin", true)) { if (getMeta("teleportOnLogin", true)) {
if (plot.teleportPlayer(PlotPlayer.this)) { if (plot.teleportPlayer(PlotPlayer.this)) {
TaskManager.runTask(() -> { TaskManager.runTask(new Runnable() {
@Override public void run() {
if (getMeta("teleportOnLogin", if (getMeta("teleportOnLogin",
true)) { true)) {
teleport(loc); teleport(loc);
sendMessage( sendMessage(
C.TELEPORTED_TO_PLOT.f() C.TELEPORTED_TO_PLOT.f()
+ " (quitLoc-unloaded) (" + " (quitLoc-unloaded) ("
+ plotX + "," + plotZ + plotX + ","
+ ")"); + plotZ + ")");
}
} }
}); });
} }
@ -612,7 +618,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
} }
public void removePersistentMeta(String key) { public void removePersistentMeta(String key) {
if (this.metaMap.containsKey(key)) {
this.metaMap.remove(key); this.metaMap.remove(key);
}
if (Settings.Enabled_Components.PERSISTENT_META) { if (Settings.Enabled_Components.PERSISTENT_META) {
DBFunc.removePersistentMeta(getUUID(), key); DBFunc.removePersistentMeta(getUUID(), key);
} }

View File

@ -14,6 +14,12 @@ import java.util.*;
*/ */
public class PlotSettings { public class PlotSettings {
/**
* Merged plots.
*
* @deprecated Raw access
*/
@Deprecated public boolean[] merged = new boolean[] {false, false, false, false};
/** /**
* Plot alias. * Plot alias.
* *
@ -26,24 +32,20 @@ public class PlotSettings {
* @deprecated Raw access * @deprecated Raw access
*/ */
@Deprecated public List<PlotComment> comments = null; @Deprecated public List<PlotComment> comments = null;
/** /**
* The ratings for a plot. * The ratings for a plot.
* *
* @deprecated Raw access * @deprecated Raw access
*/ */
@Deprecated public HashMap<UUID, Integer> ratings; @Deprecated public HashMap<UUID, Integer> ratings;
/** /**
* Flags. * Flags.
* *
* @deprecated Raw access * @deprecated Raw access
*/ */
@Deprecated public HashMap<Flag<?>, Object> flags = new HashMap<>(); @Deprecated public HashMap<Flag<?>, Object> flags = new HashMap<>();
/**
* Merged plots.
*
* @deprecated Raw access
*/
@Deprecated private boolean[] merged = new boolean[] {false, false, false, false};
/** /**
* Home Position. * Home Position.
* *

View File

@ -14,8 +14,10 @@ public abstract class CommentInbox {
public boolean canRead(Plot plot, PlotPlayer player) { public boolean canRead(Plot plot, PlotPlayer player) {
if (Permissions.hasPermission(player, "plots.inbox.read." + toString(), true)) { if (Permissions.hasPermission(player, "plots.inbox.read." + toString(), true)) {
return plot.isOwner(player.getUUID()) || Permissions if (plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, "plots.inbox.read." + toString() + ".other", true); .hasPermission(player, "plots.inbox.read." + toString() + ".other", true)) {
return true;
}
} }
return false; return false;
} }
@ -31,8 +33,10 @@ public abstract class CommentInbox {
public boolean canModify(Plot plot, PlotPlayer player) { public boolean canModify(Plot plot, PlotPlayer player) {
if (Permissions.hasPermission(player, "plots.inbox.modify." + toString(), true)) { if (Permissions.hasPermission(player, "plots.inbox.modify." + toString(), true)) {
return plot.isOwner(player.getUUID()) || Permissions if (plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, "plots.inbox.modify." + toString() + ".other", true); .hasPermission(player, "plots.inbox.modify." + toString() + ".other", true)) {
return true;
}
} }
return false; return false;
} }

View File

@ -27,7 +27,7 @@ public class InboxOwner extends CommentInbox {
plot.getSettings().addComment(comment); plot.getSettings().addComment(comment);
} }
} else { } else {
plot.getSettings().setComments(new ArrayList<>()); plot.getSettings().setComments(new ArrayList<PlotComment>());
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
} }
@ -36,7 +36,7 @@ public class InboxOwner extends CommentInbox {
} }
@Override public boolean addComment(Plot plot, PlotComment comment) { @Override public boolean addComment(Plot plot, PlotComment comment) {
if (plot.guessOwner() == null) { if (plot.owner == null) {
return false; return false;
} }
plot.getSettings().addComment(comment); plot.getSettings().addComment(comment);

View File

@ -20,7 +20,7 @@ public class InboxReport extends CommentInbox {
} }
@Override public boolean addComment(Plot plot, PlotComment comment) { @Override public boolean addComment(Plot plot, PlotComment comment) {
if (plot.guessOwner() == null) { if (plot.owner == null) {
return false; return false;
} }
DBFunc.setComment(plot, comment); DBFunc.setComment(plot, comment);

View File

@ -104,7 +104,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
} }
@Override public void removePlotArea(PlotArea area) { @Override public void removePlotArea(PlotArea area) {
ArrayList<PlotArea> globalAreas = new ArrayList<>(Arrays.asList(plotAreas)); ArrayList<PlotArea> globalAreas = new ArrayList<PlotArea>(Arrays.asList(plotAreas));
globalAreas.remove(area); globalAreas.remove(area);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]);
if (globalAreas.isEmpty()) { if (globalAreas.isEmpty()) {

View File

@ -111,8 +111,8 @@ public class SinglePlotArea extends GridPlotWorld {
return p; return p;
} }
PlotSettings s = p.getSettings(); PlotSettings s = p.getSettings();
p = new SinglePlot(p.getId(), p.guessOwner(), p.getTrusted(), p.getMembers(), p.getDenied(), p = new SinglePlot(p.getId(), p.owner, p.getTrusted(), p.getMembers(), p.getDenied(),
s.alias, s.getPosition(), null, this, s.getMerged(), p.getTimestamp(), p.temp); s.alias, s.getPosition(), null, this, s.merged, p.getTimestamp(), p.temp);
p.getSettings().flags = s.flags; p.getSettings().flags = s.flags;
return p; return p;
} }

View File

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

View File

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

View File

@ -71,7 +71,8 @@ public abstract class ChunkManager {
public static void largeRegionTask(final String world, final RegionWrapper region, public static void largeRegionTask(final String world, final RegionWrapper region,
final RunnableVal<ChunkLoc> task, final Runnable whenDone) { final RunnableVal<ChunkLoc> task, final Runnable whenDone) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
HashSet<ChunkLoc> chunks = new HashSet<>(); HashSet<ChunkLoc> chunks = new HashSet<>();
Set<ChunkLoc> mcrs = manager.getChunkChunks(world); Set<ChunkLoc> mcrs = manager.getChunkChunks(world);
for (ChunkLoc mcr : mcrs) { for (ChunkLoc mcr : mcrs) {
@ -104,6 +105,7 @@ public abstract class ChunkManager {
} }
} }
}, whenDone); }, whenDone);
}
}); });
} }
@ -237,11 +239,12 @@ public abstract class ChunkManager {
public void deleteRegionFiles(final String world, final Collection<ChunkLoc> chunks, public void deleteRegionFiles(final String world, final Collection<ChunkLoc> chunks,
final Runnable whenDone) { final Runnable whenDone) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
for (ChunkLoc loc : chunks) { for (ChunkLoc loc : chunks) {
String directory = String directory =
world + File.separator + "region" + File.separator + "r." + loc.x + "." + loc.z world + File.separator + "region" + File.separator + "r." + loc.x + "."
+ ".mca"; + loc.z + ".mca";
File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory); File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)"); PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)");
if (file.exists()) { if (file.exists()) {
@ -249,6 +252,7 @@ public abstract class ChunkManager {
} }
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
}
}); });
} }

View File

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

View File

@ -20,7 +20,8 @@ public class CommentManager {
if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) { if (!Settings.Enabled_Components.COMMENT_NOTIFIER || !plot.isOwner(player.getUUID())) {
return; return;
} }
TaskManager.runTaskLaterAsync(() -> { TaskManager.runTaskLaterAsync(new Runnable() {
@Override public void run() {
Collection<CommentInbox> boxes = CommentManager.inboxes.values(); Collection<CommentInbox> boxes = CommentManager.inboxes.values();
final AtomicInteger count = new AtomicInteger(0); final AtomicInteger count = new AtomicInteger(0);
final AtomicInteger size = new AtomicInteger(boxes.size()); final AtomicInteger size = new AtomicInteger(boxes.size());
@ -31,7 +32,8 @@ public class CommentManager {
if (value != null) { if (value != null) {
int num = 0; int num = 0;
for (PlotComment comment : value) { for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) { if (comment.timestamp > getTimestamp(player,
inbox.toString())) {
num++; num++;
} }
} }
@ -46,6 +48,7 @@ public class CommentManager {
} }
}); });
} }
}
}, 20); }, 20);
} }

Some files were not shown because too many files have changed in this diff Show More