Apply correct codestyle

This commit is contained in:
dordsor21
2019-02-04 13:59:11 +00:00
parent 9c90928d07
commit 51afbdfcdc
335 changed files with 58791 additions and 10363 deletions

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.configuration;
import java.util.Map;
import javax.annotation.Nonnull;
import java.util.Map;
/**
* Represents a source of configurable options and settings.

View File

@ -1,9 +1,9 @@
package com.github.intellectualsites.plotsquared.configuration;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
/**
* Represents a section of a {@link Configuration}.

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.configuration;
import java.util.Map;
import javax.annotation.Nonnull;
import java.util.Map;
/**
* This is a {@link Configuration} implementation that does not save or load

View File

@ -4,9 +4,9 @@ import com.github.intellectualsites.plotsquared.configuration.Configuration;
import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException;
import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration;
import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nonnull;
/**
* This is a base class for all File based implementations of {@link

View File

@ -77,7 +77,7 @@ public interface IPlotMain extends ILogger {
* @return
*/
default String getPluginName() {
return "PlotSquared";
return "PlotSquared";
}
/**

View File

@ -243,8 +243,7 @@ public class Auto extends SubCommand {
plot.claim(player, teleport, null);
}
}
if (!plotarea
.mergePlots(MainUtil.getPlotSelectionIds(start, end), true)) {
if (!plotarea.mergePlots(MainUtil.getPlotSelectionIds(start, end), true)) {
return false;
}
break;

View File

@ -244,8 +244,7 @@ import java.util.UUID;
MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, intersect.getName());
return false;
}
Set<Plot> existing =
area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2());
Set<Plot> existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2());
Set<Plot> newPlots = area.getPlotSelectionOwned(pos1, pos2);
// Set<Plot> removed = (HashSet<Plot>) existing.clone();
Set<Plot> removed = new HashSet<>(existing);

View File

@ -25,163 +25,160 @@ import java.util.Map.Entry;
@CommandDeclaration(command = "database", aliases = {"convert"},
category = CommandCategory.ADMINISTRATION, permission = "plots.database",
description = "Convert/Backup Storage", requiredType = RequiredType.CONSOLE,
usage = "/plot database [area] <sqlite|mysql|import>")
public class Database
usage = "/plot database [area] <sqlite|mysql|import>") public class Database
extends SubCommand {
public static void insertPlots(final SQLManager manager, final List<Plot> plots,
final PlotPlayer player) {
TaskManager.runTaskAsync(() -> {
try {
ArrayList<Plot> ps = new ArrayList<>(plots);
MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, () -> {
MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close();
});
} catch (Exception e) {
MainUtil.sendMessage(player,
"Failed to insert plot objects, see stacktrace for info");
e.printStackTrace();
}
});
}
@Override
public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [area] <sqlite|mysql|import>");
return false;
}
List<Plot> plots;
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
if (area != null) {
plots = PlotSquared.get().sortPlotsByTemp(area.getPlots());
args = Arrays.copyOfRange(args, 1, args.length);
} else {
plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getPlots());
}
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [world] <sqlite|mysql|import>");
MainUtil.sendMessage(player, "[arg] indicates an optional argument");
return false;
}
try {
com.github.intellectualsites.plotsquared.plot.database.Database implementation;
String prefix = "";
switch (args[0].toLowerCase()) {
case "import":
if (args.length < 2) {
MainUtil
.sendMessage(player, "/plot database import <sqlite file> [prefix]");
return false;
}
File file = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
args[1].endsWith(".db") ? args[1] : args[1] + ".db");
if (!file.exists()) {
MainUtil.sendMessage(player, "&6Database does not exist: " + file);
return false;
}
MainUtil.sendMessage(player, "&6Starting...");
implementation = new SQLite(file);
SQLManager manager =
new SQLManager(implementation, args.length == 3 ? args[2] : "", true);
HashMap<String, HashMap<PlotId, Plot>> map = manager.getPlots();
plots = new ArrayList<>();
for (Entry<String, HashMap<PlotId, Plot>> entry : map.entrySet()) {
String areaname = entry.getKey();
PlotArea pa = PlotSquared.get().getPlotAreaByString(areaname);
if (pa != null) {
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
Plot plot = entry2.getValue();
if (pa.getOwnedPlotAbs(plot.getId()) != null) {
if (pa instanceof SinglePlotArea) {
Plot newPlot = pa.getNextFreePlot(null, plot.getId());
if (newPlot != null) {
PlotId newId = newPlot.getId();
PlotId id = plot.getId();
File worldFile =
new File(PlotSquared.imp().getWorldContainer(),
id.toCommaSeparatedString());
if (worldFile.exists()) {
File newFile =
new File(PlotSquared.imp().getWorldContainer(),
newId.toCommaSeparatedString());
worldFile.renameTo(newFile);
}
id.x = newId.x;
id.y = newId.y;
id.recalculateHash();
plot.setArea(pa);
plots.add(plot);
continue;
}
}
MainUtil.sendMessage(player,
"Skipping duplicate plot: " + plot + " | id=" + plot.temp);
continue;
}
plot.setArea(pa);
plots.add(plot);
}
} else {
HashMap<PlotId, Plot> plotmap =
PlotSquared.get().plots_tmp
.computeIfAbsent(areaname, k -> new HashMap<>());
plotmap.putAll(entry.getValue());
public static void insertPlots(final SQLManager manager, final List<Plot> plots,
final PlotPlayer player) {
TaskManager.runTaskAsync(() -> {
try {
ArrayList<Plot> ps = new ArrayList<>(plots);
MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, () -> {
MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close();
});
} catch (Exception e) {
MainUtil
.sendMessage(player, "Failed to insert plot objects, see stacktrace for info");
e.printStackTrace();
}
}
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&6Database conversion finished!"));
return true;
case "mysql":
if (args.length < 6) {
return MainUtil.sendMessage(player,
"/plot database mysql [host] [port] [username] [password] [database] {prefix}");
}
String host = args[1];
String port = args[2];
String username = args[3];
String password = args[4];
String database = args[5];
if (args.length > 6) {
prefix = args[6];
}
implementation = new MySQL(host, port, database, username, password);
break;
case "sqlite":
if (args.length < 2) {
return MainUtil.sendMessage(player, "/plot database sqlite [file]");
}
File sqliteFile =
MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), args[1] + ".db");
implementation = new SQLite(sqliteFile);
break;
default:
return MainUtil.sendMessage(player, "/plot database [sqlite/mysql]");
}
try {
SQLManager manager = new SQLManager(implementation, prefix, true);
Database.insertPlots(manager, plots, player);
return true;
} catch (ClassNotFoundException | SQLException e) {
MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info");
MainUtil.sendMessage(player,
"&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
MainUtil.sendMessage(player, "&d==== End of stacktrace ====");
MainUtil
.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
}
} catch (ClassNotFoundException | SQLException e) {
MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info");
MainUtil.sendMessage(player,
"&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
MainUtil.sendMessage(player, "&d==== End of stacktrace ====");
MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
});
}
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [area] <sqlite|mysql|import>");
return false;
}
List<Plot> plots;
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
if (area != null) {
plots = PlotSquared.get().sortPlotsByTemp(area.getPlots());
args = Arrays.copyOfRange(args, 1, args.length);
} else {
plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getPlots());
}
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [world] <sqlite|mysql|import>");
MainUtil.sendMessage(player, "[arg] indicates an optional argument");
return false;
}
try {
com.github.intellectualsites.plotsquared.plot.database.Database implementation;
String prefix = "";
switch (args[0].toLowerCase()) {
case "import":
if (args.length < 2) {
MainUtil
.sendMessage(player, "/plot database import <sqlite file> [prefix]");
return false;
}
File file = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
args[1].endsWith(".db") ? args[1] : args[1] + ".db");
if (!file.exists()) {
MainUtil.sendMessage(player, "&6Database does not exist: " + file);
return false;
}
MainUtil.sendMessage(player, "&6Starting...");
implementation = new SQLite(file);
SQLManager manager =
new SQLManager(implementation, args.length == 3 ? args[2] : "", true);
HashMap<String, HashMap<PlotId, Plot>> map = manager.getPlots();
plots = new ArrayList<>();
for (Entry<String, HashMap<PlotId, Plot>> entry : map.entrySet()) {
String areaname = entry.getKey();
PlotArea pa = PlotSquared.get().getPlotAreaByString(areaname);
if (pa != null) {
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
Plot plot = entry2.getValue();
if (pa.getOwnedPlotAbs(plot.getId()) != null) {
if (pa instanceof SinglePlotArea) {
Plot newPlot = pa.getNextFreePlot(null, plot.getId());
if (newPlot != null) {
PlotId newId = newPlot.getId();
PlotId id = plot.getId();
File worldFile =
new File(PlotSquared.imp().getWorldContainer(),
id.toCommaSeparatedString());
if (worldFile.exists()) {
File newFile =
new File(PlotSquared.imp().getWorldContainer(),
newId.toCommaSeparatedString());
worldFile.renameTo(newFile);
}
id.x = newId.x;
id.y = newId.y;
id.recalculateHash();
plot.setArea(pa);
plots.add(plot);
continue;
}
}
MainUtil.sendMessage(player,
"Skipping duplicate plot: " + plot + " | id=" + plot.temp);
continue;
}
plot.setArea(pa);
plots.add(plot);
}
} else {
HashMap<PlotId, Plot> plotmap = PlotSquared.get().plots_tmp
.computeIfAbsent(areaname, k -> new HashMap<>());
plotmap.putAll(entry.getValue());
}
}
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&6Database conversion finished!"));
return true;
case "mysql":
if (args.length < 6) {
return MainUtil.sendMessage(player,
"/plot database mysql [host] [port] [username] [password] [database] {prefix}");
}
String host = args[1];
String port = args[2];
String username = args[3];
String password = args[4];
String database = args[5];
if (args.length > 6) {
prefix = args[6];
}
implementation = new MySQL(host, port, database, username, password);
break;
case "sqlite":
if (args.length < 2) {
return MainUtil.sendMessage(player, "/plot database sqlite [file]");
}
File sqliteFile =
MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), args[1] + ".db");
implementation = new SQLite(sqliteFile);
break;
default:
return MainUtil.sendMessage(player, "/plot database [sqlite/mysql]");
}
try {
SQLManager manager = new SQLManager(implementation, prefix, true);
Database.insertPlots(manager, plots, player);
return true;
} catch (ClassNotFoundException | SQLException e) {
MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info");
MainUtil.sendMessage(player,
"&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
MainUtil.sendMessage(player, "&d==== End of stacktrace ====");
MainUtil
.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
}
} catch (ClassNotFoundException | SQLException e) {
MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info");
MainUtil.sendMessage(player,
"&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
MainUtil.sendMessage(player, "&d==== End of stacktrace ====");
MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
}
}
}
}

View File

@ -164,8 +164,8 @@ import java.util.*;
"$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100");
return false;
}
PlotAnalysis.calcOptimalModifiers(
() -> MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold);
PlotAnalysis.calcOptimalModifiers(() -> MainUtil
.sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold);
return true;
case "stop-expire":
if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) {
@ -409,8 +409,8 @@ import java.util.*;
} catch (ScriptException e) {
e.printStackTrace();
}
PlotSquared.log(
"> " + (System.currentTimeMillis() - start) + "ms -> " + result);
PlotSquared
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
});
} else {
long start = System.currentTimeMillis();

View File

@ -26,6 +26,21 @@ import java.util.List;
permission = "plots.debugpaste", category = CommandCategory.DEBUG) public class DebugPaste
extends SubCommand {
private static String readFile(@NonNull final File file) throws IOException {
final StringBuilder content = new StringBuilder();
final List<String> lines = new ArrayList<>();
try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) {
content.append(lines.get(i)).append("\n");
}
return content.toString();
}
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
TaskManager.runTaskAsync(() -> {
try {
@ -36,7 +51,8 @@ import java.util.List;
"# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your "
+ "problem\n\n");
b.append("# Server Information\n");
b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation()).append("\n");
b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation())
.append("\n");
b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';')
.append(!Settings.UUID.OFFLINE).append('\n');
b.append("plugins:");
@ -55,14 +71,12 @@ import java.util.List;
b.append("memory.max: ").append(runtime.maxMemory()).append('\n');
b.append("java.specification.version: '")
.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"))
.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.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(
"\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues");
@ -71,24 +85,27 @@ import java.util.List;
incendoPaster.addFile(new IncendoPaster.PasteFile("information", b.toString()));
try {
final File logFile = new File(PlotSquared.get().IMP.getDirectory(),
"../../logs/latest.log");
final File logFile =
new File(PlotSquared.get().IMP.getDirectory(), "../../logs/latest.log");
if (Files.size(logFile.toPath()) > 14_000_000) {
throw new IOException("Too big...");
}
incendoPaster.addFile(new IncendoPaster.PasteFile("latest.log", readFile(logFile)));
incendoPaster
.addFile(new IncendoPaster.PasteFile("latest.log", readFile(logFile)));
} catch (IOException ignored) {
MainUtil.sendMessage(player,
"&clatest.log is too big to be pasted, will ignore");
MainUtil
.sendMessage(player, "&clatest.log is too big to be pasted, will ignore");
}
try {
incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml", readFile(PlotSquared.get().configFile)));
incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml",
readFile(PlotSquared.get().configFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping settings.yml because it's empty");
}
try {
incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml", readFile(PlotSquared.get().worldsFile)));
incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml",
readFile(PlotSquared.get().worldsFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping worlds.yml because it's empty");
}
@ -96,25 +113,29 @@ import java.util.List;
incendoPaster.addFile(new IncendoPaster.PasteFile("PlotSquared.use_THIS.yml",
readFile(PlotSquared.get().translationFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping PlotSquared.use_THIS.yml because it's empty");
MainUtil.sendMessage(player,
"&cSkipping PlotSquared.use_THIS.yml because it's empty");
}
try {
final String rawResponse = incendoPaster.upload();
final JsonObject jsonObject = new JsonParser().parse(rawResponse).getAsJsonObject();
final JsonObject jsonObject =
new JsonParser().parse(rawResponse).getAsJsonObject();
if (jsonObject.has("created")) {
final String pasteId = jsonObject.get("paste_id").getAsString();
final String link = String.format("https://incendo.org/paste/view/%s", pasteId);
player.sendMessage(
C.DEBUG_REPORT_CREATED.s().replace("%url%", link));
final String link =
String.format("https://incendo.org/paste/view/%s", pasteId);
player.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link));
} else {
final String responseMessage = jsonObject.get("response").getAsString();
MainUtil.sendMessage(player, String.format("&cFailed to create the debug paste: %s", responseMessage));
MainUtil.sendMessage(player, String
.format("&cFailed to create the debug paste: %s", responseMessage));
}
} catch (final Throwable throwable) {
throwable.printStackTrace();
MainUtil.sendMessage(player, "&cFailed to create the debug paste: " + throwable.getMessage());
MainUtil.sendMessage(player,
"&cFailed to create the debug paste: " + throwable.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
@ -122,19 +143,4 @@ import java.util.List;
});
return true;
}
private static String readFile(@NonNull final File file) throws IOException {
final StringBuilder content = new StringBuilder();
final List<String> lines = new ArrayList<>();
try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) {
content.append(lines.get(i)).append("\n");
}
return content.toString();
}
}

View File

@ -33,8 +33,9 @@ import java.util.*;
Settings.Limit.MAX_PLOTS;
final boolean result = player.hasPermissionRange(perm, checkRange) >= numeric;
if (!result) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), value.toLowerCase()));
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), value.toLowerCase()));
}
return result;
}
@ -45,12 +46,12 @@ import java.util.*;
final PlotBlockListFlag blockListFlag = (PlotBlockListFlag) flag;
final HashSet<PlotBlock> parsedBlocks = blockListFlag.parseValue(value);
for (final PlotBlock block : parsedBlocks) {
final String permission = C.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(),
block.getRawId().toString().toLowerCase());
final String permission = C.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), block.getRawId().toString().toLowerCase());
final boolean result = Permissions.hasPermission(player, permission);
if (!result) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), value.toLowerCase()));
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase()));
return false;
}
}
@ -58,8 +59,8 @@ import java.util.*;
}
final boolean result = Permissions.hasPermission(player, perm);
if (!result) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), value.toLowerCase()));
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase()));
}
return result;
}

View File

@ -96,7 +96,7 @@ public class Merge extends SubCommand {
if (args.length == 2) {
terrain = "true".equalsIgnoreCase(args[1]);
}
if(!terrain && !Permissions.hasPermission(player, C.PERMISSION_MERGE_KEEPROAD)) {
if (!terrain && !Permissions.hasPermission(player, C.PERMISSION_MERGE_KEEPROAD)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_MERGE_KEEPROAD.s());
return true;
}
@ -132,7 +132,7 @@ public class Merge extends SubCommand {
} else {
terrain = true;
}
if(!terrain && !Permissions.hasPermission(player, C.PERMISSION_MERGE_KEEPROAD)) {
if (!terrain && !Permissions.hasPermission(player, C.PERMISSION_MERGE_KEEPROAD)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_MERGE_KEEPROAD.s());
return true;
}

View File

@ -14,9 +14,10 @@ import java.util.Locale;
category = CommandCategory.APPEARANCE, requiredType = RequiredType.PLAYER) public class Music
extends SubCommand {
private static final Collection<String> DISCS = Arrays.asList("music_disc_13", "music_disc_cat",
"music_disc_blocks", "music_disc_chirp", "music_disc_far", "music_disc_mall", "music_disc_mellohi",
"music_disc_stal", "music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait");
private static final Collection<String> DISCS = Arrays
.asList("music_disc_13", "music_disc_cat", "music_disc_blocks", "music_disc_chirp",
"music_disc_far", "music_disc_mall", "music_disc_mellohi", "music_disc_stal",
"music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait");
@Override public boolean onCommand(PlotPlayer player, String[] args) {
Location loc = player.getLocation();

View File

@ -10,8 +10,10 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.*;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot",
usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO,

View File

@ -8,9 +8,9 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.*;
@CommandDeclaration(command = "unlink", aliases = {"u", "unmerge"},
description = "Unlink a mega-plot", usage = "/plot unlink [createroads]", requiredType = RequiredType.NONE,
category = CommandCategory.SETTINGS, confirmation = true) public class Unlink
extends SubCommand {
description = "Unlink a mega-plot", usage = "/plot unlink [createroads]",
requiredType = RequiredType.NONE, category = CommandCategory.SETTINGS, confirmation = true)
public class Unlink extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) {

View File

@ -80,8 +80,8 @@ public class Configuration {
WorldUtil.IMP.getClosestBlock(block);
if (value == null) {
throw new UnknownBlockException(block);
} else if (Settings.Enabled_Components.PREVENT_UNSAFE && !value.best.isAir() &&
!WorldUtil.IMP.isBlockSolid(value.best)) {
} else if (Settings.Enabled_Components.PREVENT_UNSAFE && !value.best.isAir()
&& !WorldUtil.IMP.isBlockSolid(value.best)) {
throw new UnsafeBlockException(value.best);
}
blockBucket.addBlock(value.best, chance);
@ -114,7 +114,8 @@ public class Configuration {
WorldUtil.IMP.getClosestBlock(block);
if (value == null || value.match > 1) {
return false;
} else if (Settings.Enabled_Components.PREVENT_UNSAFE && !value.best.isAir() && !WorldUtil.IMP.isBlockSolid(value.best)) {
} else if (Settings.Enabled_Components.PREVENT_UNSAFE && !value.best.isAir()
&& !WorldUtil.IMP.isBlockSolid(value.best)) {
throw new UnsafeBlockException(value.best);
}
}

View File

@ -221,13 +221,16 @@ public class Settings extends Config {
@Ignore public static boolean NATIVE_UUID_PROVIDER = false;
}
@Comment("General settings") public static final class General {
@Comment("Display scientific numbers (4.2E8)") public static boolean SCIENTIFIC = false;
}
@Comment("Schematic Settings") public static final class Schematics {
@Comment("Whether schematic based generation should paste schematic on top of plots, or from Y=1")
public static boolean PASTE_ON_TOP = true;
@Comment(
"Whether schematic based generation should paste schematic on top of plots, or from Y=1")
public static boolean PASTE_ON_TOP = true;
}
@ -276,6 +279,7 @@ public class Settings extends Config {
MAX_PLOTS = 127;
}
public static final class Confirmation {
@Comment("Teleport to your plot on death") public static int CONFIRMATION_TIMEOUT_SECONDS =
20;
@ -347,7 +351,7 @@ public class Settings extends Config {
@Comment("Actively purge invalid database entries") public static boolean DATABASE_PURGER =
false;
@Comment("Delete plots when a player is banned") public static boolean BAN_DELETER = false;
@Comment("Prevent possibly unsafe blocks from being used in plot components") public static
boolean PREVENT_UNSAFE = true;
@Comment("Prevent possibly unsafe blocks from being used in plot components")
public static boolean PREVENT_UNSAFE = true;
}
}

View File

@ -13,8 +13,7 @@ import java.util.*;
* Database Functions
* - These functions do not update the local plot objects and only make changes to the DB
*/
@SuppressWarnings("deprecation")
public class DBFunc {
@SuppressWarnings("deprecation") public class DBFunc {
/**
* The "global" uuid.
*/

View File

@ -2,7 +2,10 @@ package com.github.intellectualsites.plotsquared.plot.flag;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotSettings;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.google.common.collect.ImmutableSet;
@ -114,8 +117,7 @@ public class FlagManager {
* @param flag
* @return
*/
@SuppressWarnings("deprecation")
public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
@SuppressWarnings("deprecation") public static <V> V getPlotFlagRaw(Plot plot, Flag<V> flag) {
if (plot.owner == null) {
return null;
}

View File

@ -13,8 +13,7 @@ import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.util.Locale;
@SuppressWarnings("WeakerAccess")
public abstract class ClassicPlotWorld extends SquarePlotWorld {
@SuppressWarnings("WeakerAccess") public abstract class ClassicPlotWorld extends SquarePlotWorld {
public int ROAD_HEIGHT = 62;
public int PLOT_HEIGHT = 62;
@ -94,11 +93,12 @@ public abstract class ClassicPlotWorld extends SquarePlotWorld {
// Dump world settings
if (Settings.DEBUG) {
PlotSquared.debug(String.format("- Dumping settings for ClassicPlotWorld with name %s", this.worldname));
PlotSquared.debug(String
.format("- Dumping settings for ClassicPlotWorld with name %s", this.worldname));
final Field[] fields = this.getClass().getFields();
for (final Field field : fields) {
final String name = field.getName().toLowerCase(Locale.ENGLISH);
if(name.equalsIgnoreCase("g_sch")) {
if (name.equalsIgnoreCase("g_sch")) {
continue;
}
Object value;

View File

@ -58,8 +58,7 @@ public class HybridGen extends IndependentPlotGenerator {
if (blockBuckets[layer] == null) {
blockBuckets[layer] = new BlockBucket[4096];
}
blockBuckets[layer][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) | x] =
hpw.MAIN_BLOCK;
blockBuckets[layer][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK;
}
}
return blockBuckets;

View File

@ -36,7 +36,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
private Location SIGN_LOCATION;
public HybridPlotWorld(String worldName, String id, IndependentPlotGenerator generator,
PlotId min, PlotId max) {
PlotId min, PlotId max) {
super(worldName, id, generator, min, max);
}
@ -69,10 +69,10 @@ public class HybridPlotWorld extends ClassicPlotWorld {
if (direction != null) {
Vector3 vector = transform.apply(direction.toVector())
.subtract(transform.apply(Vector3.ZERO)).normalize();
.subtract(transform.apply(Vector3.ZERO)).normalize();
Direction newDirection = Direction.findClosest(vector,
Direction.Flag.CARDINAL | Direction.Flag.ORDINAL
| Direction.Flag.SECONDARY_ORDINAL);
Direction.Flag.CARDINAL | Direction.Flag.ORDINAL
| Direction.Flag.SECONDARY_ORDINAL);
if (newDirection != null) {
CompoundTagBuilder builder = tag.createBuilder();
@ -96,7 +96,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
} else {
bot.setY(0);
Location loc =
bot.add(SIGN_LOCATION.getX(), SIGN_LOCATION.getY(), SIGN_LOCATION.getZ());
bot.add(SIGN_LOCATION.getX(), SIGN_LOCATION.getY(), SIGN_LOCATION.getZ());
return loc;
}
}
@ -134,11 +134,11 @@ public class HybridPlotWorld extends ClassicPlotWorld {
public void setupSchematics() throws SchematicHandler.UnsupportedFormatException {
this.G_SCH = new HashMap<>();
File schematic1File = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
"schematics/GEN_ROAD_SCHEMATIC/" + this.worldname + "/sideroad.schematic");
"schematics/GEN_ROAD_SCHEMATIC/" + this.worldname + "/sideroad.schematic");
File schematic2File = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
"schematics/GEN_ROAD_SCHEMATIC/" + this.worldname + "/intersection.schematic");
"schematics/GEN_ROAD_SCHEMATIC/" + this.worldname + "/intersection.schematic");
File schem3File = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
"schematics/GEN_ROAD_SCHEMATIC/" + this.worldname + "/plot.schematic");
"schematics/GEN_ROAD_SCHEMATIC/" + this.worldname + "/plot.schematic");
Schematic schematic1 = SchematicHandler.manager.getSchematic(schematic1File);
Schematic schematic2 = SchematicHandler.manager.getSchematic(schematic2File);
Schematic schematic3 = SchematicHandler.manager.getSchematic(schem3File);
@ -177,8 +177,8 @@ public class HybridPlotWorld extends ClassicPlotWorld {
BaseBlock id = blockArrayClipboard3.getFullBlock(BlockVector3.at(x, y, z));
if (!id.getBlockType().getMaterial().isAir()) {
addOverlayBlock((short) (x + shift + oddshift + centerShiftX),
(short) (y + startY), (short) (z + shift + oddshift + centerShiftZ),
id, false, h3);
(short) (y + startY), (short) (z + shift + oddshift + centerShiftZ),
id, false, h3);
}
}
}
@ -241,9 +241,9 @@ public class HybridPlotWorld extends ClassicPlotWorld {
BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3.at(x, y, z));
if (!id.getBlockType().getMaterial().isAir()) {
addOverlayBlock((short) (x - shift), (short) (y + startY),
(short) (z + shift + oddshift), id, false, h1);
(short) (z + shift + oddshift), id, false, h1);
addOverlayBlock((short) (z + shift + oddshift), (short) (y + startY),
(short) (shift - x + (oddshift - 1)), id, true, h1);
(short) (shift - x + (oddshift - 1)), id, true, h1);
}
}
}
@ -254,7 +254,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3.at(x, y, z));
if (!id.getBlockType().getMaterial().isAir()) {
addOverlayBlock((short) (x - shift), (short) (y + startY),
(short) (z - shift), id, false, h2);
(short) (z - shift), id, false, h2);
}
}
}
@ -262,7 +262,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
}
public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate,
int height) {
int height) {
if (z < 0) {
z += this.SIZE;
} else if (z >= this.SIZE) {

View File

@ -167,8 +167,8 @@ public class PlotListener {
replacements.put("%greeting%", greeting);
replacements.put("%alias", plot.toString());
replacements.put("%s", MainUtil.getName(plot.owner));
String main = StringMan
.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements);
String main =
StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements);
String sub = StringMan
.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements);
AbstractTitle.sendTitle(player, main, sub);
@ -208,13 +208,12 @@ public class PlotListener {
}
}
Optional<String> farewell = plot.getFlag(Flags.FAREWELL);
farewell.ifPresent(s -> MainUtil.format(C.PREFIX_FAREWELL.s() + s, plot, player, false,
new RunnableVal<String>() {
@Override
public void run(String value) {
MainUtil.sendMessage(player, value);
}
}));
farewell.ifPresent(s -> MainUtil
.format(C.PREFIX_FAREWELL.s() + s, plot, player, false, new RunnableVal<String>() {
@Override public void run(String value) {
MainUtil.sendMessage(player, value);
}
}));
Optional<Boolean> leave = plot.getFlag(Flags.NOTIFY_LEAVE);
if (leave.isPresent() && leave.get()) {
if (!Permissions.hasPermission(player, "plots.flag.notify-enter.bypass")) {

View File

@ -10,16 +10,18 @@ import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
import com.sk89q.worldedit.world.block.*;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.HashSet;
public class WEExtent extends AbstractDelegateExtent {
private final HashSet<RegionWrapper> mask;
public static BlockState AIRSTATE = BlockTypes.AIR.getDefaultState();
public static BaseBlock AIRBASE = BlockTypes.AIR.getDefaultState().toBaseBlock();
private final HashSet<RegionWrapper> mask;
public WEExtent(HashSet<RegionWrapper> mask, Extent extent) {
super(extent);

View File

@ -4,9 +4,6 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType;
import java.util.HashSet;
import java.util.UUID;

View File

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

View File

@ -9,8 +9,7 @@ import javax.script.ScriptException;
public abstract class Expression<T> {
@Nonnull
public static <U> Expression<U> constant(final U value) {
@Nonnull public static <U> Expression<U> constant(final U value) {
return new Expression<U>() {
@Override public U evaluate(U arg) {
return value;

View File

@ -2,25 +2,21 @@ package com.github.intellectualsites.plotsquared.plot.object;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import lombok.Getter;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.UUID;
import javax.annotation.Nonnull;
import lombok.Getter;
public class PlotCluster {
public PlotArea area;
@Nonnull
@Getter
public PlotSettings settings;
@Nonnull @Getter public PlotSettings settings;
public UUID owner;
public HashSet<UUID> helpers = new HashSet<>();
public HashSet<UUID> invited = new HashSet<>();
public int temp;
@Nonnull
private PlotId pos1;
@Nonnull
private PlotId pos2;
@Nonnull private PlotId pos1;
@Nonnull private PlotId pos2;
private RegionWrapper region;
public PlotCluster(PlotArea area, @Nonnull PlotId pos1, @Nonnull PlotId pos2, UUID owner) {
@ -88,11 +84,14 @@ public class PlotCluster {
return this.settings.getAlias();
}
public void setName(String name) {
this.settings.setAlias(name);
}
public String getAlias() {
return this.settings.getAlias();
}
public void setName(String name) { this.settings.setAlias(name);}
/**
* Get the area (in plots).
*

View File

@ -7,6 +7,23 @@ import lombok.NonNull;
public class PlotInventory {
private static final String META_KEY = "inventory";
public final PlotPlayer player;
public final int size;
private final PlotItemStack[] items;
private String title;
private boolean open = false;
public PlotInventory(PlotPlayer player) {
this.size = 4;
this.title = null;
this.player = player;
this.items = InventoryUtil.manager.getItems(player);
}
public PlotInventory(PlotPlayer player, int size, String name) {
this.size = size;
this.title = name == null ? "" : name;
this.player = player;
this.items = new PlotItemStack[size * 9];
}
public static boolean hasPlotInventoryOpen(@NonNull final PlotPlayer plotPlayer) {
return getOpenPlotInventory(plotPlayer) != null;
@ -25,26 +42,6 @@ public class PlotInventory {
plotPlayer.deleteMeta(META_KEY);
}
public final PlotPlayer player;
public final int size;
private final PlotItemStack[] items;
private String title;
private boolean open = false;
public PlotInventory(PlotPlayer player) {
this.size = 4;
this.title = null;
this.player = player;
this.items = InventoryUtil.manager.getItems(player);
}
public PlotInventory(PlotPlayer player, int size, String name) {
this.size = size;
this.title = name == null ? "" : name;
this.player = player;
this.items = new PlotItemStack[size * 9];
}
public boolean onClick(int index) {
return true;
}

View File

@ -31,9 +31,11 @@ public class PlotLoc {
if (split.length == 2) {
return new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
} else if (split.length == 3) {
return new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
return new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1]),
Integer.parseInt(split[2]));
} else {
throw new IllegalArgumentException(String.format("Unable to deserialize: %s", input));
throw new IllegalArgumentException(
String.format("Unable to deserialize: %s", input));
}
} catch (NumberFormatException ignored) {
return null;

View File

@ -5,30 +5,26 @@ import java.io.OutputStream;
public class AbstractDelegateOutputStream extends OutputStream {
private final OutputStream parent;
private final OutputStream parent;
public AbstractDelegateOutputStream(OutputStream os) {
this.parent = os;
}
public AbstractDelegateOutputStream(OutputStream os) {
this.parent = os;
}
@Override
public void write(int b) throws IOException {
parent.write(b);
}
@Override public void write(int b) throws IOException {
parent.write(b);
}
@Override
public void write(byte[] b) throws IOException {
parent.write(b);
}
@Override
public void flush() throws IOException {
parent.flush();
}
@Override public void write(byte[] b) throws IOException {
parent.write(b);
}
@Override
public void close() throws IOException {
parent.close();
}
@Override public void flush() throws IOException {
parent.flush();
}
@Override public void close() throws IOException {
parent.close();
}
}

View File

@ -89,8 +89,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
localAreas.add(plotArea);
globalAreas.add(plotArea);
this.plotAreas = globalAreas.toArray(new PlotArea[0]);
this.plotAreaMap
.put(plotArea.worldname, localAreas.toArray(new PlotArea[0]));
this.plotAreaMap.put(plotArea.worldname, localAreas.toArray(new PlotArea[0]));
QuadMap<PlotArea> map = this.plotAreaGrid.get(plotArea.worldname);
if (map == null) {
map = new QuadMap<PlotArea>(Integer.MAX_VALUE, 0, 0) {
@ -111,8 +110,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
this.plotAreaMap.remove(area.worldname);
this.plotAreaGrid.remove(area.worldname);
} else {
this.plotAreaMap
.put(area.worldname, globalAreas.toArray(new PlotArea[0]));
this.plotAreaMap.put(area.worldname, globalAreas.toArray(new PlotArea[0]));
this.plotAreaGrid.get(area.worldname).remove(area);
}
}

View File

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

View File

@ -240,8 +240,8 @@ public abstract class ChunkManager {
TaskManager.runTaskAsync(() -> {
for (ChunkLoc loc : chunks) {
String directory =
world + File.separator + "region" + File.separator + "r." + loc.x + "."
+ loc.z + ".mca";
world + File.separator + "region" + File.separator + "r." + loc.x + "." + loc.z
+ ".mca";
File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)");
if (file.exists()) {

View File

@ -31,8 +31,7 @@ public class CommentManager {
if (value != null) {
int num = 0;
for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player,
inbox.toString())) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) {
num++;
}
}

View File

@ -1,8 +1,11 @@
package com.github.intellectualsites.plotsquared.plot.util;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.google.common.base.Charsets;
import java.io.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
@ -11,8 +14,7 @@ import java.util.*;
/**
* Single class paster for the Incendo paste service
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class IncendoPaster {
@SuppressWarnings({"unused", "WeakerAccess"}) public final class IncendoPaster {
/**
* Upload service URL
@ -21,9 +23,8 @@ public final class IncendoPaster {
/**
* Valid paste applications
*/
public static final Collection<String>
VALID_APPLICATIONS = Arrays
.asList("plotsquared", "fastasyncworldedit", "incendopermissions", "kvantum");
public static final Collection<String> VALID_APPLICATIONS =
Arrays.asList("plotsquared", "fastasyncworldedit", "incendopermissions", "kvantum");
private final Collection<PasteFile> files = new ArrayList<>();
private final String pasteApplication;
@ -38,7 +39,8 @@ public final class IncendoPaster {
throw new IllegalArgumentException("paste application cannot be null, nor empty");
}
if (!VALID_APPLICATIONS.contains(pasteApplication.toLowerCase(Locale.ENGLISH))) {
throw new IllegalArgumentException(String.format("Unknown application name: %s", pasteApplication));
throw new IllegalArgumentException(
String.format("Unknown application name: %s", pasteApplication));
}
this.pasteApplication = pasteApplication;
}
@ -64,8 +66,8 @@ public final class IncendoPaster {
// Check to see that no duplicate files are submitted
for (final PasteFile pasteFile : this.files) {
if (pasteFile.fileName.equalsIgnoreCase(file.getFileName())) {
throw new IllegalArgumentException(String.format("Found duplicate file with name %s",
file.getFileName()));
throw new IllegalArgumentException(
String.format("Found duplicate file with name %s", file.getFileName()));
}
}
this.files.add(file);
@ -78,7 +80,8 @@ public final class IncendoPaster {
*/
private String toJsonString() {
final StringBuilder builder = new StringBuilder("{\n");
builder.append("\"paste_application\": \"").append(this.pasteApplication).append("\",\n\"files\": \"");
builder.append("\"paste_application\": \"").append(this.pasteApplication)
.append("\",\n\"files\": \"");
Iterator<PasteFile> fileIterator = this.files.iterator();
while (fileIterator.hasNext()) {
final PasteFile file = fileIterator.next();
@ -126,11 +129,13 @@ public final class IncendoPaster {
final long size = content.length;
PlotSquared.debug(String.format("Paste Too Big > Size: %dMB", size / 1_000_000));
}
throw new IllegalStateException(String.format("Server returned status: %d %s",
httpURLConnection.getResponseCode(), httpURLConnection.getResponseMessage()));
throw new IllegalStateException(String
.format("Server returned status: %d %s", httpURLConnection.getResponseCode(),
httpURLConnection.getResponseMessage()));
}
final StringBuilder input = new StringBuilder();
try (final BufferedReader inputStream = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
try (final BufferedReader inputStream = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()))) {
String line;
while ((line = inputStream.readLine()) != null) {
input.append(line).append("\n");
@ -151,7 +156,7 @@ public final class IncendoPaster {
* Construct a new paste file
*
* @param fileName File name, cannot be empty, nor null
* @param content File content, cannot be empty, nor null
* @param content File content, cannot be empty, nor null
*/
public PasteFile(final String fileName, final String content) {
if (fileName == null || fileName.isEmpty()) {

View File

@ -780,8 +780,7 @@ public class MainUtil {
final String newInfo = info;
TaskManager.runTaskAsync(() -> {
int max = 10;
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES
.isEmpty()) {
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) {
max = 8;
}
String info1;

View File

@ -245,8 +245,8 @@ public class StringMan {
}
public static boolean isEqual(String a, String b) {
return (a == b) || ((a != null) && (b != null) && (a.length() == b.length()) &&
(a.hashCode() == b.hashCode()) && a.equals(b));
return (a == b) || ((a != null) && (b != null) && (a.length() == b.length()) && (
a.hashCode() == b.hashCode()) && a.equals(b));
// return a.equals(b) || b != null && a.length() == b.length() && a.hashCode() == b.hashCode()
// && a.equals(b);
}

View File

@ -13,292 +13,291 @@ import java.util.concurrent.atomic.AtomicBoolean;
public class GlobalBlockQueue {
public static GlobalBlockQueue IMP;
private final int PARALLEL_THREADS;
private final ConcurrentLinkedDeque<LocalBlockQueue> activeQueues;
private final ConcurrentLinkedDeque<LocalBlockQueue> inactiveQueues;
private final ConcurrentLinkedDeque<Runnable> runnables;
private final AtomicBoolean running;
private QueueProvider provider;
/**
* Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the
* server
*/
private long last;
private long secondLast;
private long lastSuccess;
private final RunnableVal2<Long, LocalBlockQueue> SET_TASK =
new RunnableVal2<Long, LocalBlockQueue>() {
@Override
public void run(Long free, LocalBlockQueue queue) {
do {
boolean more = queue.next();
if (!more) {
lastSuccess = last;
if (inactiveQueues.size() == 0 && activeQueues.size() == 0) {
tasks();
}
return;
public static GlobalBlockQueue IMP;
private final int PARALLEL_THREADS;
private final ConcurrentLinkedDeque<LocalBlockQueue> activeQueues;
private final ConcurrentLinkedDeque<LocalBlockQueue> inactiveQueues;
private final ConcurrentLinkedDeque<Runnable> runnables;
private final AtomicBoolean running;
private QueueProvider provider;
/**
* Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the
* server
*/
private long last;
private long secondLast;
private long lastSuccess;
private final RunnableVal2<Long, LocalBlockQueue> SET_TASK =
new RunnableVal2<Long, LocalBlockQueue>() {
@Override public void run(Long free, LocalBlockQueue queue) {
do {
boolean more = queue.next();
if (!more) {
lastSuccess = last;
if (inactiveQueues.size() == 0 && activeQueues.size() == 0) {
tasks();
}
return;
}
} while (((GlobalBlockQueue.this.secondLast = System.currentTimeMillis())
- GlobalBlockQueue.this.last) < free);
}
} while (((GlobalBlockQueue.this.secondLast = System.currentTimeMillis())
- GlobalBlockQueue.this.last) < free);
};
public GlobalBlockQueue(QueueProvider provider, int threads) {
this.provider = provider;
activeQueues = new ConcurrentLinkedDeque<>();
inactiveQueues = new ConcurrentLinkedDeque<>();
runnables = new ConcurrentLinkedDeque<>();
running = new AtomicBoolean();
this.PARALLEL_THREADS = threads;
}
public QueueProvider getProvider() {
return provider;
}
public void setProvider(QueueProvider provider) {
this.provider = provider;
}
public LocalBlockQueue getNewQueue(String world, boolean autoQueue) {
LocalBlockQueue queue = provider.getNewQueue(world);
if (autoQueue) {
inactiveQueues.add(queue);
}
};
public GlobalBlockQueue(QueueProvider provider, int threads) {
this.provider = provider;
activeQueues = new ConcurrentLinkedDeque<>();
inactiveQueues = new ConcurrentLinkedDeque<>();
runnables = new ConcurrentLinkedDeque<>();
running = new AtomicBoolean();
this.PARALLEL_THREADS = threads;
}
public QueueProvider getProvider() {
return provider;
}
public void setProvider(QueueProvider provider) {
this.provider = provider;
}
public LocalBlockQueue getNewQueue(String world, boolean autoQueue) {
LocalBlockQueue queue = provider.getNewQueue(world);
if (autoQueue) {
inactiveQueues.add(queue);
}
return queue;
}
public boolean stop() {
if (!running.get()) {
return false;
}
running.set(false);
return true;
}
public boolean runTask() {
if (running.get()) {
return false;
}
running.set(true);
TaskManager.runTaskRepeat(() -> {
if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) {
lastSuccess = System.currentTimeMillis();
tasks();
return;
}
SET_TASK.value1 = 50 + Math.min(
(50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last =
System.currentTimeMillis()),
GlobalBlockQueue.this.secondLast - System.currentTimeMillis());
SET_TASK.value2 = getNextQueue();
if (SET_TASK.value2 == null) {
return;
}
if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException(
"This shouldn't be possible for placement to occur off the main thread");
}
// Disable the async catcher as it can't discern async vs parallel
SET_TASK.value2.startSet(true);
try {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true);
}
}, 1);
return true;
}
public QueueStage getStage(LocalBlockQueue queue) {
if (activeQueues.contains(queue)) {
return QueueStage.ACTIVE;
} else if (inactiveQueues.contains(queue)) {
return QueueStage.INACTIVE;
}
return QueueStage.NONE;
}
public boolean isStage(LocalBlockQueue queue, QueueStage stage) {
switch (stage) {
case ACTIVE:
return activeQueues.contains(queue);
case INACTIVE:
return inactiveQueues.contains(queue);
case NONE:
return !activeQueues.contains(queue) && !inactiveQueues.contains(queue);
}
return false;
}
public void enqueue(LocalBlockQueue queue) {
inactiveQueues.remove(queue);
if (queue.size() > 0 && !activeQueues.contains(queue)) {
queue.optimize();
activeQueues.add(queue);
}
}
public void dequeue(LocalBlockQueue queue) {
inactiveQueues.remove(queue);
activeQueues.remove(queue);
}
public List<LocalBlockQueue> getAllQueues() {
ArrayList<LocalBlockQueue> list =
new ArrayList<>(activeQueues.size() + inactiveQueues.size());
list.addAll(inactiveQueues);
list.addAll(activeQueues);
return list;
}
public List<LocalBlockQueue> getActiveQueues() {
return new ArrayList<>(activeQueues);
}
public List<LocalBlockQueue> getInactiveQueues() {
return new ArrayList<>(inactiveQueues);
}
public void flush(LocalBlockQueue queue) {
SET_TASK.value1 = Long.MAX_VALUE;
SET_TASK.value2 = queue;
if (SET_TASK.value2 == null) {
return;
}
if (PlotSquared.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException("Must be flushed on the main thread!");
}
// Disable the async catcher as it can't discern async vs parallel
SET_TASK.value2.startSet(true);
try {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true);
dequeue(queue);
}
}
public LocalBlockQueue getNextQueue() {
long now = System.currentTimeMillis();
while (activeQueues.size() > 0) {
LocalBlockQueue queue = activeQueues.peek();
if (queue != null && queue.size() > 0) {
queue.setModified(now);
return queue;
} else {
activeQueues.poll();
}
}
int size = inactiveQueues.size();
if (size > 0) {
Iterator<LocalBlockQueue> iter = inactiveQueues.iterator();
try {
int total = 0;
LocalBlockQueue firstNonEmpty = null;
while (iter.hasNext()) {
LocalBlockQueue queue = iter.next();
long age = now - queue.getModified();
total += queue.size();
if (queue.size() == 0) {
if (age > 1000) {
iter.remove();
}
continue;
}
if (firstNonEmpty == null) {
firstNonEmpty = queue;
}
if (total > 64) {
firstNonEmpty.setModified(now);
return firstNonEmpty;
}
if (age > 60000) {
queue.setModified(now);
return queue;
}
public boolean stop() {
if (!running.get()) {
return false;
}
} catch (ConcurrentModificationException e) {
e.printStackTrace();
}
running.set(false);
return true;
}
return null;
}
public boolean isDone() {
return activeQueues.size() == 0 && inactiveQueues.size() == 0;
}
public boolean runTask() {
if (running.get()) {
return false;
}
running.set(true);
TaskManager.runTaskRepeat(() -> {
if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) {
lastSuccess = System.currentTimeMillis();
tasks();
return;
}
SET_TASK.value1 = 50 + Math.min(
(50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last =
System.currentTimeMillis()),
GlobalBlockQueue.this.secondLast - System.currentTimeMillis());
SET_TASK.value2 = getNextQueue();
if (SET_TASK.value2 == null) {
return;
}
if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException(
"This shouldn't be possible for placement to occur off the main thread");
}
// Disable the async catcher as it can't discern async vs parallel
SET_TASK.value2.startSet(true);
try {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true);
}
}, 1);
return true;
}
public boolean addTask(final Runnable whenDone) {
if (this.isDone()) {
// Run
this.tasks();
if (whenDone != null) {
whenDone.run();
}
return true;
public QueueStage getStage(LocalBlockQueue queue) {
if (activeQueues.contains(queue)) {
return QueueStage.ACTIVE;
} else if (inactiveQueues.contains(queue)) {
return QueueStage.INACTIVE;
}
return QueueStage.NONE;
}
if (whenDone != null) {
this.runnables.add(whenDone);
}
return false;
}
public synchronized boolean tasks() {
if (this.runnables.isEmpty()) {
return false;
public boolean isStage(LocalBlockQueue queue, QueueStage stage) {
switch (stage) {
case ACTIVE:
return activeQueues.contains(queue);
case INACTIVE:
return inactiveQueues.contains(queue);
case NONE:
return !activeQueues.contains(queue) && !inactiveQueues.contains(queue);
}
return false;
}
final ArrayList<Runnable> tmp = new ArrayList<>(this.runnables);
this.runnables.clear();
for (final Runnable runnable : tmp) {
runnable.run();
}
return true;
}
public enum QueueStage {
INACTIVE, ACTIVE, NONE
}
public void enqueue(LocalBlockQueue queue) {
inactiveQueues.remove(queue);
if (queue.size() > 0 && !activeQueues.contains(queue)) {
queue.optimize();
activeQueues.add(queue);
}
}
public void dequeue(LocalBlockQueue queue) {
inactiveQueues.remove(queue);
activeQueues.remove(queue);
}
public List<LocalBlockQueue> getAllQueues() {
ArrayList<LocalBlockQueue> list =
new ArrayList<>(activeQueues.size() + inactiveQueues.size());
list.addAll(inactiveQueues);
list.addAll(activeQueues);
return list;
}
public List<LocalBlockQueue> getActiveQueues() {
return new ArrayList<>(activeQueues);
}
public List<LocalBlockQueue> getInactiveQueues() {
return new ArrayList<>(inactiveQueues);
}
public void flush(LocalBlockQueue queue) {
SET_TASK.value1 = Long.MAX_VALUE;
SET_TASK.value2 = queue;
if (SET_TASK.value2 == null) {
return;
}
if (PlotSquared.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException("Must be flushed on the main thread!");
}
// Disable the async catcher as it can't discern async vs parallel
SET_TASK.value2.startSet(true);
try {
if (PARALLEL_THREADS <= 1) {
SET_TASK.run();
} else {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
// Enable it again (note that we are still on the main thread)
SET_TASK.value2.endSet(true);
dequeue(queue);
}
}
public LocalBlockQueue getNextQueue() {
long now = System.currentTimeMillis();
while (activeQueues.size() > 0) {
LocalBlockQueue queue = activeQueues.peek();
if (queue != null && queue.size() > 0) {
queue.setModified(now);
return queue;
} else {
activeQueues.poll();
}
}
int size = inactiveQueues.size();
if (size > 0) {
Iterator<LocalBlockQueue> iter = inactiveQueues.iterator();
try {
int total = 0;
LocalBlockQueue firstNonEmpty = null;
while (iter.hasNext()) {
LocalBlockQueue queue = iter.next();
long age = now - queue.getModified();
total += queue.size();
if (queue.size() == 0) {
if (age > 1000) {
iter.remove();
}
continue;
}
if (firstNonEmpty == null) {
firstNonEmpty = queue;
}
if (total > 64) {
firstNonEmpty.setModified(now);
return firstNonEmpty;
}
if (age > 60000) {
queue.setModified(now);
return queue;
}
}
} catch (ConcurrentModificationException e) {
e.printStackTrace();
}
}
return null;
}
public boolean isDone() {
return activeQueues.size() == 0 && inactiveQueues.size() == 0;
}
public boolean addTask(final Runnable whenDone) {
if (this.isDone()) {
// Run
this.tasks();
if (whenDone != null) {
whenDone.run();
}
return true;
}
if (whenDone != null) {
this.runnables.add(whenDone);
}
return false;
}
public synchronized boolean tasks() {
if (this.runnables.isEmpty()) {
return false;
}
final ArrayList<Runnable> tmp = new ArrayList<>(this.runnables);
this.runnables.clear();
for (final Runnable runnable : tmp) {
runnable.run();
}
return true;
}
public enum QueueStage {
INACTIVE, ACTIVE, NONE
}
}

View File

@ -19,435 +19,431 @@ import java.util.concurrent.ConcurrentLinkedDeque;
public class ExpireManager {
public static ExpireManager IMP;
private final ConcurrentHashMap<UUID, Long> dates_cache;
private final ConcurrentHashMap<UUID, Long> account_age_cache;
private volatile HashSet<Plot> plotsToDelete;
private ArrayDeque<ExpiryTask> tasks;
/**
* 0 = stopped, 1 = stopping, 2 = running
*/
private int running;
public static ExpireManager IMP;
private final ConcurrentHashMap<UUID, Long> dates_cache;
private final ConcurrentHashMap<UUID, Long> account_age_cache;
private volatile HashSet<Plot> plotsToDelete;
private ArrayDeque<ExpiryTask> tasks;
/**
* 0 = stopped, 1 = stopping, 2 = running
*/
private int running;
public ExpireManager() {
tasks = new ArrayDeque<>();
dates_cache = new ConcurrentHashMap<>();
account_age_cache = new ConcurrentHashMap<>();
}
public void addTask(ExpiryTask task) {
PlotSquared.debug("Adding new expiry task!");
this.tasks.add(task);
}
public void handleJoin(PlotPlayer pp) {
storeDate(pp.getUUID(), System.currentTimeMillis());
if (plotsToDelete != null && !plotsToDelete.isEmpty()) {
for (Plot plot : pp.getPlots()) {
plotsToDelete.remove(plot);
}
public ExpireManager() {
tasks = new ArrayDeque<>();
dates_cache = new ConcurrentHashMap<>();
account_age_cache = new ConcurrentHashMap<>();
}
confirmExpiry(pp);
}
public void handleEntry(PlotPlayer pp, Plot plot) {
if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp
.hasPermission("plots.admin.command.autoclear") && plotsToDelete.contains(plot)) {
if (!isExpired(new ArrayDeque<>(tasks), plot).isEmpty()) {
public void addTask(ExpiryTask task) {
PlotSquared.debug("Adding new expiry task!");
this.tasks.add(task);
}
public void handleJoin(PlotPlayer pp) {
storeDate(pp.getUUID(), System.currentTimeMillis());
if (plotsToDelete != null && !plotsToDelete.isEmpty()) {
for (Plot plot : pp.getPlots()) {
plotsToDelete.remove(plot);
}
}
confirmExpiry(pp);
} else {
plotsToDelete.remove(plot);
confirmExpiry(pp);
}
}
}
/**
* Gets the account last joined - first joined (or Long.MAX_VALUE)
*
* @return result
*/
public long getAccountAge(UUID uuid) {
Long value = this.account_age_cache.get(uuid);
return value == null ? Long.MAX_VALUE : value;
}
public long getTimestamp(UUID uuid) {
Long value = this.dates_cache.get(uuid);
return value == null ? 0 : value;
}
public void updateExpired(Plot plot) {
if (plotsToDelete != null && !plotsToDelete.isEmpty() && plotsToDelete.contains(plot)) {
if (isExpired(new ArrayDeque<>(tasks), plot).isEmpty()) {
plotsToDelete.remove(plot);
}
}
}
public void confirmExpiry(final PlotPlayer pp) {
if (pp.getMeta("ignoreExpireTask") != null) {
return;
}
if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp
.hasPermission("plots.admin.command.autoclear")) {
final int num = plotsToDelete.size();
while (!plotsToDelete.isEmpty()) {
Iterator<Plot> iter = plotsToDelete.iterator();
final Plot current = iter.next();
if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) {
TaskManager.runTask(() -> {
pp.setMeta("ignoreExpireTask", true);
pp.teleport(current.getCenter());
pp.deleteMeta("ignoreExpireTask");
PlotMessage msg = new PlotMessage().text(
num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ")
.color("$1").text(current.toString()).color("$2")
.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 this (/plot delete)")
.color("$2").suggest("/plot delete").tooltip("/plot delete")
.text("\n - ").color("$3").text("Remind later (/plot set keep 1d)")
.color("$2").suggest("/plot set keep 1d")
.tooltip("/plot set keep 1d").text("\n - ").color("$3")
.text("Keep this (/plot set keep true)").color("$2")
.suggest("/plot set keep true").tooltip("/plot set keep true")
.text("\n - ").color("$3").text("Don't show me this").color("$2")
.suggest("/plot toggle clear-confirmation")
.tooltip("/plot toggle clear-confirmation");
msg.send(pp);
});
return;
} else {
iter.remove();
public void handleEntry(PlotPlayer pp, Plot plot) {
if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp
.hasPermission("plots.admin.command.autoclear") && plotsToDelete.contains(plot)) {
if (!isExpired(new ArrayDeque<>(tasks), plot).isEmpty()) {
confirmExpiry(pp);
} else {
plotsToDelete.remove(plot);
confirmExpiry(pp);
}
}
}
plotsToDelete.clear();
}
}
public boolean cancelTask() {
if (this.running != 2) {
return false;
/**
* Gets the account last joined - first joined (or Long.MAX_VALUE)
*
* @return result
*/
public long getAccountAge(UUID uuid) {
Long value = this.account_age_cache.get(uuid);
return value == null ? Long.MAX_VALUE : value;
}
this.running = 1;
return true;
}
public boolean runAutomatedTask() {
return runTask(new RunnableVal3<Plot, Runnable, Boolean>() {
@Override
public void run(Plot plot, Runnable runnable, Boolean confirm) {
if (confirm) {
if (plotsToDelete == null) {
plotsToDelete = new HashSet<>();
}
plotsToDelete.add(plot);
runnable.run();
} else {
deleteWithMessage(plot, runnable);
public long getTimestamp(UUID uuid) {
Long value = this.dates_cache.get(uuid);
return value == null ? 0 : value;
}
public void updateExpired(Plot plot) {
if (plotsToDelete != null && !plotsToDelete.isEmpty() && plotsToDelete.contains(plot)) {
if (isExpired(new ArrayDeque<>(tasks), plot).isEmpty()) {
plotsToDelete.remove(plot);
}
}
}
});
}
public Collection<ExpiryTask> isExpired(ArrayDeque<ExpiryTask> applicable, Plot plot) {
// Filter out invalid worlds
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask et = applicable.poll();
if (et.applies(plot.getArea())) {
applicable.add(et);
}
}
if (applicable.isEmpty()) {
return new ArrayList<>();
}
boolean shouldCheckAccountAge = false;
long diff = getAge(plot);
if (diff == 0) {
return new ArrayList<>();
}
// Filter out non old plots
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask et = applicable.poll();
if (et.applies(diff)) {
applicable.add(et);
shouldCheckAccountAge |= et.getSettings().SKIP_ACCOUNT_AGE_DAYS != -1;
}
}
if (applicable.isEmpty()) {
return new ArrayList<>();
}
// Check account age
if (shouldCheckAccountAge) {
long accountAge = getAge(plot);
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask et = applicable.poll();
if (et.appliesAccountAge(accountAge)) {
applicable.add(et);
}
}
if (applicable.isEmpty()) {
return new ArrayList<>();
}
}
// Run applicable non confirming tasks
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask expiryTask = applicable.poll();
if (!expiryTask.needsAnalysis() || plot.getArea().TYPE != 0) {
if (!expiryTask.requiresConfirmation()) {
return Collections.singletonList(expiryTask);
}
}
applicable.add(expiryTask);
}
// Run applicable confirming tasks
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask expiryTask = applicable.poll();
if (!expiryTask.needsAnalysis() || plot.getArea().TYPE != 0) {
return Collections.singletonList(expiryTask);
}
applicable.add(expiryTask);
}
return applicable;
}
public ArrayDeque<ExpiryTask> getTasks(PlotArea area) {
ArrayDeque<ExpiryTask> queue = new ArrayDeque<>(tasks);
queue.removeIf(expiryTask -> !expiryTask.applies(area));
return queue;
}
public void passesComplexity(PlotAnalysis analysis, Collection<ExpiryTask> applicable,
RunnableVal<Boolean> success, Runnable failure) {
if (analysis != null) {
// Run non confirming tasks
for (ExpiryTask et : applicable) {
if (!et.requiresConfirmation() && et.applies(analysis)) {
success.run(false);
return;
}
}
for (ExpiryTask et : applicable) {
if (et.applies(analysis)) {
success.run(true);
return;
}
}
failure.run();
}
}
public boolean runTask(final RunnableVal3<Plot, Runnable, Boolean> expiredTask) {
if (this.running != 0) {
return false;
}
this.running = 2;
final ConcurrentLinkedDeque<Plot> plots =
new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots());
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
final Runnable task = this;
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
long start = System.currentTimeMillis();
while (!plots.isEmpty()) {
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
public void confirmExpiry(final PlotPlayer pp) {
if (pp.getMeta("ignoreExpireTask") != null) {
return;
}
Plot plot = plots.poll();
PlotArea area = plot.getArea();
final Plot newPlot = area.getPlot(plot.getId());
final ArrayDeque<ExpiryTask> applicable = new ArrayDeque<>(tasks);
final Collection<ExpiryTask> expired = isExpired(applicable, newPlot);
if (expired.isEmpty()) {
continue;
}
for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) {
expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1),
expiryTask.requiresConfirmation());
return;
}
}
final RunnableVal<PlotAnalysis> handleAnalysis =
new RunnableVal<PlotAnalysis>() {
@Override
public void run(final PlotAnalysis changed) {
passesComplexity(changed, expired, new RunnableVal<Boolean>() {
@Override
public void run(Boolean confirmation) {
expiredTask.run(newPlot,
() -> TaskManager.IMP.taskLaterAsync(task, 1), confirmation);
}
}, () -> {
FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20);
});
}
if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp
.hasPermission("plots.admin.command.autoclear")) {
final int num = plotsToDelete.size();
while (!plotsToDelete.isEmpty()) {
Iterator<Plot> iter = plotsToDelete.iterator();
final Plot current = iter.next();
if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) {
TaskManager.runTask(() -> {
pp.setMeta("ignoreExpireTask", true);
pp.teleport(current.getCenter());
pp.deleteMeta("ignoreExpireTask");
PlotMessage msg = new PlotMessage()
.text(num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ")
.color("$1").text(current.toString()).color("$2")
.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 this (/plot delete)")
.color("$2").suggest("/plot delete").tooltip("/plot delete")
.text("\n - ").color("$3").text("Remind later (/plot set keep 1d)")
.color("$2").suggest("/plot set keep 1d").tooltip("/plot set keep 1d")
.text("\n - ").color("$3").text("Keep this (/plot set keep true)")
.color("$2").suggest("/plot set keep true")
.tooltip("/plot set keep true").text("\n - ").color("$3")
.text("Don't show me this").color("$2")
.suggest("/plot toggle clear-confirmation")
.tooltip("/plot toggle clear-confirmation");
msg.send(pp);
});
return;
} else {
iter.remove();
}
};
final Runnable doAnalysis = () -> HybridUtils.manager
.analyzePlot(newPlot, handleAnalysis);
PlotAnalysis analysis = newPlot.getComplexity(null);
if (analysis != null) {
passesComplexity(analysis, expired, new RunnableVal<Boolean>() {
@Override
public void run(Boolean value) {
doAnalysis.run();
}
}, () -> TaskManager.IMP.taskLaterAsync(task, 1));
} else {
doAnalysis.run();
}
return;
}
if (plots.isEmpty()) {
ExpireManager.this.running = 3;
TaskManager.runTaskLater(() -> {
if (ExpireManager.this.running == 3) {
ExpireManager.this.running = 2;
runTask(expiredTask);
}
}, 86400000);
plotsToDelete.clear();
}
}
public boolean cancelTask() {
if (this.running != 2) {
return false;
}
this.running = 1;
return true;
}
public boolean runAutomatedTask() {
return runTask(new RunnableVal3<Plot, Runnable, Boolean>() {
@Override public void run(Plot plot, Runnable runnable, Boolean confirm) {
if (confirm) {
if (plotsToDelete == null) {
plotsToDelete = new HashSet<>();
}
plotsToDelete.add(plot);
runnable.run();
} else {
deleteWithMessage(plot, runnable);
}
}
});
}
public Collection<ExpiryTask> isExpired(ArrayDeque<ExpiryTask> applicable, Plot plot) {
// Filter out invalid worlds
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask et = applicable.poll();
if (et.applies(plot.getArea())) {
applicable.add(et);
}
}
if (applicable.isEmpty()) {
return new ArrayList<>();
}
boolean shouldCheckAccountAge = false;
long diff = getAge(plot);
if (diff == 0) {
return new ArrayList<>();
}
// Filter out non old plots
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask et = applicable.poll();
if (et.applies(diff)) {
applicable.add(et);
shouldCheckAccountAge |= et.getSettings().SKIP_ACCOUNT_AGE_DAYS != -1;
}
}
if (applicable.isEmpty()) {
return new ArrayList<>();
}
// Check account age
if (shouldCheckAccountAge) {
long accountAge = getAge(plot);
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask et = applicable.poll();
if (et.appliesAccountAge(accountAge)) {
applicable.add(et);
}
}
if (applicable.isEmpty()) {
return new ArrayList<>();
}
}
// Run applicable non confirming tasks
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask expiryTask = applicable.poll();
if (!expiryTask.needsAnalysis() || plot.getArea().TYPE != 0) {
if (!expiryTask.requiresConfirmation()) {
return Collections.singletonList(expiryTask);
}
}
applicable.add(expiryTask);
}
// Run applicable confirming tasks
for (int i = 0; i < applicable.size(); i++) {
ExpiryTask expiryTask = applicable.poll();
if (!expiryTask.needsAnalysis() || plot.getArea().TYPE != 0) {
return Collections.singletonList(expiryTask);
}
applicable.add(expiryTask);
}
return applicable;
}
public ArrayDeque<ExpiryTask> getTasks(PlotArea area) {
ArrayDeque<ExpiryTask> queue = new ArrayDeque<>(tasks);
queue.removeIf(expiryTask -> !expiryTask.applies(area));
return queue;
}
public void passesComplexity(PlotAnalysis analysis, Collection<ExpiryTask> applicable,
RunnableVal<Boolean> success, Runnable failure) {
if (analysis != null) {
// Run non confirming tasks
for (ExpiryTask et : applicable) {
if (!et.requiresConfirmation() && et.applies(analysis)) {
success.run(false);
return;
}
}
for (ExpiryTask et : applicable) {
if (et.applies(analysis)) {
success.run(true);
return;
}
}
failure.run();
}
}
public boolean runTask(final RunnableVal3<Plot, Runnable, Boolean> expiredTask) {
if (this.running != 0) {
return false;
}
this.running = 2;
final ConcurrentLinkedDeque<Plot> plots =
new ConcurrentLinkedDeque<>(PlotSquared.get().getPlots());
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
final Runnable task = this;
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
long start = System.currentTimeMillis();
while (!plots.isEmpty()) {
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
Plot plot = plots.poll();
PlotArea area = plot.getArea();
final Plot newPlot = area.getPlot(plot.getId());
final ArrayDeque<ExpiryTask> applicable = new ArrayDeque<>(tasks);
final Collection<ExpiryTask> expired = isExpired(applicable, newPlot);
if (expired.isEmpty()) {
continue;
}
for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) {
expiredTask.run(newPlot, () -> TaskManager.IMP.taskLaterAsync(task, 1),
expiryTask.requiresConfirmation());
return;
}
}
final RunnableVal<PlotAnalysis> handleAnalysis =
new RunnableVal<PlotAnalysis>() {
@Override public void run(final PlotAnalysis changed) {
passesComplexity(changed, expired, new RunnableVal<Boolean>() {
@Override public void run(Boolean confirmation) {
expiredTask.run(newPlot,
() -> TaskManager.IMP.taskLaterAsync(task, 1),
confirmation);
}
}, () -> {
FlagManager
.addPlotFlag(newPlot, Flags.ANALYSIS, changed.asList());
TaskManager.runTaskLaterAsync(task, 20);
});
}
};
final Runnable doAnalysis =
() -> HybridUtils.manager.analyzePlot(newPlot, handleAnalysis);
PlotAnalysis analysis = newPlot.getComplexity(null);
if (analysis != null) {
passesComplexity(analysis, expired, new RunnableVal<Boolean>() {
@Override public void run(Boolean value) {
doAnalysis.run();
}
}, () -> TaskManager.IMP.taskLaterAsync(task, 1));
} else {
doAnalysis.run();
}
return;
}
if (plots.isEmpty()) {
ExpireManager.this.running = 3;
TaskManager.runTaskLater(() -> {
if (ExpireManager.this.running == 3) {
ExpireManager.this.running = 2;
runTask(expiredTask);
}
}, 86400000);
} else {
TaskManager.runTaskLaterAsync(task, 20 * 10);
}
}
});
return true;
}
public void storeDate(UUID uuid, long time) {
Long existing = this.dates_cache.put(uuid, time);
if (existing != null) {
long diff = time - existing;
if (diff > 0) {
Long account_age = this.account_age_cache.get(uuid);
if (account_age != null) {
this.account_age_cache.put(uuid, account_age + diff);
}
}
}
}
public void storeAccountAge(UUID uuid, long time) {
this.account_age_cache.put(uuid, time);
}
public HashSet<Plot> getPendingExpired() {
return plotsToDelete == null ? new HashSet<>() : plotsToDelete;
}
public void deleteWithMessage(Plot plot, Runnable whenDone) {
if (plot.isMerged()) {
plot.unlinkPlot(true, false);
}
for (UUID helper : plot.getTrusted()) {
PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.toString());
}
}
for (UUID helper : plot.getMembers()) {
PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.toString());
}
}
Set<Plot> plots = plot.getConnectedPlots();
plot.deletePlot(whenDone);
PlotAnalysis changed = plot.getComplexity(null);
int changes = changed == null ? 0 : changed.changes_sd;
int modified = changed == null ? 0 : changed.changes;
PlotSquared.debug(
"$2[&5Expire&dManager$2] &cDeleted expired plot: " + plot + " User:" + plot.owner
+ " Delta:" + changes + "/" + modified + " Connected: " + StringMan
.getString(plots));
PlotSquared.debug("$4 - Area: " + plot.getArea());
if (plot.hasOwner()) {
PlotSquared.debug("$4 - Owner: " + UUIDHandler.getName(plot.owner));
} else {
TaskManager.runTaskLaterAsync(task, 20 * 10);
PlotSquared.debug("$4 - Owner: Unowned");
}
}
});
return true;
}
}
public void storeDate(UUID uuid, long time) {
Long existing = this.dates_cache.put(uuid, time);
if (existing != null) {
long diff = time - existing;
if (diff > 0) {
Long account_age = this.account_age_cache.get(uuid);
if (account_age != null) {
this.account_age_cache.put(uuid, account_age + diff);
public long getAge(UUID uuid) {
if (UUIDHandler.getPlayer(uuid) != null) {
return 0;
}
}
}
}
public void storeAccountAge(UUID uuid, long time) {
this.account_age_cache.put(uuid, time);
}
public HashSet<Plot> getPendingExpired() {
return plotsToDelete == null ? new HashSet<>() : plotsToDelete;
}
public void deleteWithMessage(Plot plot, Runnable whenDone) {
if (plot.isMerged()) {
plot.unlinkPlot(true, false);
}
for (UUID helper : plot.getTrusted()) {
PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.toString());
}
}
for (UUID helper : plot.getMembers()) {
PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.toString());
}
}
Set<Plot> plots = plot.getConnectedPlots();
plot.deletePlot(whenDone);
PlotAnalysis changed = plot.getComplexity(null);
int changes = changed == null ? 0 : changed.changes_sd;
int modified = changed == null ? 0 : changed.changes;
PlotSquared.debug(
"$2[&5Expire&dManager$2] &cDeleted expired plot: " + plot + " User:" + plot.owner
+ " Delta:" + changes + "/" + modified + " Connected: " + StringMan
.getString(plots));
PlotSquared.debug("$4 - Area: " + plot.getArea());
if (plot.hasOwner()) {
PlotSquared.debug("$4 - Owner: " + UUIDHandler.getName(plot.owner));
} else {
PlotSquared.debug("$4 - Owner: Unowned");
}
}
public long getAge(UUID uuid) {
if (UUIDHandler.getPlayer(uuid) != null) {
return 0;
}
String name = UUIDHandler.getName(uuid);
if (name != null) {
Long last = this.dates_cache.get(uuid);
if (last == null) {
OfflinePlotPlayer opp;
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
opp = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid);
} else {
opp = UUIDHandler.getUUIDWrapper().getOfflinePlayer(name);
String name = UUIDHandler.getName(uuid);
if (name != null) {
Long last = this.dates_cache.get(uuid);
if (last == null) {
OfflinePlotPlayer opp;
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
opp = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid);
} else {
opp = UUIDHandler.getUUIDWrapper().getOfflinePlayer(name);
}
if (opp != null && (last = opp.getLastPlayed()) != 0) {
this.dates_cache.put(uuid, last);
} else {
return 0;
}
}
if (last == 0) {
return 0;
}
return System.currentTimeMillis() - last;
}
if (opp != null && (last = opp.getLastPlayed()) != 0) {
this.dates_cache.put(uuid, last);
} else {
return 0;
}
}
if (last == 0) {
return 0;
}
return System.currentTimeMillis() - last;
}
return 0;
}
public long getAccountAge(Plot plot) {
if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.owner)
|| UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) {
return Long.MAX_VALUE;
public long getAccountAge(Plot plot) {
if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.owner)
|| UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) {
return Long.MAX_VALUE;
}
long max = 0;
for (UUID owner : plot.getOwners()) {
long age = getAccountAge(owner);
max = Math.max(age, max);
}
return max;
}
long max = 0;
for (UUID owner : plot.getOwners()) {
long age = getAccountAge(owner);
max = Math.max(age, max);
}
return max;
}
public long getAge(Plot plot) {
if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.owner)
|| UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) {
return 0;
}
Optional<?> keep = plot.getFlag(Flags.KEEP);
if (keep.isPresent()) {
Object value = keep.get();
if (value instanceof Boolean) {
if (Boolean.TRUE.equals(value)) {
return 0;
public long getAge(Plot plot) {
if (!plot.hasOwner() || Objects.equals(DBFunc.EVERYONE, plot.owner)
|| UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) {
return 0;
}
} else if (value instanceof Long) {
if ((Long) value > System.currentTimeMillis()) {
return 0;
Optional<?> keep = plot.getFlag(Flags.KEEP);
if (keep.isPresent()) {
Object value = keep.get();
if (value instanceof Boolean) {
if (Boolean.TRUE.equals(value)) {
return 0;
}
} else if (value instanceof Long) {
if ((Long) value > System.currentTimeMillis()) {
return 0;
}
} else { // Invalid?
return 0;
}
}
} else { // Invalid?
return 0;
}
long min = Long.MAX_VALUE;
for (UUID owner : plot.getOwners()) {
long age = getAge(owner);
if (age < min) {
min = age;
}
}
return min;
}
long min = Long.MAX_VALUE;
for (UUID owner : plot.getOwners()) {
long age = getAge(owner);
if (age < min) {
min = age;
}
}
return min;
}
}

View File

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

View File

@ -433,7 +433,6 @@ public class PlotAnalysis {
/**
* An optimized lossy standard deviation algorithm.
*
*/
public static int[] getSD(int[]... ranks) {
if (ranks.length == 0) {
@ -460,7 +459,6 @@ public class PlotAnalysis {
* An optimized algorithm for ranking a very specific set of inputs<br>
* - Input is an array of int with a max size of 102400<br>
* - A reduced sample space allows for sorting (and ranking in this case) in linear time
*
*/
public static int[] rank(int[] input) {
return rank(input, 102400);

View File

@ -4,7 +4,7 @@ This will increase a player's allowed plots by the provided value
*/
var uuid = UUIDHandler.getUUID('%s0', null);
if (uuid === null) {
C_INVALID_PLAYER.send(PlotPlayer, '%s0');
C_INVALID_PLAYER.send(PlotPlayer, '%s0');
}
else if (!MathMan.class.static.isInteger('%s1')) {
C_NOT_VALID_NUMBER.send(PlotPlayer, '(0, ' + Settings.MAX_PLOTS + ')');