Cleanup of various methods

mainly just more lambda's

Signed-off-by: matt <4009945+MattBDev@users.noreply.github.com>
This commit is contained in:
matt 2019-02-05 19:41:03 -05:00
parent e3d43509cf
commit 9a23b718f3
5 changed files with 218 additions and 311 deletions

View File

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

@ -214,11 +214,8 @@ import java.util.zip.ZipInputStream;
} }
// Economy // Economy
if (Settings.Enabled_Components.ECONOMY) { if (Settings.Enabled_Components.ECONOMY) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(
@Override public void run() { () -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler());
EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler();
}
});
} }
/* // Check for updates /* // Check for updates
@ -247,21 +244,19 @@ import java.util.zip.ZipInputStream;
this.IMP.setGenerator(world); this.IMP.setGenerator(world);
} }
} }
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(() -> {
@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("&c`" + world + "` was not properly loaded - " + IMP
debug("&c`" + world + "` was not properly loaded - " + IMP .getPluginName() + " will now try to load it properly: ");
.getPluginName() + " 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( "&8 - &7Your world management plugin may be faulty (or non existent)");
"&8 - &7Your world management plugin may be faulty (or non existent)"); PlotSquared.this.IMP.setGenerator(world);
PlotSquared.this.IMP.setGenerator(world);
}
} }
} }
}, 1); }, 1);
@ -342,25 +337,21 @@ import java.util.zip.ZipInputStream;
} }
private void startUuidCatching() { private void startUuidCatching() {
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(() -> {
@Override public void run() { debug("Starting UUID caching");
debug("Starting UUID caching"); UUIDHandler.startCaching(() -> {
UUIDHandler.startCaching(new Runnable() { UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE);
@Override public void run() { foreachPlotRaw(new RunnableVal<Plot>() {
UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); @Override public void run(Plot plot) {
foreachPlotRaw(new RunnableVal<Plot>() { if (plot.hasOwner() && plot.temp != -1) {
@Override public void run(Plot plot) { if (UUIDHandler.getName(plot.owner) == null) {
if (plot.hasOwner() && plot.temp != -1) { UUIDHandler.implementation.unknown.add(plot.owner);
if (UUIDHandler.getName(plot.owner) == null) {
UUIDHandler.implementation.unknown.add(plot.owner);
}
}
} }
}); }
startExpiryTasks();
} }
}); });
} startExpiryTasks();
});
}, 20); }, 20);
} }
@ -495,11 +486,8 @@ 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 = this.plots_tmp.get(area.toString()); HashMap<PlotId, Plot> map =
if (map == null) { this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>());
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);
} }
@ -567,11 +555,7 @@ import java.util.zip.ZipInputStream;
result.add(plot); result.add(plot);
} }
} }
Collections.sort(overflow, new Comparator<Plot>() { overflow.sort(Comparator.comparingInt(Plot::hashCode));
@Override public int compare(Plot a, Plot b) {
return a.hashCode() - b.hashCode();
}
});
result.addAll(overflow); result.addAll(overflow);
return result; return result;
} }
@ -581,12 +565,8 @@ import java.util.zip.ZipInputStream;
* *
* @param plots the collection of plots to sort * @param plots the collection of plots to sort
* @return the sorted collection * @return the sorted collection
* @deprecated Unchecked, please use
* {@link #sortPlots(Collection, SortType, PlotArea)} which has
* additional checks before calling this
*/ */
// TODO: Re-evaluate deprecation of this, as it's being used internally private ArrayList<Plot> sortPlotsByHash(Collection<Plot> plots) {
@Deprecated public ArrayList<Plot> sortPlotsByHash(Collection<Plot> plots) {
int hardmax = 256000; int hardmax = 256000;
int max = 0; int max = 0;
int overflowSize = 0; int overflowSize = 0;
@ -618,7 +598,7 @@ import java.util.zip.ZipInputStream;
overflow.add(plot); overflow.add(plot);
} }
} }
Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); Plot[] overflowArray = overflow.toArray(new Plot[0]);
sortPlotsByHash(overflowArray); sortPlotsByHash(overflowArray);
ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length); ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length);
for (Plot plot : cache) { for (Plot plot : cache) {
@ -627,9 +607,7 @@ import java.util.zip.ZipInputStream;
} }
} }
Collections.addAll(result, overflowArray); Collections.addAll(result, overflowArray);
for (Plot plot : extra) { result.addAll(extra);
result.add(plot);
}
return result; return result;
} }
@ -638,8 +616,7 @@ import java.util.zip.ZipInputStream;
* *
* @param input an array of plots to sort * @param input an array of plots to sort
*/ */
// TODO: Re-evaluate deprecation of this, as it's being used internally private void sortPlotsByHash(Plot[] input) {
@Deprecated public void sortPlotsByHash(Plot[] input) {
List<Plot>[] bucket = new ArrayList[32]; List<Plot>[] bucket = new ArrayList[32];
for (int i = 0; i < bucket.length; i++) { for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<>(); bucket[i] = new ArrayList<>();
@ -648,26 +625,25 @@ import java.util.zip.ZipInputStream;
int placement = 1; int placement = 1;
while (!maxLength) { while (!maxLength) {
maxLength = true; maxLength = true;
for (Plot i : input) { for (Plot plot : input) {
int tmp = MathMan.getPositiveId(i.hashCode()) / placement; int tmp = MathMan.getPositiveId(plot.hashCode()) / placement;
bucket[tmp & 31].add(i); bucket[tmp & 31].add(plot);
if (maxLength && tmp > 0) { if (maxLength && tmp > 0) {
maxLength = false; maxLength = false;
} }
} }
int a = 0; int a = 0;
for (int b = 0; b < 32; b++) { for (int i = 0; i < 32; i++) {
for (Plot i : bucket[b]) { for (Plot plot : bucket[i]) {
input[a++] = i; input[a++] = plot;
} }
bucket[b].clear(); bucket[i].clear();
} }
placement *= 32; placement *= 32;
} }
} }
// TODO: Re-evaluate deprecation of this, as it's being used internally private ArrayList<Plot> sortPlotsByTimestamp(Collection<Plot> plots) {
@Deprecated public ArrayList<Plot> sortPlotsByTimestamp(Collection<Plot> plots) {
int hardMax = 256000; int hardMax = 256000;
int max = 0; int max = 0;
int overflowSize = 0; int overflowSize = 0;
@ -699,7 +675,7 @@ import java.util.zip.ZipInputStream;
overflow.add(plot); overflow.add(plot);
} }
} }
Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); Plot[] overflowArray = overflow.toArray(new Plot[0]);
sortPlotsByHash(overflowArray); sortPlotsByHash(overflowArray);
ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length); ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length);
for (Plot plot : cache) { for (Plot plot : cache) {
@ -708,9 +684,7 @@ import java.util.zip.ZipInputStream;
} }
} }
Collections.addAll(result, overflowArray); Collections.addAll(result, overflowArray);
for (Plot plot : extra) { result.addAll(extra);
result.add(plot);
}
return result; return result;
} }
@ -719,29 +693,18 @@ import java.util.zip.ZipInputStream;
* *
* @param input * @param input
* @return * @return
* @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks
*/ */
// TODO: Re-evaluate deprecation of this, as it's being used internally private List<Plot> sortPlotsByModified(Collection<Plot> input) {
@Deprecated public List<Plot> sortPlotsByModified(Collection<Plot> input) {
List<Plot> list; List<Plot> list;
if (input instanceof List) { if (input instanceof List) {
list = (List<Plot>) input; list = (List<Plot>) input;
} else { } else {
list = new ArrayList<>(input); list = new ArrayList<>(input);
} }
Collections.sort(list, new Comparator<Plot>() { list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.owner)));
@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;
} }
public ArrayList<Plot> sortPlots(Collection<Plot> plots) {
return sortPlots(plots, SortType.DISTANCE_FROM_ORIGIN, null);
}
/** /**
* Sort a collection of plots by world (with a priority world), then * Sort a collection of plots by world (with a priority world), then
* by hashcode. * by hashcode.
@ -764,7 +727,7 @@ import java.util.zip.ZipInputStream;
} }
} else { } else {
for (PlotArea area : plotAreaManager.getAllPlotAreas()) { for (PlotArea area : plotAreaManager.getAllPlotAreas()) {
map.put(area, new ArrayList<Plot>(0)); map.put(area, new ArrayList<>(0));
} }
Collection<Plot> lastList = null; Collection<Plot> lastList = null;
PlotArea lastWorld = null; PlotArea lastWorld = null;
@ -779,17 +742,15 @@ import java.util.zip.ZipInputStream;
} }
} }
List<PlotArea> areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); List<PlotArea> areas = Arrays.asList(plotAreaManager.getAllPlotAreas());
Collections.sort(areas, new Comparator<PlotArea>() { areas.sort((a, b) -> {
@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; } else if (b.equals(priorityArea)) {
} else if (b.equals(priorityArea)) { return 1;
return 1;
}
} }
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) {
@ -868,11 +829,8 @@ 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 = this.plots_tmp.get(world); HashMap<PlotId, Plot> map =
if (map == null) { this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>());
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()) {
@ -1025,11 +983,8 @@ import java.util.zip.ZipInputStream;
} }
public boolean hasPlot(final UUID uuid) { public boolean hasPlot(final UUID uuid) {
for (final PlotArea area : plotAreaManager.getAllPlotAreas()) { return Arrays.stream(plotAreaManager.getAllPlotAreas())
if (area.hasPlot(uuid)) .anyMatch(area -> area.hasPlot(uuid));
return true;
}
return false;
} }
public Set<Plot> getBasePlots(final UUID uuid) { public Set<Plot> getBasePlots(final UUID uuid) {
@ -1918,11 +1873,8 @@ import java.util.zip.ZipInputStream;
} }
public int getPlotCount() { public int getPlotCount() {
int count = 0; return Arrays.stream(this.plotAreaManager.getAllPlotAreas()).mapToInt(PlotArea::getPlotCount)
for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { .sum();
count += area.getPlotCount();
}
return count;
} }
public Set<PlotArea> getPlotAreas() { public Set<PlotArea> getPlotAreas() {

View File

@ -15,6 +15,8 @@ import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@CommandDeclaration(command = "set", description = "Set a plot value", aliases = {"s"}, @CommandDeclaration(command = "set", description = "Set a plot value", aliases = {"s"},
usage = "/plot set <biome|alias|home|flag> <value...>", permission = "plots.set", usage = "/plot set <biome|alias|home|flag> <value...>", permission = "plots.set",
@ -100,11 +102,7 @@ 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(new Runnable() { GlobalBlockQueue.IMP.addTask(plot::removeRunning);
@Override public void run() {
plot.removeRunning();
}
});
return true; return true;
} }
} }
@ -114,8 +112,8 @@ import java.util.HashSet;
} }
public boolean noArgs(PlotPlayer player) { public boolean noArgs(PlotPlayer player) {
ArrayList<String> newValues = new ArrayList<>(); ArrayList<String> newValues =
newValues.addAll(Arrays.asList("biome", "alias", "home", "flag")); new ArrayList<>(Arrays.asList("biome", "alias", "home", "flag"));
Plot plot = player.getCurrentPlot(); Plot plot = player.getCurrentPlot();
if (plot != null) { if (plot != null) {
newValues.addAll( newValues.addAll(
@ -153,13 +151,12 @@ import java.util.HashSet;
// flag // flag
Flag<?> flag = FlagManager.getFlag(args[0].toLowerCase()); Flag<?> flag = FlagManager.getFlag(args[0].toLowerCase());
if (Flags.getFlags().contains(flag)) { if (Flags.getFlags().contains(flag)) {
StringBuilder a = new StringBuilder(); String a = "";
if (args.length > 1) { if (args.length > 1) {
for (int x = 1; x < args.length; x++) { a = IntStream.range(1, args.length).mapToObj(x -> " " + args[x])
a.append(" ").append(args[x]); .collect(Collectors.joining());
}
} }
MainCommand.onCommand(player, ("flag set " + args[0] + a.toString()).split(" ")); MainCommand.onCommand(player, ("flag set " + args[0] + a).split(" "));
return true; return true;
} }
return noArgs(player); return noArgs(player);

View File

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

View File

@ -97,28 +97,26 @@ public class ExpireManager {
Iterator<Plot> iter = plotsToDelete.iterator(); Iterator<Plot> iter = plotsToDelete.iterator();
final Plot current = iter.next(); final Plot current = iter.next();
if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) { if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> {
@Override public void run() { pp.setMeta("ignoreExpireTask", true);
pp.setMeta("ignoreExpireTask", true); pp.teleport(current.getCenter());
pp.teleport(current.getCenter()); pp.deleteMeta("ignoreExpireTask");
pp.deleteMeta("ignoreExpireTask"); PlotMessage msg = new PlotMessage().text(
PlotMessage msg = new PlotMessage().text( num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ")
num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ") .color("$1").text(current.toString()).color("$2")
.color("$1").text(current.toString()).color("$2") .suggest("/plot list expired").tooltip("/plot list expired")
.suggest("/plot list expired").tooltip("/plot list expired") //.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired")
//.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired") .text("\n - ").color("$3").text("Delete this (/plot delete)")
.text("\n - ").color("$3").text("Delete this (/plot delete)") .color("$2").suggest("/plot delete").tooltip("/plot delete")
.color("$2").suggest("/plot delete").tooltip("/plot delete") .text("\n - ").color("$3").text("Remind later (/plot set keep 1d)")
.text("\n - ").color("$3").text("Remind later (/plot set keep 1d)") .color("$2").suggest("/plot set keep 1d")
.color("$2").suggest("/plot set keep 1d") .tooltip("/plot set keep 1d").text("\n - ").color("$3")
.tooltip("/plot set keep 1d").text("\n - ").color("$3") .text("Keep this (/plot set keep true)").color("$2")
.text("Keep this (/plot set keep true)").color("$2") .suggest("/plot set keep true").tooltip("/plot set keep true")
.suggest("/plot set keep true").tooltip("/plot set keep true") .text("\n - ").color("$3").text("Don't show me this").color("$2")
.text("\n - ").color("$3").text("Don't show me this").color("$2") .suggest("/plot toggle clear-confirmation")
.suggest("/plot toggle clear-confirmation") .tooltip("/plot toggle clear-confirmation");
.tooltip("/plot toggle clear-confirmation"); msg.send(pp);
msg.send(pp);
}
}); });
return; return;
} else { } else {
@ -219,12 +217,7 @@ public class ExpireManager {
public ArrayDeque<ExpiryTask> getTasks(PlotArea area) { public ArrayDeque<ExpiryTask> getTasks(PlotArea area) {
ArrayDeque<ExpiryTask> queue = new ArrayDeque<>(tasks); ArrayDeque<ExpiryTask> queue = new ArrayDeque<>(tasks);
Iterator<ExpiryTask> iter = queue.iterator(); queue.removeIf(expiryTask -> !expiryTask.applies(area));
while (iter.hasNext()) {
if (!iter.next().applies(area)) {
iter.remove();
}
}
return queue; return queue;
} }
@ -254,7 +247,7 @@ public class ExpireManager {
} }
this.running = 2; this.running = 2;
final ConcurrentLinkedDeque<Plot> plots = final ConcurrentLinkedDeque<Plot> plots =
new ConcurrentLinkedDeque<Plot>(PlotSquared.get().getPlots()); new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots());
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override public void run() { @Override public void run() {
final Runnable task = this; final Runnable task = this;
@ -278,11 +271,7 @@ public class ExpireManager {
} }
for (ExpiryTask expiryTask : expired) { for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) { if (!expiryTask.needsAnalysis()) {
expiredTask.run(newPlot, new Runnable() { expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1), expiryTask.requiresConfirmation());
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, expiryTask.requiresConfirmation());
return; return;
} }
} }
@ -291,26 +280,18 @@ public class ExpireManager {
@Override public void run(final PlotAnalysis changed) { @Override public void run(final PlotAnalysis changed) {
passesComplexity(changed, expired, new RunnableVal<Boolean>() { passesComplexity(changed, expired, new RunnableVal<Boolean>() {
@Override public void run(Boolean confirmation) { @Override public void run(Boolean confirmation) {
expiredTask.run(newPlot, new Runnable() { expiredTask.run(newPlot,
@Override public void run() { () -> TaskManager.IMP.taskLaterAsync(task, 1), confirmation);
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, confirmation);
}
}, new Runnable() {
@Override public void run() {
FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20);
} }
}, () -> {
FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20);
}); });
} }
}; };
final Runnable doAnalysis = new Runnable() { final Runnable doAnalysis =
@Override public void run() { () -> HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
}
};
PlotAnalysis analysis = newPlot.getComplexity(null); PlotAnalysis analysis = newPlot.getComplexity(null);
if (analysis != null) { if (analysis != null) {
@ -318,11 +299,7 @@ public class ExpireManager {
@Override public void run(Boolean value) { @Override public void run(Boolean value) {
doAnalysis.run(); doAnalysis.run();
} }
}, new Runnable() { }, () -> TaskManager.IMP.taskLaterAsync(task, 1));
@Override public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
});
} else { } else {
doAnalysis.run(); doAnalysis.run();
} }
@ -330,12 +307,10 @@ public class ExpireManager {
} }
if (plots.isEmpty()) { if (plots.isEmpty()) {
ExpireManager.this.running = 3; ExpireManager.this.running = 3;
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(() -> {
@Override public void run() { if (ExpireManager.this.running == 3) {
if (ExpireManager.this.running == 3) { ExpireManager.this.running = 2;
ExpireManager.this.running = 2; runTask(expiredTask);
runTask(expiredTask);
}
} }
}, 86400000); }, 86400000);
} else { } else {
@ -363,7 +338,7 @@ public class ExpireManager {
} }
public HashSet<Plot> getPendingExpired() { public HashSet<Plot> getPendingExpired() {
return plotsToDelete == null ? new HashSet<Plot>() : plotsToDelete; return plotsToDelete == null ? new HashSet<>() : plotsToDelete;
} }
public void deleteWithMessage(Plot plot, Runnable whenDone) { public void deleteWithMessage(Plot plot, Runnable whenDone) {