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,11 +71,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try {
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
HashBiMap.create(new HashMap<>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
@ -102,8 +101,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
FileUUIDHandler fileHandler =
new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override public void run() {
fileHandler.startCaching(() -> {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
@ -113,22 +111,16 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
return;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
while (!toFetch.isEmpty()) {
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();
HttpURLConnection connection =
(HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid
.toString().replace("-", ""))
.openConnection();
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
HttpURLConnection connection = (HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid.toString()
.replace("-", "")).openConnection();
try (InputStream con = connection.getInputStream()) {
InputStreamReader reader = new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
@ -154,14 +146,11 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
whenDone.run();
}
return;
}
});
}
});
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
}
@ -172,8 +161,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (ifFetch == null) {
return;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
@ -191,7 +179,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
String name1 = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
@ -199,7 +187,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
TaskManager.runTask(ifFetch);
}
});
}
@ -215,8 +202,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
@ -227,7 +213,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} catch (SQLException e) {
e.printStackTrace();
}
}
});
return true;
}
@ -239,8 +224,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
*/
@Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
@ -251,7 +235,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}

View File

@ -214,11 +214,8 @@ import java.util.zip.ZipInputStream;
}
// Economy
if (Settings.Enabled_Components.ECONOMY) {
TaskManager.runTask(new Runnable() {
@Override public void run() {
EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler();
}
});
TaskManager.runTask(
() -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler());
}
/* // Check for updates
@ -247,8 +244,7 @@ import java.util.zip.ZipInputStream;
this.IMP.setGenerator(world);
}
}
TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
TaskManager.runTaskLater(() -> {
for (String world : section.getKeys(false)) {
if (world.equals("CheckingPlotSquaredGenerator")) {
continue;
@ -263,7 +259,6 @@ import java.util.zip.ZipInputStream;
PlotSquared.this.IMP.setGenerator(world);
}
}
}
}, 1);
}
@ -342,11 +337,9 @@ import java.util.zip.ZipInputStream;
}
private void startUuidCatching() {
TaskManager.runTaskLater(new Runnable() {
@Override public void run() {
TaskManager.runTaskLater(() -> {
debug("Starting UUID caching");
UUIDHandler.startCaching(new Runnable() {
@Override public void run() {
UUIDHandler.startCaching(() -> {
UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE);
foreachPlotRaw(new RunnableVal<Plot>() {
@Override public void run(Plot plot) {
@ -358,9 +351,7 @@ import java.util.zip.ZipInputStream;
}
});
startExpiryTasks();
}
});
}
}, 20);
}
@ -495,11 +486,8 @@ import java.util.zip.ZipInputStream;
if (this.plots_tmp == null) {
this.plots_tmp = new HashMap<>();
}
HashMap<PlotId, Plot> map = this.plots_tmp.get(area.toString());
if (map == null) {
map = new HashMap<>();
this.plots_tmp.put(area.toString(), map);
}
HashMap<PlotId, Plot> map =
this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>());
for (Plot plot : area.getPlots()) {
map.put(plot.getId(), plot);
}
@ -567,11 +555,7 @@ import java.util.zip.ZipInputStream;
result.add(plot);
}
}
Collections.sort(overflow, new Comparator<Plot>() {
@Override public int compare(Plot a, Plot b) {
return a.hashCode() - b.hashCode();
}
});
overflow.sort(Comparator.comparingInt(Plot::hashCode));
result.addAll(overflow);
return result;
}
@ -581,12 +565,8 @@ import java.util.zip.ZipInputStream;
*
* @param plots the collection of plots to sort
* @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
@Deprecated public ArrayList<Plot> sortPlotsByHash(Collection<Plot> plots) {
private ArrayList<Plot> sortPlotsByHash(Collection<Plot> plots) {
int hardmax = 256000;
int max = 0;
int overflowSize = 0;
@ -618,7 +598,7 @@ import java.util.zip.ZipInputStream;
overflow.add(plot);
}
}
Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]);
Plot[] overflowArray = overflow.toArray(new Plot[0]);
sortPlotsByHash(overflowArray);
ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length);
for (Plot plot : cache) {
@ -627,9 +607,7 @@ import java.util.zip.ZipInputStream;
}
}
Collections.addAll(result, overflowArray);
for (Plot plot : extra) {
result.add(plot);
}
result.addAll(extra);
return result;
}
@ -638,8 +616,7 @@ import java.util.zip.ZipInputStream;
*
* @param input an array of plots to sort
*/
// TODO: Re-evaluate deprecation of this, as it's being used internally
@Deprecated public void sortPlotsByHash(Plot[] input) {
private void sortPlotsByHash(Plot[] input) {
List<Plot>[] bucket = new ArrayList[32];
for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<>();
@ -648,26 +625,25 @@ import java.util.zip.ZipInputStream;
int placement = 1;
while (!maxLength) {
maxLength = true;
for (Plot i : input) {
int tmp = MathMan.getPositiveId(i.hashCode()) / placement;
bucket[tmp & 31].add(i);
for (Plot plot : input) {
int tmp = MathMan.getPositiveId(plot.hashCode()) / placement;
bucket[tmp & 31].add(plot);
if (maxLength && tmp > 0) {
maxLength = false;
}
}
int a = 0;
for (int b = 0; b < 32; b++) {
for (Plot i : bucket[b]) {
input[a++] = i;
for (int i = 0; i < 32; i++) {
for (Plot plot : bucket[i]) {
input[a++] = plot;
}
bucket[b].clear();
bucket[i].clear();
}
placement *= 32;
}
}
// TODO: Re-evaluate deprecation of this, as it's being used internally
@Deprecated public ArrayList<Plot> sortPlotsByTimestamp(Collection<Plot> plots) {
private ArrayList<Plot> sortPlotsByTimestamp(Collection<Plot> plots) {
int hardMax = 256000;
int max = 0;
int overflowSize = 0;
@ -699,7 +675,7 @@ import java.util.zip.ZipInputStream;
overflow.add(plot);
}
}
Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]);
Plot[] overflowArray = overflow.toArray(new Plot[0]);
sortPlotsByHash(overflowArray);
ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length);
for (Plot plot : cache) {
@ -708,9 +684,7 @@ import java.util.zip.ZipInputStream;
}
}
Collections.addAll(result, overflowArray);
for (Plot plot : extra) {
result.add(plot);
}
result.addAll(extra);
return result;
}
@ -719,29 +693,18 @@ import java.util.zip.ZipInputStream;
*
* @param input
* @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
@Deprecated public List<Plot> sortPlotsByModified(Collection<Plot> input) {
private List<Plot> sortPlotsByModified(Collection<Plot> input) {
List<Plot> list;
if (input instanceof List) {
list = (List<Plot>) input;
} else {
list = new ArrayList<>(input);
}
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));
}
});
list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.owner)));
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
* by hashcode.
@ -764,7 +727,7 @@ import java.util.zip.ZipInputStream;
}
} else {
for (PlotArea area : plotAreaManager.getAllPlotAreas()) {
map.put(area, new ArrayList<Plot>(0));
map.put(area, new ArrayList<>(0));
}
Collection<Plot> lastList = null;
PlotArea lastWorld = null;
@ -779,8 +742,7 @@ import java.util.zip.ZipInputStream;
}
}
List<PlotArea> areas = Arrays.asList(plotAreaManager.getAllPlotAreas());
Collections.sort(areas, new Comparator<PlotArea>() {
@Override public int compare(PlotArea a, PlotArea b) {
areas.sort((a, b) -> {
if (priorityArea != null) {
if (a.equals(priorityArea)) {
return -1;
@ -789,7 +751,6 @@ import java.util.zip.ZipInputStream;
}
}
return a.hashCode() - b.hashCode();
}
});
ArrayList<Plot> toReturn = new ArrayList<>(plots.size());
for (PlotArea area : areas) {
@ -868,11 +829,8 @@ import java.util.zip.ZipInputStream;
String world = entry.getKey();
PlotArea area = getPlotArea(world, null);
if (area == null) {
HashMap<PlotId, Plot> map = this.plots_tmp.get(world);
if (map == null) {
map = new HashMap<>();
this.plots_tmp.put(world, map);
}
HashMap<PlotId, Plot> map =
this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>());
map.putAll(entry.getValue());
} else {
for (Plot plot : entry.getValue().values()) {
@ -1025,11 +983,8 @@ import java.util.zip.ZipInputStream;
}
public boolean hasPlot(final UUID uuid) {
for (final PlotArea area : plotAreaManager.getAllPlotAreas()) {
if (area.hasPlot(uuid))
return true;
}
return false;
return Arrays.stream(plotAreaManager.getAllPlotAreas())
.anyMatch(area -> area.hasPlot(uuid));
}
public Set<Plot> getBasePlots(final UUID uuid) {
@ -1918,11 +1873,8 @@ import java.util.zip.ZipInputStream;
}
public int getPlotCount() {
int count = 0;
for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) {
count += area.getPlotCount();
}
return count;
return Arrays.stream(this.plotAreaManager.getAllPlotAreas()).mapToInt(PlotArea::getPlotCount)
.sum();
}
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.Arrays;
import java.util.HashSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@CommandDeclaration(command = "set", description = "Set a plot value", aliases = {"s"},
usage = "/plot set <biome|alias|home|flag> <value...>", permission = "plots.set",
@ -100,11 +102,7 @@ import java.util.HashSet;
current.setComponent(component, bucket);
}
MainUtil.sendMessage(player, C.GENERATING_COMPONENT);
GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override public void run() {
plot.removeRunning();
}
});
GlobalBlockQueue.IMP.addTask(plot::removeRunning);
return true;
}
}
@ -114,8 +112,8 @@ import java.util.HashSet;
}
public boolean noArgs(PlotPlayer player) {
ArrayList<String> newValues = new ArrayList<>();
newValues.addAll(Arrays.asList("biome", "alias", "home", "flag"));
ArrayList<String> newValues =
new ArrayList<>(Arrays.asList("biome", "alias", "home", "flag"));
Plot plot = player.getCurrentPlot();
if (plot != null) {
newValues.addAll(
@ -153,13 +151,12 @@ import java.util.HashSet;
// flag
Flag<?> flag = FlagManager.getFlag(args[0].toLowerCase());
if (Flags.getFlags().contains(flag)) {
StringBuilder a = new StringBuilder();
String a = "";
if (args.length > 1) {
for (int x = 1; x < args.length; x++) {
a.append(" ").append(args[x]);
a = IntStream.range(1, args.length).mapToObj(x -> " " + 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 noArgs(player);

View File

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

View File

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