More cleaning

This commit is contained in:
MattBDev 2016-03-23 13:09:13 -04:00
parent 9e2c6f2182
commit bb4700aa5a
54 changed files with 1831 additions and 1933 deletions

View File

@ -148,6 +148,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
Bukkit.getServer().getConsoleSender().sendMessage(message);
return;
} catch (Throwable ignored) {
//ignored
}
}
System.out.println(ConsoleColors.fromString(message));
@ -345,7 +346,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
}
@Override
final public ChunkGenerator getDefaultWorldGenerator(String world, String id) {
public final ChunkGenerator getDefaultWorldGenerator(String world, String id) {
HybridGen result = new HybridGen();
if (!PS.get().setupPlotWorld(world, id, result)) {
return null;
@ -590,14 +591,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
// create world
ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", "PlotSquared");
String generator = worldConfig.getString("generator.init", manager);
int type = worldConfig.getInt("generator.type");
int terrain = worldConfig.getInt("generator.terrain");
SetupObject setup = new SetupObject();
setup.plotManager = manager;
setup.setupGenerator = generator;
setup.type = type;
setup.terrain = terrain;
setup.setupGenerator = worldConfig.getString("generator.init", manager);
setup.type = worldConfig.getInt("generator.type");
setup.terrain = worldConfig.getInt("generator.terrain");
setup.step = new ConfigurationNode[0];
setup.world = worldName;
SetupUtils.manager.setupWorld(setup);

View File

@ -18,7 +18,7 @@ import java.util.Collection;
*/
public final class ArrayWrapper<E> {
private E[] _array;
private E[] array;
/**
* Creates an array wrapper with some elements.
@ -64,7 +64,7 @@ public final class ArrayWrapper<E> {
* @return The array wrapped by this instance.
*/
public E[] getArray() {
return this._array;
return this.array;
}
/**
@ -73,7 +73,7 @@ public final class ArrayWrapper<E> {
*/
public void setArray(E[] array) {
Validate.notNull(array, "The array must not be null.");
this._array = array;
this.array = array;
}
/**
@ -86,7 +86,7 @@ public final class ArrayWrapper<E> {
if (!(other instanceof ArrayWrapper)) {
return false;
}
return Arrays.equals(this._array, ((ArrayWrapper) other)._array);
return Arrays.equals(this.array, ((ArrayWrapper) other).array);
}
/**
@ -96,6 +96,6 @@ public final class ArrayWrapper<E> {
*/
@Override
public int hashCode() {
return Arrays.hashCode(this._array);
return Arrays.hashCode(this.array);
}
}

View File

@ -41,12 +41,12 @@ import java.util.logging.Level;
* provided by the vanilla Minecraft <a href="http://minecraft.gamepedia.com/Tellraw#Raw_JSON_Text">JSON message formatter</a>.
* This class allows plugins to emulate the functionality of the vanilla Minecraft
* <a href="http://minecraft.gamepedia.com/Commands#tellraw">tellraw command</a>.
* <p>
* This class follows the builder pattern, allowing for method chaining.
* It is set up such that invocations of property-setting methods will affect the current editing component,
* and a call to {@link #then(String)} or {@link #text(TextualComponent)} will append a new editing component to the end of the message,
* optionally initializing it with text. Further property-setting method calls will affect that editing component.
* </p>
* <p> This class follows the builder pattern, allowing for method chaining.
* It is set up such that invocations of property-setting methods will affect
* the current editing component, and a call to {@link #then(String)} or
* {@link #text(TextualComponent)} will append a new editing component to the
* end of the message, optionally initializing it with text. Further
* property-setting method calls will affect that editing component.</p>
*/
public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<MessagePart>, ConfigurationSerializable {

View File

@ -39,7 +39,7 @@ public final class Reflection {
* This is needed to bypass the JAR package name changing on each update.
* @return The version string of the OBC and NMS packages, <em>including the trailing dot</em>.
*/
public synchronized static String getVersion() {
public static synchronized String getVersion() {
return PS.get().IMP.getNMSPackage();
}
@ -50,7 +50,7 @@ public final class Reflection {
* @param className The name of the class, excluding the package, within NMS.
* @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getNMSClass(String className) {
public static synchronized Class<?> getNMSClass(String className) {
if (_loadedNMSClasses.containsKey(className)) {
return _loadedNMSClasses.get(className);
}
@ -76,7 +76,7 @@ public final class Reflection {
* .CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getOBCClass(String className) {
public static synchronized Class<?> getOBCClass(String className) {
if (_loadedOBCClasses.containsKey(className)) {
return _loadedOBCClasses.get(className);
}

View File

@ -178,8 +178,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
if (denied == null) {
if ("*".equals(name)) {
denied = DBFunc.everyone;
} else {
if (DBFunc.hasColumn(resultSet, "playerid")) {
} else if (DBFunc.hasColumn(resultSet, "playerid")) {
try {
byte[] bytes = resultSet.getBytes("playerid");
if (bytes != null) {
@ -198,7 +197,6 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
e.printStackTrace();
}
}
}
if (denied == null) {
PS.log("&6Could not identify denied for plot: " + id);
continue;

View File

@ -35,10 +35,10 @@ import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@ -51,26 +51,21 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created 2014-08-17 for PlotSquared
*
*/
public class LikePlotMeConverter {
private final String plugin;
/**
* Constructor
* Constructor.
*
* @param plugin Plugin Used to run the converter
*/
public LikePlotMeConverter(final String plugin) {
public LikePlotMeConverter(String plugin) {
this.plugin = plugin;
}
public static String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
public static String getWorld(String world) {
for (World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
@ -78,33 +73,34 @@ public class LikePlotMeConverter {
return world;
}
private void sendMessage(final String message) {
private void sendMessage(String message) {
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
public String getPlotMePath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
}
public String getAthionPlotsPath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
}
public FileConfiguration getPlotMeConfig(final String dataFolder) {
final File plotMeFile = new File(dataFolder + "config.yml");
public FileConfiguration getPlotMeConfig(String dataFolder) {
File plotMeFile = new File(dataFolder + "config.yml");
if (!plotMeFile.exists()) {
return null;
}
return YamlConfiguration.loadConfiguration(plotMeFile);
}
public Set<String> getPlotMeWorlds(final FileConfiguration plotConfig) {
public Set<String> getPlotMeWorlds(FileConfiguration plotConfig) {
return plotConfig.getConfigurationSection("worlds").getKeys(false);
}
public void mergeWorldYml(final String plugin, FileConfiguration plotConfig) {
public void mergeWorldYml(String plugin, FileConfiguration plotConfig) {
try {
File genConfig = new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
File genConfig =
new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
if (genConfig.exists()) {
YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig);
for (String key : yml.getKeys(true)) {
@ -116,32 +112,31 @@ public class LikePlotMeConverter {
}
}
}
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateWorldYml(final String plugin, final String location) {
public void updateWorldYml(String plugin, String location) {
try {
final Path path = Paths.get(location);
final File file = new File(location);
Path path = Paths.get(location);
File file = new File(location);
if (!file.exists()) {
return;
}
final Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared");
content = content.replaceAll(plugin, "PlotSquared");
Files.write(path, content.getBytes(charset));
} catch (IOException e) {
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) {
//ignored
}
}
public boolean run(final APlotMeConnector connector) {
public boolean run(APlotMeConnector connector) {
try {
final String dataFolder = getPlotMePath();
final FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
String dataFolder = getPlotMePath();
FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) {
return false;
}
@ -156,46 +151,47 @@ public class LikePlotMeConverter {
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
Connection connection = connector.getPlotMeConnection(this.plugin, plotConfig, dataFolder);
if (!connector.isValidConnection(connection)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false;
}
sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'");
sendMessage(this.plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'");
mergeWorldYml(plugin, plotConfig);
mergeWorldYml(this.plugin, plotConfig);
sendMessage("Connecting to " + plugin + " DB");
sendMessage("Connecting to " + this.plugin + " DB");
final ArrayList<Plot> createdPlots = new ArrayList<>();
ArrayList<Plot> createdPlots = new ArrayList<>();
sendMessage("Collecting plot data");
final String dbPrefix = plugin.toLowerCase();
String dbPrefix = this.plugin.toLowerCase();
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (Settings.CONVERT_PLOTME) {
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
updateWorldYml(this.plugin, "bukkit.yml");
updateWorldYml(this.plugin, "plugins/Multiverse-Core/worlds.yml");
for (String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world);
try {
final String actualWorldName = getWorld(world);
String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile);
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
sendMessage("&c-- &lFailed to save configuration for world '" + world
+ "'\nThis will need to be done using the setup command, or manually");
}
}
}
final HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
int plotCount = 0;
for (final Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
plotCount += entry.getValue().size();
}
if (!Settings.CONVERT_PLOTME) {
@ -205,14 +201,14 @@ public class LikePlotMeConverter {
sendMessage(" - " + dbPrefix + "Allowed");
sendMessage("Collected " + plotCount + " plots from PlotMe");
final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
if (PLOTME_DG_FILE.exists()) {
final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE);
File plotmeDgFile = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
if (plotmeDgFile.exists()) {
YamlConfiguration plotmeDgYml = YamlConfiguration.loadConfiguration(plotmeDgFile);
try {
for (final String world : plots.keySet()) {
final String actualWorldName = getWorld(world);
final String plotMeWorldName = world.toLowerCase();
Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
for (String world : plots.keySet()) {
String actualWorldName = getWorld(world);
String plotMeWorldName = world.toLowerCase();
Integer pathwidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
/*
* TODO: dead code
*
@ -222,29 +218,29 @@ public class LikePlotMeConverter {
*/
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
Integer pathheight = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (pathheight == 0) {
pathheight = 64;
}
PS.get().config.set("worlds." + world + ".road.height", pathheight);
PS.get().config.set("worlds." + world + ".wall.height", pathheight);
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
Integer plotsize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if (plotsize == 0) {
plotsize = 32;
}
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock", "44"); //
String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44"); //
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor));
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
PS.get().config.set("worlds." + world + ".plot.filling", Collections.singletonList(filling));
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5");
String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5");
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
Integer height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (height == 0) {
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if (height == 0) {
height = 64;
}
@ -254,7 +250,8 @@ public class LikePlotMeConverter {
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile);
}
} catch (IOException e) {
} catch (IOException ignored) {
//ignored
}
}
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
@ -270,7 +267,8 @@ public class LikePlotMeConverter {
}
}
if (duplicate > 0) {
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world
+ "'. Have you run the converter already?");
}
} else {
if (PS.get().plots_tmp != null) {
@ -284,7 +282,8 @@ public class LikePlotMeConverter {
}
}
if (duplicate > 0) {
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world
+ "'. Have you run the converter already?");
}
continue;
}
@ -315,57 +314,61 @@ public class LikePlotMeConverter {
sendMessage("Saving configuration...");
try {
PS.get().config.save(PS.get().configFile);
} catch (final IOException e) {
} catch (IOException e) {
sendMessage(" - &cFailed to save configuration.");
}
TaskManager.runTask(new Runnable() {
@Override
public void run() {
try {
boolean MV = false;
boolean MW = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
MV = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
MW = true;
boolean mv = false;
boolean mw = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
mv = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld")
.isEnabled()) {
mw = true;
}
for (final String worldname : worlds) {
final World world = Bukkit.getWorld(getWorld(worldname));
for (String worldname : worlds) {
World world = Bukkit.getWorld(getWorld(worldname));
if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldname);
}
final String actualWorldName = world.getName();
String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PS.get().removePlotAreas(actualWorldName);
if (MV) {
if (mv) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared");
} else if (MW) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g PlotSquared");
} else if (mw) {
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared");
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:PlotSquared");
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
final World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld();
World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld();
myworld.save();
}
}
} catch (final Exception e) {
} catch (CommandException e) {
e.printStackTrace();
}
if (done.get()) {
@ -381,7 +384,7 @@ public class LikePlotMeConverter {
}
}
});
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
PS.debug("&/end/");
}

View File

@ -23,39 +23,42 @@ import java.util.Map.Entry;
import java.util.UUID;
public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin;
@Override
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder) {
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
try {
if (plotConfig.getBoolean("usemySQL")) {
final String user = plotConfig.getString("mySQLuname");
final String password = plotConfig.getString("mySQLpass");
final String con = plotConfig.getString("mySQLconn");
String user = plotConfig.getString("mySQLuname");
String password = plotConfig.getString("mySQLpass");
String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
} else {
final File file = new File(dataFolder + File.separator + "plotmecore.db");
File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) {
return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection();
}
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
} catch (SQLException | ClassNotFoundException e) {}
} catch (SQLException | ClassNotFoundException ignored) {
//ignored
}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException {
ResultSet r;
PreparedStatement stmt;
final HashMap<String, Integer> plotWidth = new HashMap<>();
final HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<Integer, Plot> plots = new HashMap<>();
final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
ResultSet resultSet;
PreparedStatement statement;
HashMap<String, Integer> plotWidth = new HashMap<>();
HashMap<String, Integer> roadWidth = new HashMap<>();
HashMap<Integer, Plot> plots = new HashMap<>();
HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
try {
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_plots`");
r = stmt.executeQuery();
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`");
resultSet = statement.executeQuery();
} catch (SQLException e) {
PS.debug("========= Table does not exist =========");
e.printStackTrace();
@ -64,29 +67,29 @@ public class PlotMeConnector_017 extends APlotMeConnector {
PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3");
return null;
}
final boolean checkUUID = DBFunc.hasColumn(r, "ownerID");
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) {
final int key = r.getInt("plot_id");
final PlotId id = new PlotId(r.getInt("plotX"), r.getInt("plotZ"));
final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID");
boolean merge = !this.plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (resultSet.next()) {
int key = resultSet.getInt("plot_id");
PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ"));
String name = resultSet.getString("owner");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
if (!plots.containsKey(world) && merge) {
final int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
final int path = PS.get().config.getInt("worlds." + world + ".road.width");
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId, boolean[]>());
}
if (merge) {
final int tx = r.getInt("topX");
final int tz = r.getInt("topZ");
final int bx = r.getInt("bottomX") - 1;
final int bz = r.getInt("bottomZ") - 1;
final int path = roadWidth.get(world);
final int plot = plotWidth.get(world);
final Location top = getPlotTopLocAbs(path, plot, id);
final Location bot = getPlotBottomLocAbs(path, plot, id);
int tx = resultSet.getInt("topX");
int tz = resultSet.getInt("topZ");
int bx = resultSet.getInt("bottomX") - 1;
int bz = resultSet.getInt("bottomZ") - 1;
int path = roadWidth.get(world);
int plot = plotWidth.get(world);
Location top = getPlotTopLocAbs(path, plot, id);
Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX()) {
setMerged(merges, world, id, 1);
}
@ -107,12 +110,12 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} else {
if (checkUUID) {
try {
final byte[] bytes = r.getBytes("ownerid");
byte[] bytes = resultSet.getBytes("ownerid");
if (bytes != null) {
owner = UUID.nameUUIDFromBytes(bytes);
UUIDHandler.add(new StringWrapper(name), owner);
}
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -124,60 +127,60 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} else {
UUIDHandler.add(new StringWrapper(name), owner);
}
final Plot plot = new Plot(PlotArea.createGeneric(world), id, owner);
Plot plot = new Plot(PlotArea.createGeneric(world), id, owner);
plots.put(key, plot);
}
for (final Entry<Integer, Plot> entry : plots.entrySet()) {
final Plot plot = entry.getValue();
final HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.getArea().worldname);
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.getArea().worldname);
if (mergeMap != null) {
if (mergeMap.containsKey(plot.getId())) {
plot.setMerged(mergeMap.get(plot.getId()));
}
}
}
r.close();
stmt.close();
resultSet.close();
statement.close();
try {
PS.log(" - " + plugin + "core_denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_denied`");
r = stmt.executeQuery();
PS.log(" - " + this.plugin + "core_denied");
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`");
resultSet = statement.executeQuery();
while (r.next()) {
final int key = r.getInt("plot_id");
final Plot plot = plots.get(key);
while (resultSet.next()) {
int key = resultSet.getInt("plot_id");
Plot plot = plots.get(key);
if (plot == null) {
PS.log("&6Denied (" + key + ") references deleted plot; ignoring entry.");
continue;
}
final UUID denied = UUID.fromString(r.getString("player"));
UUID denied = UUID.fromString(resultSet.getString("player"));
plot.getDenied().add(denied);
}
PS.log(" - " + plugin + "core_allowed");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_allowed`");
r = stmt.executeQuery();
PS.log(" - " + this.plugin + "core_allowed");
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`");
resultSet = statement.executeQuery();
while (r.next()) {
final int key = r.getInt("plot_id");
final Plot plot = plots.get(key);
while (resultSet.next()) {
int key = resultSet.getInt("plot_id");
Plot plot = plots.get(key);
if (plot == null) {
PS.log("&6Allowed (" + key + ") references deleted plot; ignoring entry.");
continue;
}
final UUID allowed = UUID.fromString(r.getString("player"));
UUID allowed = UUID.fromString(resultSet.getString("player"));
plot.getTrusted().add(allowed);
}
r.close();
stmt.close();
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
final HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (final Entry<Integer, Plot> entry : plots.entrySet()) {
final Plot plot = entry.getValue();
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
HashMap<PlotId, Plot> map = processed.get(plot.getArea().worldname);
if (map == null) {
map = new HashMap<>();
@ -189,7 +192,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
}
@Override
public boolean accepts(final String version) {
public boolean accepts(String version) {
if (version == null) {
return false;
}

View File

@ -30,7 +30,8 @@ import java.util.HashSet;
public class WEListener implements Listener {
public final HashSet<String> rad1 = new HashSet<>(Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size"));
public final HashSet<String> rad1 = new HashSet<>(
Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size"));
public final HashSet<String> rad2 = new HashSet<>(Arrays.asList("fill", "fillr", "removenear", "remove"));
public final HashSet<String> rad2_1 = new HashSet<>(Arrays.asList("hcyl", "cyl"));
public final HashSet<String> rad2_2 = new HashSet<>(Arrays.asList("sphere", "pyramid"));
@ -38,7 +39,9 @@ public class WEListener implements Listener {
public final HashSet<String> rad3_1 = new HashSet<>(Collections.singletonList("brush gravity"));
public final HashSet<String> rad3_2 = new HashSet<>(Arrays.asList("brush sphere", "brush cylinder"));
public final HashSet<String> region = new HashSet<>(Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count", "distr",
public final HashSet<String> region = new HashSet<>(
Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count",
"distr",
"regen", "copy", "cut", "green", "setbiome"));
public final HashSet<String> regionExtend = new HashSet<>(Collections.singletonList("stack"));
public final HashSet<String> restricted = new HashSet<>(Collections.singletonList("up"));
@ -229,7 +232,8 @@ public class WEListener implements Listener {
if (split.length == 4) {
int iterations = getInt(split[3]);
if (iterations > maxIterations) {
MainUtil.sendMessage(pp, C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + ""));
MainUtil.sendMessage(pp,
C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + ""));
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);

View File

@ -10,7 +10,9 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer {
public final OfflinePlayer player;
/**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
* <p>Please do not use this method. Instead use BukkitUtil.getPlayer(Player),
* as it caches player objects.</p>
*
* @param player
*/
public BukkitOfflinePlayer(OfflinePlayer player) {

View File

@ -28,7 +28,8 @@ public class BukkitPlayer extends PlotPlayer {
private long last = 0;
/**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
* <p>Please do not use this method. Instead use BukkitUtil.getPlayer(Player),
* as it caches player objects.</p>
* @param player
*/
public BukkitPlayer(Player player) {
@ -140,13 +141,16 @@ public class BukkitPlayer extends PlotPlayer {
switch (weather) {
case CLEAR:
this.player.setPlayerWeather(WeatherType.CLEAR);
return;
break;
case RAIN:
this.player.setPlayerWeather(WeatherType.DOWNFALL);
return;
break;
case RESET:
this.player.resetPlayerWeather();
return;
break;
default:
this.player.resetPlayerWeather();
break;
}
}
@ -161,8 +165,9 @@ public class BukkitPlayer extends PlotPlayer {
return PlotGameMode.SPECTATOR;
case SURVIVAL:
return PlotGameMode.SURVIVAL;
default:
return PlotGameMode.SURVIVAL;
}
return null;
}
@Override
@ -170,16 +175,19 @@ public class BukkitPlayer extends PlotPlayer {
switch (gameMode) {
case ADVENTURE:
this.player.setGameMode(GameMode.ADVENTURE);
return;
break;
case CREATIVE:
this.player.setGameMode(GameMode.CREATIVE);
return;
break;
case SPECTATOR:
this.player.setGameMode(GameMode.SPECTATOR);
return;
break;
case SURVIVAL:
this.player.setGameMode(GameMode.SURVIVAL);
return;
break;
default:
this.player.setGameMode(GameMode.SURVIVAL);
break;
}
}

View File

@ -1,12 +1,13 @@
package com.plotsquared.bukkit.object.entity;
public class ArmorStandStats {
public float[] head = new float[3];
public float[] body = new float[3];
public float[] leftLeg = new float[3];
public float[] rightLeg = new float[3];
public float[] leftArm = new float[3];
public float[] rightArm = new float[3];
public final float[] head = new float[3];
public final float[] body = new float[3];
public final float[] leftLeg = new float[3];
public final float[] rightLeg = new float[3];
public final float[] leftArm = new float[3];
public final float[] rightArm = new float[3];
public boolean arms;
public boolean noplate;
public boolean nogravity;

View File

@ -1,16 +1,5 @@
package com.plotsquared.bukkit.object.schematic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import com.intellectualcrafters.jnbt.ByteTag;
import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.ListTag;
@ -20,32 +9,42 @@ import com.intellectualcrafters.plot.object.schematic.ItemType;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class StateWrapper {
public BlockState state = null;
public CompoundTag tag = null;
public StateWrapper(final BlockState state) {
public StateWrapper(BlockState state) {
this.state = state;
}
public StateWrapper(final CompoundTag tag) {
public StateWrapper(CompoundTag tag) {
this.tag = tag;
}
public boolean restoreTag(final short x, final short y, final short z, final Schematic schematic) {
if (tag == null) {
public boolean restoreTag(short x, short y, short z, Schematic schematic) {
if (this.tag == null) {
return false;
}
final List<Tag> itemsTag = tag.getListTag("Items").getValue();
final int length = itemsTag.size();
final short[] ids = new short[length];
final byte[] datas = new byte[length];
final byte[] amounts = new byte[length];
List<Tag> itemsTag = this.tag.getListTag("Items").getValue();
int length = itemsTag.size();
short[] ids = new short[length];
byte[] datas = new byte[length];
byte[] amounts = new byte[length];
for (int i = 0; i < length; i++) {
final Tag itemTag = itemsTag.get(i);
final CompoundTag itemComp = (CompoundTag) itemTag;
Tag itemTag = itemsTag.get(i);
CompoundTag itemComp = (CompoundTag) itemTag;
short id = itemComp.getShort("id");
String idStr = itemComp.getString("id");
if (idStr != null && !MathMan.isInteger(idStr)) {
@ -63,13 +62,13 @@ public class StateWrapper {
}
public CompoundTag getTag() {
if (tag != null) {
return tag;
if (this.tag != null) {
return this.tag;
}
if (state instanceof InventoryHolder) {
final InventoryHolder inv = (InventoryHolder) state;
final ItemStack[] contents = inv.getInventory().getContents();
final Map<String, Tag> values = new HashMap<>();
if (this.state instanceof InventoryHolder) {
InventoryHolder inv = (InventoryHolder) this.state;
ItemStack[] contents = inv.getInventory().getContents();
Map<String, Tag> values = new HashMap<>();
values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents)));
return new CompoundTag(values);
}
@ -80,11 +79,11 @@ public class StateWrapper {
return "Chest";
}
public List<CompoundTag> serializeInventory(final ItemStack[] items) {
final List<CompoundTag> tags = new ArrayList<>();
public List<CompoundTag> serializeInventory(ItemStack[] items) {
List<CompoundTag> tags = new ArrayList<>();
for (int i = 0; i < items.length; ++i) {
if (items[i] != null) {
final Map<String, Tag> tagData = serializeItem(items[i]);
Map<String, Tag> tagData = serializeItem(items[i]);
tagData.put("Slot", new ByteTag("Slot", (byte) i));
tags.add(new CompoundTag(tagData));
}
@ -104,20 +103,20 @@ public class StateWrapper {
}
*/
public Map<String, Tag> serializeItem(final ItemStack item) {
final Map<String, Tag> data = new HashMap<>();
public Map<String, Tag> serializeItem(ItemStack item) {
Map<String, Tag> data = new HashMap<>();
data.put("id", new ShortTag("id", (short) item.getTypeId()));
data.put("Damage", new ShortTag("Damage", item.getDurability()));
data.put("Count", new ByteTag("Count", (byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) {
final List<CompoundTag> enchantmentList = new ArrayList<>();
for (final Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
final Map<String, Tag> enchantment = new HashMap<>();
List<CompoundTag> enchantmentList = new ArrayList<>();
for (Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
Map<String, Tag> enchantment = new HashMap<>();
enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId()));
enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue()));
enchantmentList.add(new CompoundTag(enchantment));
}
final Map<String, Tag> auxData = new HashMap<>();
Map<String, Tag> auxData = new HashMap<>();
auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList));
data.put("tag", new CompoundTag("tag", auxData));
}

View File

@ -13,7 +13,6 @@ import java.util.Map;
/**
* [ PlotSquared DefaultTitleManager by Maxim Van de Wynckel ]
*
* @version 1.1.0
* @author Maxim Van de Wynckel
*
*/
@ -46,7 +45,7 @@ public class DefaultTitleManager {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title) throws ClassNotFoundException {
public DefaultTitleManager(String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
@ -60,48 +59,42 @@ public class DefaultTitleManager {
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title, final String subtitle) throws ClassNotFoundException {
public DefaultTitleManager(String title, String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title
* Copy 1.8 title.
*
* @param title
* Title
* @param title Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final DefaultTitleManager title) throws ClassNotFoundException {
public DefaultTitleManager(DefaultTitleManager title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
subtitle = title.subtitle;
titleColor = title.titleColor;
subtitleColor = title.subtitleColor;
fadeInTime = title.fadeInTime;
fadeOutTime = title.fadeOutTime;
stayTime = title.stayTime;
ticks = title.ticks;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
loadClasses();
}
/**
* Create a new 1.8 title
* Create a new 1.8 title.
*
* @param title
* Title text
* @param subtitle
* Subtitle text
* @param fadeInTime
* Fade in time
* @param stayTime
* Stay on screen time
* @param fadeOutTime
* Fade out time
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime)
public DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime)
throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
@ -111,7 +104,7 @@ public class DefaultTitleManager {
loadClasses();
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
@ -128,10 +121,10 @@ public class DefaultTitleManager {
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
packetTitle = getNMSClass("PacketPlayOutTitle");
packetActions = getNMSClass("EnumTitleAction");
chatBaseComponent = getNMSClass("IChatBaseComponent");
nmsChatSerializer = getNMSClass("ChatSerializer");
this.packetTitle = getNMSClass("PacketPlayOutTitle");
this.packetActions = getNMSClass("EnumTitleAction");
this.chatBaseComponent = getNMSClass("IChatBaseComponent");
this.nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
@ -140,7 +133,7 @@ public class DefaultTitleManager {
* @return Title text
*/
public String getTitle() {
return title;
return this.title;
}
/**
@ -149,7 +142,7 @@ public class DefaultTitleManager {
* @param title
* Title
*/
public void setTitle(final String title) {
public void setTitle(String title) {
this.title = title;
}
@ -159,190 +152,172 @@ public class DefaultTitleManager {
* @return Subtitle text
*/
public String getSubtitle() {
return subtitle;
return this.subtitle;
}
/**
* Set subtitle text
* Set subtitle text.
*
* @param subtitle
* Subtitle text
* @param subtitle Subtitle text
*/
public void setSubtitle(final String subtitle) {
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Set the title color
* Set the title color.
*
* @param color
* Chat color
* @param color Chat color
*/
public void setTitleColor(final ChatColor color) {
titleColor = color;
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Set the subtitle color
* Set the subtitle color.
*
* @param color
* Chat color
* @param color Chat color
*/
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Set title fade in time
* Set title fade in time.
*
* @param time
* Time
* @param time Time
*/
public void setFadeInTime(final int time) {
fadeInTime = time;
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Set title fade out time
* Set title fade out time.
*
* @param time
* Time
* @param time Time
*/
public void setFadeOutTime(final int time) {
fadeOutTime = time;
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Set title stay time
* Set title stay time.
*
* @param time
* Time
* @param time Time
*/
public void setStayTime(final int time) {
stayTime = time;
public void setStayTime(int time) {
this.stayTime = time;
}
/**
* Set timings to ticks
* Set timings to ticks.
*/
public void setTimingsToTicks() {
ticks = true;
this.ticks = true;
}
/**
* Set timings to seconds
* Set timings to seconds.
*/
public void setTimingsToSeconds() {
ticks = false;
this.ticks = false;
}
/**
* Send the title to a player
* Send the title to a player.
*
* @param player
* Player
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @param player Player
* @throws Exception
*/
public void send(final Player player)
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
if (packetTitle != null) {
public void send(Player player) throws Exception {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) {
if (this.fadeInTime != -1 && this.fadeOutTime != -1 && this.stayTime != -1) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!subtitle.isEmpty()) {
if (!this.subtitle.isEmpty()) {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[1], serialized);
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
/**
* Broadcast the title to all players
* @throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException
* Broadcast the title to all players.
*
* @throws Exception
*/
public void broadcast()
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
for (final Player p : Bukkit.getOnlinePlayers()) {
public void broadcast() throws Exception {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
* Clear the title.
*
* @param player
* Player
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @param player Player
* @throws Exception
*/
public void clearTitle(final Player player)
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
public void clearTitle(Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings
* Reset the title settings.
*
* @param player
* Player
* @param player Player
* @throws Exception
*/
public void resetTitle(final Player player)
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
public void resetTitle(Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private Object getHandle(final Object obj) {
private Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (IllegalAccessException e) {
@ -357,10 +332,10 @@ public class DefaultTitleManager {
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) {
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
@ -369,18 +344,18 @@ public class DefaultTitleManager {
}
private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName();
String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + ".";
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
final String fullName = "net.minecraft.server." + getVersion() + className;
private Class<?> getNMSClass(String className) throws ClassNotFoundException {
String fullName = "net.minecraft.server." + getVersion() + className;
return Class.forName(fullName);
}
private Field getField(final Class<?> clazz, final String name) {
private Field getField(Class<?> clazz, String name) {
try {
final Field field = clazz.getDeclaredField(name);
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
@ -392,8 +367,8 @@ public class DefaultTitleManager {
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
@ -402,7 +377,7 @@ public class DefaultTitleManager {
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}

View File

@ -18,6 +18,8 @@ import java.util.Map;
*
*/
public class DefaultTitleManager_183 {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -36,7 +38,6 @@ public class DefaultTitleManager_183 {
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/**
* Create a new 1.8 title
@ -45,7 +46,7 @@ public class DefaultTitleManager_183 {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title) throws ClassNotFoundException {
public DefaultTitleManager_183(String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
@ -59,7 +60,7 @@ public class DefaultTitleManager_183 {
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title, final String subtitle) throws ClassNotFoundException {
public DefaultTitleManager_183(String title, String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
@ -72,16 +73,16 @@ public class DefaultTitleManager_183 {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final DefaultTitleManager_183 title) throws ClassNotFoundException {
public DefaultTitleManager_183(DefaultTitleManager_183 title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
subtitle = title.subtitle;
titleColor = title.titleColor;
subtitleColor = title.subtitleColor;
fadeInTime = title.fadeInTime;
fadeOutTime = title.fadeOutTime;
stayTime = title.stayTime;
ticks = title.ticks;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
loadClasses();
}
@ -100,7 +101,7 @@ public class DefaultTitleManager_183 {
* Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
public DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -109,45 +110,47 @@ public class DefaultTitleManager_183 {
loadClasses();
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
packetTitle = getNMSClass("PacketPlayOutTitle");
chatBaseComponent = getNMSClass("IChatBaseComponent");
packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction");
nmsChatSerializer = getNMSClass("IChatBaseComponent$ChatSerializer");
this.packetTitle = getNMSClass("PacketPlayOutTitle");
this.chatBaseComponent = getNMSClass("IChatBaseComponent");
this.packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction");
this.nmsChatSerializer = getNMSClass("IChatBaseComponent$ChatSerializer");
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(final String title) {
this.title = title;
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle() {
return title;
return this.title;
}
/**
* Set subtitle text
* Set title text
*
* @param subtitle
* Subtitle text
* @param title
* Title
*/
public void setSubtitle(final String subtitle) {
this.subtitle = subtitle;
public void setTitle(String title) {
this.title = title;
}
/**
@ -156,7 +159,17 @@ public class DefaultTitleManager_183 {
* @return Subtitle text
*/
public String getSubtitle() {
return subtitle;
return this.subtitle;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
@ -165,8 +178,8 @@ public class DefaultTitleManager_183 {
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
titleColor = color;
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
@ -175,8 +188,8 @@ public class DefaultTitleManager_183 {
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
@ -185,8 +198,8 @@ public class DefaultTitleManager_183 {
* @param time
* Time
*/
public void setFadeInTime(final int time) {
fadeInTime = time;
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
@ -195,8 +208,8 @@ public class DefaultTitleManager_183 {
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
fadeOutTime = time;
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
@ -205,22 +218,22 @@ public class DefaultTitleManager_183 {
* @param time
* Time
*/
public void setStayTime(final int time) {
stayTime = time;
public void setStayTime(int time) {
this.stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
ticks = true;
this.ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
ticks = false;
this.ticks = false;
}
/**
@ -232,31 +245,39 @@ public class DefaultTitleManager_183 {
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player) throws Exception {
if (packetTitle != null) {
public void send(Player player) throws Exception {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle
.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null,
this.fadeInTime * (
this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1)) {
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!subtitle.isEmpty()) {
if (!this.subtitle.isEmpty()) {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[1], serialized);
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
@ -267,7 +288,7 @@ public class DefaultTitleManager_183 {
* @throws Exception
*/
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
@ -280,13 +301,13 @@ public class DefaultTitleManager_183 {
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player) throws Exception {
public void clearTitle(Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
@ -302,54 +323,42 @@ public class DefaultTitleManager_183 {
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void resetTitle(final Player player) throws Exception {
public void resetTitle(Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
private Object getHandle(final Object obj) {
private Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) {
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
@ -358,29 +367,29 @@ public class DefaultTitleManager_183 {
}
private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
String name = Bukkit.getServer().getClass().getPackage().getName();
String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
final String fullName = "net.minecraft.server." + getVersion() + className;
private Class<?> getNMSClass(String className) throws ClassNotFoundException {
String fullName = "net.minecraft.server." + getVersion() + className;
return Class.forName(fullName);
}
private Field getField(final Class<?> clazz, final String name) {
private Field getField(Class<?> clazz, String name) {
try {
final Field field = clazz.getDeclaredField(name);
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
@ -389,7 +398,7 @@ public class DefaultTitleManager_183 {
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}

View File

@ -360,10 +360,8 @@ public class BukkitChunkManager extends ChunkManager {
blockLocShortEntry.getKey().z + zOffset));
}
} catch (Exception e) {
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + xOffset) + "," +
blockLocShortEntry
.getKey().y + "," + (
blockLocShortEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + xOffset) + ","
+ blockLocShortEntry.getKey().y + "," + (blockLocShortEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, EntityType> blockLocEntityTypeEntry : spawnerData.entrySet()) {
@ -382,8 +380,8 @@ public class BukkitChunkManager extends ChunkManager {
blockLocEntityTypeEntry.getKey().z + zOffset));
}
} catch (Exception e) {
PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + xOffset) + "," +
blockLocEntityTypeEntry.getKey().y + "," + (blockLocEntityTypeEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ","
+ blockLocEntityTypeEntry.getKey().y + "," + (blockLocEntityTypeEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, String> blockLocStringEntry : cmdData.entrySet()) {
@ -490,8 +488,7 @@ public class BukkitChunkManager extends ChunkManager {
}
}
public static void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ,
boolean storeNormal) {
public static void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, boolean storeNormal) {
maxY = Math.min(255, maxY);
PlotBlock[] ids;
if (storeNormal) {

View File

@ -19,11 +19,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created 2015-02-20 for PlotSquared
*
*/
public class BukkitCommand implements CommandExecutor, TabCompleter {
public BukkitCommand() {

View File

@ -75,15 +75,6 @@ public class BukkitEconHandler extends EconHandler {
this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
public void setPermission(String world, String player, String perm, boolean value) {
if (value) {
this.perms.playerAdd(world, player, perm);
} else {
this.perms.playerRemove(world, player, perm);
}
}
@Override
public boolean hasPermission(String world, String player, String perm) {
return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);

View File

@ -87,7 +87,7 @@ public class Metrics {
*/
private volatile BukkitTask task = null;
public Metrics(Plugin plugin) throws IOException {
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
@ -280,7 +280,7 @@ public class Metrics {
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
public void enable() {
// Enable Task, if it is not running
if (this.task == null) {
start();
@ -290,9 +290,8 @@ public class Metrics {
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
public void disable() {
// Disable Task, if it is running
if (this.task != null) {
this.task.cancel();
@ -301,7 +300,8 @@ public class Metrics {
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
* Gets the File object of the config file that should be used to store
* data such as the GUID and opt-out status.
*
* @return the File object for the config file
*/
@ -318,7 +318,7 @@ public class Metrics {
}
/**
* Generic method that posts a plugin to the metrics website
* Generic method that posts a plugin to the metrics website.
*/
private void postPlugin(boolean isPing) throws IOException {
// Server software specific section

View File

@ -48,7 +48,7 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
}
/**
* Get the number of block changes in a specified section
* Get the number of block changes in a specified section.
* @param i
* @return
*/
@ -95,7 +95,7 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
}
/**
* Get the raw data for a section
* Get the raw data for a section.
* @param i
* @return
*/

View File

@ -48,7 +48,7 @@ public class FastChunk_1_9 extends PlotChunk<Chunk> {
}
/**
* Get the number of block changes in a specified section
* Get the number of block changes in a specified section.
* @param i
* @return
*/
@ -65,7 +65,7 @@ public class FastChunk_1_9 extends PlotChunk<Chunk> {
}
/**
* Get the number of block changes in a specified section
* Get the number of block changes in a specified section.
* @param i
* @return
*/
@ -95,7 +95,7 @@ public class FastChunk_1_9 extends PlotChunk<Chunk> {
}
/**
* Get the raw data for a section
* Get the raw data for a section.
* @param i
* @return
*/

View File

@ -39,7 +39,7 @@ public class FastQueue_1_7 extends SlowQueue {
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
public FastQueue_1_7() throws NoSuchMethodException, RuntimeException {
public FastQueue_1_7() throws RuntimeException {
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);

View File

@ -42,7 +42,7 @@ public class FastQueue_1_8 extends SlowQueue {
private final RefConstructor constructorBlockPosition;
private final SendChunk chunksender;
public FastQueue_1_8() throws NoSuchMethodException, RuntimeException {
public FastQueue_1_8() throws RuntimeException {
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class);

View File

@ -48,7 +48,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
private final RefField fieldWorld;
private final RefMethod methodGetIdArray;
public FastQueue_1_8_3() throws NoSuchMethodException, RuntimeException {
public FastQueue_1_8_3() throws RuntimeException {
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
RefClass classChunk = getRefClass("{nms}.Chunk");

View File

@ -8,6 +8,7 @@ import java.util.Set;
* Represents a section of a {@link Configuration}
*/
public interface ConfigurationSection {
/**
* Gets a set containing all keys in this section.
* <p>
@ -22,7 +23,7 @@ public interface ConfigurationSection {
* list.
* @return Set of keys contained within this ConfigurationSection.
*/
Set<String> getKeys(final boolean deep);
Set<String> getKeys(boolean deep);
/**
* Gets a Map containing all keys and their values for this section.
@ -38,7 +39,7 @@ public interface ConfigurationSection {
* list.
* @return Map of keys and values of this section.
*/
Map<String, Object> getValues(final boolean deep);
Map<String, Object> getValues(boolean deep);
/**
* Checks if this {@link ConfigurationSection} contains the given path.
@ -51,7 +52,7 @@ public interface ConfigurationSection {
* default or being set.
* @throws IllegalArgumentException Thrown when path is null.
*/
boolean contains(final String path);
boolean contains(String path);
/**
* Checks if this {@link ConfigurationSection} has a value set for the
@ -65,7 +66,7 @@ public interface ConfigurationSection {
* having a default.
* @throws IllegalArgumentException Thrown when path is null.
*/
boolean isSet(final String path);
boolean isSet(String path);
/**
* Gets the path of this {@link ConfigurationSection} from its root {@link
@ -132,7 +133,7 @@ public interface ConfigurationSection {
* @param path Path of the Object to get.
* @return Requested Object.
*/
Object get(final String path);
Object get(String path);
/**
* Gets the requested Object by path, returning a default value if not
@ -146,7 +147,7 @@ public interface ConfigurationSection {
* @param def The default value to return if the path is not found.
* @return Requested Object.
*/
Object get(final String path, final Object def);
Object get(String path, Object def);
/**
* Sets the specified path to the given value.
@ -162,7 +163,7 @@ public interface ConfigurationSection {
* @param path Path of the object to set.
* @param value New value to set the path to.
*/
void set(final String path, final Object value);
void set(String path, Object value);
/**
* Creates an empty {@link ConfigurationSection} at the specified path.
@ -174,7 +175,7 @@ public interface ConfigurationSection {
* @param path Path to create the section at.
* @return Newly created section
*/
ConfigurationSection createSection(final String path);
ConfigurationSection createSection(String path);
/**
* Creates a {@link ConfigurationSection} at the specified path, with
@ -188,9 +189,10 @@ public interface ConfigurationSection {
* @param map The values to used.
* @return Newly created section
*/
ConfigurationSection createSection(final String path, final Map<?, ?> map);
ConfigurationSection createSection(String path, Map<?, ?> map);
// Primitives
/**
* Gets the requested String by path.
* <p>
@ -201,7 +203,7 @@ public interface ConfigurationSection {
* @param path Path of the String to get.
* @return Requested String.
*/
String getString(final String path);
String getString(String path);
/**
* Gets the requested String by path, returning a default value if not
@ -216,59 +218,59 @@ public interface ConfigurationSection {
* not a String.
* @return Requested String.
*/
String getString(final String path, final String def);
String getString(String path, String def);
/**
* Checks if the specified path is a String.
* <p>
* If the path exists but is not a String, this will return false. If the
*
* <p> If the path exists but is not a String, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a String and return appropriately.
* value is a String and return appropriately.</p>
*
* @param path Path of the String to check.
* @return Whether or not the specified path is a String.
*/
boolean isString(final String path);
boolean isString(String path);
/**
* Gets the requested int by path.
* <p>
* If the int does not exist but a default value has been specified, this
*
* <p>If the int does not exist but a default value has been specified, this
* will return the default value. If the int does not exist and no default
* value was specified, this will return 0.
* value was specified, this will return 0.</p>
*
* @param path Path of the int to get.
* @return Requested int.
*/
int getInt(final String path);
int getInt(String path);
/**
* Gets the requested int by path, returning a default value if not found.
* <p>
* If the int does not exist then the specified default value will
*
* <p>If the int does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
* {@link Configuration}.</p>
*
* @param path Path of the int to get.
* @param def The default value to return if the path is not found or is
* not an int.
* @return Requested int.
*/
int getInt(final String path, final int def);
int getInt(String path, int def);
/**
* Checks if the specified path is an int.
* <p>
* If the path exists but is not a int, this will return false. If the
*
* <p>If the path exists but is not a int, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a int and return appropriately.
* value is a int and return appropriately.</p>
*
* @param path Path of the int to check.
* @return Whether or not the specified path is an int.
*/
boolean isInt(final String path);
boolean isInt(String path);
/**
* Gets the requested boolean by path.
@ -280,7 +282,7 @@ public interface ConfigurationSection {
* @param path Path of the boolean to get.
* @return Requested boolean.
*/
boolean getBoolean(final String path);
boolean getBoolean(String path);
/**
* Gets the requested boolean by path, returning a default value if not
@ -295,7 +297,7 @@ public interface ConfigurationSection {
* not a boolean.
* @return Requested boolean.
*/
boolean getBoolean(final String path, final boolean def);
boolean getBoolean(String path, boolean def);
/**
* Checks if the specified path is a boolean.
@ -308,7 +310,7 @@ public interface ConfigurationSection {
* @param path Path of the boolean to check.
* @return Whether or not the specified path is a boolean.
*/
boolean isBoolean(final String path);
boolean isBoolean(String path);
/**
* Gets the requested double by path.
@ -320,7 +322,7 @@ public interface ConfigurationSection {
* @param path Path of the double to get.
* @return Requested double.
*/
double getDouble(final String path);
double getDouble(String path);
/**
* Gets the requested double by path, returning a default value if not
@ -335,7 +337,7 @@ public interface ConfigurationSection {
* not a double.
* @return Requested double.
*/
double getDouble(final String path, final double def);
double getDouble(String path, double def);
/**
* Checks if the specified path is a double.
@ -348,7 +350,7 @@ public interface ConfigurationSection {
* @param path Path of the double to check.
* @return Whether or not the specified path is a double.
*/
boolean isDouble(final String path);
boolean isDouble(String path);
/**
* Gets the requested long by path.
@ -360,7 +362,7 @@ public interface ConfigurationSection {
* @param path Path of the long to get.
* @return Requested long.
*/
long getLong(final String path);
long getLong(String path);
/**
* Gets the requested long by path, returning a default value if not
@ -375,7 +377,7 @@ public interface ConfigurationSection {
* not a long.
* @return Requested long.
*/
long getLong(final String path, final long def);
long getLong(String path, long def);
/**
* Checks if the specified path is a long.
@ -388,9 +390,10 @@ public interface ConfigurationSection {
* @param path Path of the long to check.
* @return Whether or not the specified path is a long.
*/
boolean isLong(final String path);
boolean isLong(String path);
// Java
/**
* Gets the requested List by path.
* <p>
@ -401,7 +404,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List.
*/
List<?> getList(final String path);
List<?> getList(String path);
/**
* Gets the requested List by path, returning a default value if not
@ -416,7 +419,7 @@ public interface ConfigurationSection {
* not a List.
* @return Requested List.
*/
List<?> getList(final String path, final List<?> def);
List<?> getList(String path, List<?> def);
/**
* Checks if the specified path is a List.
@ -429,7 +432,7 @@ public interface ConfigurationSection {
* @param path Path of the List to check.
* @return Whether or not the specified path is a List.
*/
boolean isList(final String path);
boolean isList(String path);
/**
* Gets the requested List of String by path.
@ -444,7 +447,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of String.
*/
List<String> getStringList(final String path);
List<String> getStringList(String path);
/**
* Gets the requested List of Integer by path.
@ -459,7 +462,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Integer.
*/
List<Integer> getIntegerList(final String path);
List<Integer> getIntegerList(String path);
/**
* Gets the requested List of Boolean by path.
@ -474,7 +477,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Boolean.
*/
List<Boolean> getBooleanList(final String path);
List<Boolean> getBooleanList(String path);
/**
* Gets the requested List of Double by path.
@ -489,7 +492,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Double.
*/
List<Double> getDoubleList(final String path);
List<Double> getDoubleList(String path);
/**
* Gets the requested List of Float by path.
@ -504,7 +507,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Float.
*/
List<Float> getFloatList(final String path);
List<Float> getFloatList(String path);
/**
* Gets the requested List of Long by path.
@ -519,7 +522,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Long.
*/
List<Long> getLongList(final String path);
List<Long> getLongList(String path);
/**
* Gets the requested List of Byte by path.
@ -534,7 +537,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Byte.
*/
List<Byte> getByteList(final String path);
List<Byte> getByteList(String path);
/**
* Gets the requested List of Character by path.
@ -549,7 +552,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Character.
*/
List<Character> getCharacterList(final String path);
List<Character> getCharacterList(String path);
/**
* Gets the requested List of Short by path.
@ -564,7 +567,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Short.
*/
List<Short> getShortList(final String path);
List<Short> getShortList(String path);
/**
* Gets the requested List of Maps by path.
@ -579,7 +582,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Maps.
*/
List<Map<?, ?>> getMapList(final String path);
List<Map<?, ?>> getMapList(String path);
/**
* Gets the requested ConfigurationSection by path.
@ -592,7 +595,7 @@ public interface ConfigurationSection {
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection.
*/
ConfigurationSection getConfigurationSection(final String path);
ConfigurationSection getConfigurationSection(String path);
/**
* Checks if the specified path is a ConfigurationSection.
@ -606,7 +609,7 @@ public interface ConfigurationSection {
* @param path Path of the ConfigurationSection to check.
* @return Whether or not the specified path is a ConfigurationSection.
*/
boolean isConfigurationSection(final String path);
boolean isConfigurationSection(String path);
/**
* Gets the equivalent {@link ConfigurationSection} from the default
@ -638,5 +641,5 @@ public interface ConfigurationSection {
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
*/
void addDefault(final String path, final Object value);
void addDefault(String path, Object value);
}

View File

@ -11,6 +11,7 @@ import java.util.Set;
* A type of {@link ConfigurationSection} that is stored in memory.
*/
public class MemorySection implements ConfigurationSection {
protected final Map<String, Object> map = new LinkedHashMap<>();
private final Configuration root;
private final ConfigurationSection parent;
@ -32,10 +33,10 @@ public class MemorySection implements ConfigurationSection {
throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration");
}
path = "";
fullPath = "";
parent = null;
root = (Configuration) this;
this.path = "";
this.fullPath = "";
this.parent = null;
this.root = (Configuration) this;
}
/**
@ -47,7 +48,7 @@ public class MemorySection implements ConfigurationSection {
* @throws IllegalArgumentException Thrown is parent or path is null, or
* if parent contains no root Configuration.
*/
protected MemorySection(final ConfigurationSection parent, final String path) {
protected MemorySection(ConfigurationSection parent, String path) {
if (parent == null) {
throw new NullPointerException("Parent may not be null");
}
@ -57,16 +58,16 @@ public class MemorySection implements ConfigurationSection {
this.path = path;
this.parent = parent;
root = parent.getRoot();
this.root = parent.getRoot();
if (root == null) {
if (this.root == null) {
throw new NullPointerException("Path may not be orphaned");
}
fullPath = createPath(parent, path);
this.fullPath = createPath(parent, path);
}
public static double toDouble(final Object obj, final double def) {
public static double toDouble(Object obj, double def) {
if (obj instanceof Number) {
return ((Number) obj).doubleValue();
}
@ -76,7 +77,7 @@ public class MemorySection implements ConfigurationSection {
} catch (NumberFormatException ignored) {
}
} else if (obj instanceof List) {
final List<?> val = (List<?>) obj;
List<?> val = (List<?>) obj;
if (!val.isEmpty()) {
return toDouble(val.get(0), def);
}
@ -84,7 +85,7 @@ public class MemorySection implements ConfigurationSection {
return def;
}
public static int toInt(final Object obj, final int def) {
public static int toInt(Object obj, int def) {
if (obj instanceof Number) {
return ((Number) obj).intValue();
}
@ -94,7 +95,7 @@ public class MemorySection implements ConfigurationSection {
} catch (NumberFormatException ignored) {
}
} else if (obj instanceof List) {
final List<?> val = (List<?>) obj;
List<?> val = (List<?>) obj;
if (!val.isEmpty()) {
return toInt(val.get(0), def);
}
@ -102,7 +103,7 @@ public class MemorySection implements ConfigurationSection {
return def;
}
public static long toLong(final Object obj, final long def) {
public static long toLong(Object obj, long def) {
if (obj instanceof Number) {
return ((Number) obj).longValue();
}
@ -112,7 +113,7 @@ public class MemorySection implements ConfigurationSection {
} catch (NumberFormatException ignored) {
}
} else if (obj instanceof List) {
final List<?> val = (List<?>) obj;
List<?> val = (List<?>) obj;
if (!val.isEmpty()) {
return toLong(val.get(0), def);
}
@ -131,7 +132,7 @@ public class MemorySection implements ConfigurationSection {
* @param key Name of the specified section.
* @return Full path of the section from its root.
*/
public static String createPath(final ConfigurationSection section, final String key) {
public static String createPath(ConfigurationSection section, String key) {
return createPath(section, key, (section == null) ? null : section.getRoot());
}
@ -147,17 +148,17 @@ public class MemorySection implements ConfigurationSection {
* @param relativeTo Section to create the path relative to.
* @return Full path of the section from its root.
*/
public static String createPath(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo) {
public static String createPath(ConfigurationSection section, String key, ConfigurationSection relativeTo) {
if (section == null) {
throw new NullPointerException("Cannot create path without a section");
}
final Configuration root = section.getRoot();
Configuration root = section.getRoot();
if (root == null) {
throw new IllegalStateException("Cannot create path without a root");
}
final char separator = root.options().pathSeparator();
char separator = root.options().pathSeparator();
final StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder();
for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) {
if (builder.length() > 0) {
builder.insert(0, separator);
@ -178,12 +179,12 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public Set<String> getKeys(final boolean deep) {
final Set<String> result = new LinkedHashSet<>();
public Set<String> getKeys(boolean deep) {
Set<String> result = new LinkedHashSet<>();
final Configuration root = getRoot();
Configuration root = getRoot();
if ((root != null) && root.options().copyDefaults()) {
final ConfigurationSection defaults = getDefaultSection();
ConfigurationSection defaults = getDefaultSection();
if (defaults != null) {
result.addAll(defaults.getKeys(deep));
@ -196,12 +197,12 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public Map<String, Object> getValues(final boolean deep) {
final Map<String, Object> result = new LinkedHashMap<>();
public Map<String, Object> getValues(boolean deep) {
Map<String, Object> result = new LinkedHashMap<>();
final Configuration root = getRoot();
Configuration root = getRoot();
if ((root != null) && root.options().copyDefaults()) {
final ConfigurationSection defaults = getDefaultSection();
ConfigurationSection defaults = getDefaultSection();
if (defaults != null) {
result.putAll(defaults.getValues(deep));
@ -214,13 +215,13 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public boolean contains(final String path) {
public boolean contains(String path) {
return get(path) != null;
}
@Override
public boolean isSet(final String path) {
final Configuration root = getRoot();
public boolean isSet(String path) {
Configuration root = getRoot();
if (root == null) {
return false;
}
@ -232,31 +233,31 @@ public class MemorySection implements ConfigurationSection {
@Override
public String getCurrentPath() {
return fullPath;
return this.fullPath;
}
@Override
public String getName() {
return path;
return this.path;
}
@Override
public Configuration getRoot() {
return root;
return this.root;
}
@Override
public ConfigurationSection getParent() {
return parent;
return this.parent;
}
@Override
public void addDefault(final String path, final Object value) {
public void addDefault(String path, Object value) {
if (path == null) {
throw new NullPointerException("Path cannot be null");
}
final Configuration root = getRoot();
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot add default without root");
}
@ -268,8 +269,8 @@ public class MemorySection implements ConfigurationSection {
@Override
public ConfigurationSection getDefaultSection() {
final Configuration root = getRoot();
final Configuration defaults = root == null ? null : root.getDefaults();
Configuration root = getRoot();
Configuration defaults = root == null ? null : root.getDefaults();
if (defaults != null) {
if (defaults.isConfigurationSection(getCurrentPath())) {
@ -281,24 +282,24 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public void set(final String path, final Object value) {
public void set(String path, Object value) {
if (path == null) {
throw new NullPointerException("Cannot set to an empty path");
}
final Configuration root = getRoot();
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot use section without a root");
}
final char separator = root.options().pathSeparator();
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
final String node = path.substring(i2, i1);
final ConfigurationSection subSection = section.getConfigurationSection(node);
String node = path.substring(i2, i1);
ConfigurationSection subSection = section.getConfigurationSection(node);
if (subSection == null) {
section = section.createSection(node);
} else {
@ -306,12 +307,12 @@ public class MemorySection implements ConfigurationSection {
}
}
final String key = path.substring(i2);
String key = path.substring(i2);
if (section == this) {
if (value == null) {
map.remove(key);
this.map.remove(key);
} else {
map.put(key, value);
this.map.put(key, value);
}
} else {
section.set(key, value);
@ -319,12 +320,12 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public Object get(final String path) {
public Object get(String path) {
return get(path, getDefault(path));
}
@Override
public Object get(final String path, final Object def) {
public Object get(String path, Object def) {
if (path == null) {
throw new NullPointerException("Path cannot be null");
}
@ -333,15 +334,16 @@ public class MemorySection implements ConfigurationSection {
return this;
}
final Configuration root = getRoot();
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot access section without a root");
}
final char separator = root.options().pathSeparator();
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
int i1 = -1;
int i2;
ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
section = section.getConfigurationSection(path.substring(i2, i1));
@ -350,32 +352,36 @@ public class MemorySection implements ConfigurationSection {
}
}
final String key = path.substring(i2);
String key = path.substring(i2);
if (section == this) {
final Object result = map.get(key);
return (result == null) ? def : result;
Object result = this.map.get(key);
if (result == null) {
return def;
} else {
return result;
}
}
return section.get(key, def);
}
@Override
public ConfigurationSection createSection(final String path) {
public ConfigurationSection createSection(String path) {
if (path == null) {
throw new NullPointerException("Cannot create section at empty path");
}
final Configuration root = getRoot();
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot create section without a root");
}
final char separator = root.options().pathSeparator();
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
final String node = path.substring(i2, i1);
final ConfigurationSection subSection = section.getConfigurationSection(node);
String node = path.substring(i2, i1);
ConfigurationSection subSection = section.getConfigurationSection(node);
if (subSection == null) {
section = section.createSection(node);
} else {
@ -383,20 +389,20 @@ public class MemorySection implements ConfigurationSection {
}
}
final String key = path.substring(i2);
String key = path.substring(i2);
if (section == this) {
final ConfigurationSection result = new MemorySection(this, key);
map.put(key, result);
ConfigurationSection result = new MemorySection(this, key);
this.map.put(key, result);
return result;
}
return section.createSection(key);
}
@Override
public ConfigurationSection createSection(final String path, final Map<?, ?> map) {
final ConfigurationSection section = createSection(path);
public ConfigurationSection createSection(String path, Map<?, ?> map) {
ConfigurationSection section = createSection(path);
for (final Map.Entry<?, ?> entry : map.entrySet()) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
section.createSection(entry.getKey().toString(), (Map<?, ?>) entry.getValue());
} else {
@ -409,125 +415,137 @@ public class MemorySection implements ConfigurationSection {
// Primitives
@Override
public String getString(final String path) {
final Object def = getDefault(path);
public String getString(String path) {
Object def = getDefault(path);
return getString(path, def != null ? def.toString() : null);
}
@Override
public String getString(final String path, final String def) {
final Object val = get(path, def);
return (val != null) ? val.toString() : def;
public String getString(String path, String def) {
Object val = get(path, def);
if (val != null) {
return val.toString();
} else {
return def;
}
}
@Override
public boolean isString(final String path) {
final Object val = get(path);
public boolean isString(String path) {
Object val = get(path);
return val instanceof String;
}
@Override
public int getInt(final String path) {
final Object def = getDefault(path);
public int getInt(String path) {
Object def = getDefault(path);
return getInt(path, toInt(def, 0));
}
@Override
public int getInt(final String path, final int def) {
final Object val = get(path, def);
public int getInt(String path, int def) {
Object val = get(path, def);
return toInt(val, def);
}
@Override
public boolean isInt(final String path) {
final Object val = get(path);
public boolean isInt(String path) {
Object val = get(path);
return val instanceof Integer;
}
@Override
public boolean getBoolean(final String path) {
final Object def = getDefault(path);
return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false);
public boolean getBoolean(String path) {
Object def = getDefault(path);
if (def instanceof Boolean) {
return getBoolean(path, (Boolean) def);
} else {
return getBoolean(path, false);
}
}
@Override
public boolean getBoolean(final String path, final boolean def) {
final Object val = get(path, def);
return (val instanceof Boolean) ? (Boolean) val : def;
public boolean getBoolean(String path, boolean def) {
Object val = get(path, def);
if (val instanceof Boolean) {
return (Boolean) val;
} else {
return def;
}
}
@Override
public boolean isBoolean(final String path) {
final Object val = get(path);
public boolean isBoolean(String path) {
Object val = get(path);
return val instanceof Boolean;
}
@Override
public double getDouble(final String path) {
final Object def = getDefault(path);
public double getDouble(String path) {
Object def = getDefault(path);
return getDouble(path, toDouble(def, 0));
}
@Override
public double getDouble(final String path, final double def) {
final Object val = get(path, def);
public double getDouble(String path, double def) {
Object val = get(path, def);
return toDouble(val, def);
}
@Override
public boolean isDouble(final String path) {
final Object val = get(path);
public boolean isDouble(String path) {
Object val = get(path);
return val instanceof Double;
}
@Override
public long getLong(final String path) {
final Object def = getDefault(path);
public long getLong(String path) {
Object def = getDefault(path);
return getLong(path, toLong(def, 0));
}
@Override
public long getLong(final String path, final long def) {
final Object val = get(path, def);
public long getLong(String path, long def) {
Object val = get(path, def);
return toLong(val, def);
}
@Override
public boolean isLong(final String path) {
final Object val = get(path);
public boolean isLong(String path) {
Object val = get(path);
return val instanceof Long;
}
// Java
@Override
public List<?> getList(final String path) {
final Object def = getDefault(path);
return getList(path, (def instanceof List) ? (List<?>) def : null);
public List<?> getList(String path) {
Object def = getDefault(path);
return getList(path, def instanceof List ? (List<?>) def : null);
}
@Override
public List<?> getList(final String path, final List<?> def) {
final Object val = get(path, def);
public List<?> getList(String path, List<?> def) {
Object val = get(path, def);
return (List<?>) ((val instanceof List) ? val : def);
}
@Override
public boolean isList(final String path) {
final Object val = get(path);
public boolean isList(String path) {
Object val = get(path);
return val instanceof List;
}
@Override
public List<String> getStringList(final String path) {
final List<?> list = getList(path);
public List<String> getStringList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<String> result = new ArrayList<>();
List<String> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if ((object instanceof String) || isPrimitiveWrapper(object)) {
result.add(String.valueOf(object));
}
@ -537,16 +555,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Integer> getIntegerList(final String path) {
final List<?> list = getList(path);
public List<Integer> getIntegerList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Integer> result = new ArrayList<>();
List<Integer> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Integer) {
result.add((Integer) object);
} else if (object instanceof String) {
@ -565,16 +583,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Boolean> getBooleanList(final String path) {
final List<?> list = getList(path);
public List<Boolean> getBooleanList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Boolean> result = new ArrayList<>();
List<Boolean> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Boolean) {
result.add((Boolean) object);
} else if (object instanceof String) {
@ -590,16 +608,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Double> getDoubleList(final String path) {
final List<?> list = getList(path);
public List<Double> getDoubleList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Double> result = new ArrayList<>();
List<Double> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Double) {
result.add((Double) object);
} else if (object instanceof String) {
@ -618,16 +636,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Float> getFloatList(final String path) {
final List<?> list = getList(path);
public List<Float> getFloatList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Float> result = new ArrayList<>();
List<Float> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Float) {
result.add((Float) object);
} else if (object instanceof String) {
@ -646,16 +664,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Long> getLongList(final String path) {
final List<?> list = getList(path);
public List<Long> getLongList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Long> result = new ArrayList<>();
List<Long> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Long) {
result.add((Long) object);
} else if (object instanceof String) {
@ -674,16 +692,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Byte> getByteList(final String path) {
final List<?> list = getList(path);
public List<Byte> getByteList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Byte> result = new ArrayList<>();
List<Byte> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Byte) {
result.add((Byte) object);
} else if (object instanceof String) {
@ -702,20 +720,20 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Character> getCharacterList(final String path) {
final List<?> list = getList(path);
public List<Character> getCharacterList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Character> result = new ArrayList<>();
List<Character> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Character) {
result.add((Character) object);
} else if (object instanceof String) {
final String str = (String) object;
String str = (String) object;
if (str.length() == 1) {
result.add(str.charAt(0));
@ -729,16 +747,16 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Short> getShortList(final String path) {
final List<?> list = getList(path);
public List<Short> getShortList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Short> result = new ArrayList<>();
List<Short> result = new ArrayList<>();
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Short) {
result.add((Short) object);
} else if (object instanceof String) {
@ -757,15 +775,15 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public List<Map<?, ?>> getMapList(final String path) {
final List<?> list = getList(path);
final List<Map<?, ?>> result = new ArrayList<>();
public List<Map<?, ?>> getMapList(String path) {
List<?> list = getList(path);
List<Map<?, ?>> result = new ArrayList<>();
if (list == null) {
return result;
}
for (final Object object : list) {
for (Object object : list) {
if (object instanceof Map) {
result.add((Map<?, ?>) object);
}
@ -775,7 +793,7 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public ConfigurationSection getConfigurationSection(final String path) {
public ConfigurationSection getConfigurationSection(String path) {
Object val = get(path, null);
if (val != null) {
return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
@ -786,12 +804,12 @@ public class MemorySection implements ConfigurationSection {
}
@Override
public boolean isConfigurationSection(final String path) {
final Object val = get(path);
public boolean isConfigurationSection(String path) {
Object val = get(path);
return val instanceof ConfigurationSection;
}
protected boolean isPrimitiveWrapper(final Object input) {
protected boolean isPrimitiveWrapper(Object input) {
return (input instanceof Integer)
|| (input instanceof Boolean)
|| (input instanceof Character)
@ -802,42 +820,42 @@ public class MemorySection implements ConfigurationSection {
|| (input instanceof Float);
}
protected Object getDefault(final String path) {
protected Object getDefault(String path) {
if (path == null) {
throw new NullPointerException("Path may not be null");
}
final Configuration root = getRoot();
final Configuration defaults = root == null ? null : root.getDefaults();
Configuration root = getRoot();
Configuration defaults = root == null ? null : root.getDefaults();
return (defaults == null) ? null : defaults.get(createPath(this, path));
}
protected void mapChildrenKeys(final Set<String> output, final ConfigurationSection section, final boolean deep) {
protected void mapChildrenKeys(Set<String> output, ConfigurationSection section, boolean deep) {
if (section instanceof MemorySection) {
final MemorySection sec = (MemorySection) section;
MemorySection sec = (MemorySection) section;
for (final Map.Entry<String, Object> entry : sec.map.entrySet()) {
for (Map.Entry<String, Object> entry : sec.map.entrySet()) {
output.add(createPath(section, entry.getKey(), this));
if (deep && (entry.getValue() instanceof ConfigurationSection)) {
final ConfigurationSection subsection = (ConfigurationSection) entry.getValue();
ConfigurationSection subsection = (ConfigurationSection) entry.getValue();
mapChildrenKeys(output, subsection, deep);
}
}
} else {
final Set<String> keys = section.getKeys(deep);
Set<String> keys = section.getKeys(deep);
for (final String key : keys) {
for (String key : keys) {
output.add(createPath(section, key, this));
}
}
}
protected void mapChildrenValues(final Map<String, Object> output, final ConfigurationSection section, final boolean deep) {
protected void mapChildrenValues(Map<String, Object> output, ConfigurationSection section, boolean deep) {
if (section instanceof MemorySection) {
final MemorySection sec = (MemorySection) section;
MemorySection sec = (MemorySection) section;
for (final Map.Entry<String, Object> entry : sec.map.entrySet()) {
for (Map.Entry<String, Object> entry : sec.map.entrySet()) {
output.put(createPath(section, entry.getKey(), this), entry.getValue());
if (entry.getValue() instanceof ConfigurationSection) {
@ -847,9 +865,9 @@ public class MemorySection implements ConfigurationSection {
}
}
} else {
final Map<String, Object> values = section.getValues(deep);
Map<String, Object> values = section.getValues(deep);
for (final Map.Entry<String, Object> entry : values.entrySet()) {
for (Map.Entry<String, Object> entry : values.entrySet()) {
output.put(createPath(section, entry.getKey(), this), entry.getValue());
}
}
@ -857,7 +875,7 @@ public class MemorySection implements ConfigurationSection {
@Override
public String toString() {
final Configuration root = getRoot();
Configuration root = getRoot();
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + (root == null ? null : root.getClass().getSimpleName()) +
"']";
}

View File

@ -15,17 +15,164 @@ import java.util.logging.Logger;
* Utility class for storing and retrieving classes for {@link Configuration}.
*/
public class ConfigurationSerialization {
public static final String SERIALIZED_TYPE_KEY = "==";
private final Class<? extends ConfigurationSerializable> clazz;
private static Map<String, Class<? extends ConfigurationSerializable>> aliases = new HashMap<String, Class<? extends ConfigurationSerializable>>();
protected ConfigurationSerialization(final Class<? extends ConfigurationSerializable> clazz) {
public static final String SERIALIZED_TYPE_KEY = "==";
private static final Map<String, Class<? extends ConfigurationSerializable>> aliases =
new HashMap<String, Class<? extends ConfigurationSerializable>>();
private final Class<? extends ConfigurationSerializable> clazz;
protected ConfigurationSerialization(Class<? extends ConfigurationSerializable> clazz) {
this.clazz = clazz;
}
protected Method getMethod(final String name, final boolean isStatic) {
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
*
* <p>The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.</p>
*
* <p>If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.</p>
*
* @param args Arguments for deserialization
* @param clazz Class to deserialize into
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(Map<String, ?> args, Class<? extends ConfigurationSerializable> clazz) {
return new ConfigurationSerialization(clazz).deserialize(args);
}
/**
* Attempts to deserialize the given arguments into a new instance of the
*
* given class.
* <p>
* The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.</p>
*
* <p>
* If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.</p>
*
* @param args Arguments for deserialization
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(Map<String, ?> args) {
Class<? extends ConfigurationSerializable> clazz = null;
if (args.containsKey(SERIALIZED_TYPE_KEY)) {
try {
final Method method = clazz.getDeclaredMethod(name, Map.class);
String alias = (String) args.get(SERIALIZED_TYPE_KEY);
if (alias == null) {
throw new IllegalArgumentException("Cannot have null alias");
}
clazz = getClassByAlias(alias);
if (clazz == null) {
throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
}
} catch (ClassCastException ex) {
ex.fillInStackTrace();
throw ex;
}
} else {
throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
}
return new ConfigurationSerialization(clazz).deserialize(args);
}
/**
* Registers the given {@link ConfigurationSerializable} class by its
* alias.
*
* @param clazz Class to register
*/
public static void registerClass(Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate == null) {
registerClass(clazz, getAlias(clazz));
registerClass(clazz, clazz.getName());
}
}
/**
* Registers the given alias to the specified {@link
* ConfigurationSerializable} class.
*
* @param clazz Class to register
* @param alias Alias to register as
* @see SerializableAs
*/
public static void registerClass(Class<? extends ConfigurationSerializable> clazz, String alias) {
aliases.put(alias, clazz);
}
/**
* Unregisters the specified alias to a {@link ConfigurationSerializable}
*
* @param alias Alias to unregister
*/
public static void unregisterClass(String alias) {
aliases.remove(alias);
}
/**
* Unregisters any aliases for the specified {@link
* ConfigurationSerializable} class.
*
* @param clazz Class to unregister
*/
public static void unregisterClass(Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) {
}
}
/**
* Attempts to get a registered {@link ConfigurationSerializable} class by
* its alias.
*
* @param alias Alias of the serializable
* @return Registered class, or null if not found
*/
public static Class<? extends ConfigurationSerializable> getClassByAlias(String alias) {
return aliases.get(alias);
}
/**
* Gets the correct alias for the given {@link ConfigurationSerializable}
* class.
*
* @param clazz Class to get alias for
* @return Alias to use for the class
*/
public static String getAlias(Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate != null) {
if ((delegate.value() == null) || (delegate.value() == clazz)) {
delegate = null;
} else {
return getAlias(delegate.value());
}
}
SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
if (alias != null) {
return alias.value();
}
return clazz.getName();
}
protected Method getMethod(String name, boolean isStatic) {
try {
Method method = this.clazz.getDeclaredMethod(name, Map.class);
if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) {
return null;
@ -35,53 +182,57 @@ public class ConfigurationSerialization {
}
return method;
} catch (final NoSuchMethodException ex) {
} catch (NoSuchMethodException ex) {
return null;
} catch (final SecurityException ex) {
} catch (SecurityException ex) {
return null;
}
}
protected Constructor<? extends ConfigurationSerializable> getConstructor() {
try {
return clazz.getConstructor(Map.class);
} catch (final NoSuchMethodException ex) {
return this.clazz.getConstructor(Map.class);
} catch (NoSuchMethodException ex) {
return null;
} catch (final SecurityException ex) {
} catch (SecurityException ex) {
return null;
}
}
protected ConfigurationSerializable deserializeViaMethod(final Method method, final Map<String, ?> args) {
protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, ?> args) {
try {
final ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
if (result == null) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null");
"Could not call method '" + method.toString() + "' of " + this.clazz + " for deserialization: method returned null");
} else {
return result;
}
} catch (final Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
} catch (Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName())
.log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + this.clazz
+ " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
return null;
}
protected ConfigurationSerializable deserializeViaCtor(final Constructor<? extends ConfigurationSerializable> ctor, final Map<String, ?> args) {
protected ConfigurationSerializable deserializeViaCtor(Constructor<? extends ConfigurationSerializable> ctor, Map<String, ?> args) {
try {
return ctor.newInstance(args);
} catch (final Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
} catch (Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName())
.log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + this.clazz
+ " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
return null;
}
public ConfigurationSerializable deserialize(final Map<String, ?> args) {
public ConfigurationSerializable deserialize(Map<String, ?> args) {
if (args == null) {
throw new NullPointerException("Args must not be null");
}
@ -101,7 +252,7 @@ public class ConfigurationSerialization {
}
if (result == null) {
final Constructor<? extends ConfigurationSerializable> constructor = getConstructor();
Constructor<? extends ConfigurationSerializable> constructor = getConstructor();
if (constructor != null) {
result = deserializeViaCtor(constructor, args);
@ -110,146 +261,4 @@ public class ConfigurationSerialization {
return result;
}
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
* <p>
* The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.
* <p>
* If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.
*
* @param args Arguments for deserialization
* @param clazz Class to deserialize into
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(final Map<String, ?> args, final Class<? extends ConfigurationSerializable> clazz) {
return new ConfigurationSerialization(clazz).deserialize(args);
}
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
* <p>
* The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.
* <p>
* If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.
*
* @param args Arguments for deserialization
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(final Map<String, ?> args) {
Class<? extends ConfigurationSerializable> clazz = null;
if (args.containsKey(SERIALIZED_TYPE_KEY)) {
try {
final String alias = (String) args.get(SERIALIZED_TYPE_KEY);
if (alias == null) {
throw new IllegalArgumentException("Cannot have null alias");
}
clazz = getClassByAlias(alias);
if (clazz == null) {
throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
}
} catch (final ClassCastException ex) {
ex.fillInStackTrace();
throw ex;
}
} else {
throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
}
return new ConfigurationSerialization(clazz).deserialize(args);
}
/**
* Registers the given {@link ConfigurationSerializable} class by its
* alias
*
* @param clazz Class to register
*/
public static void registerClass(final Class<? extends ConfigurationSerializable> clazz) {
final DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate == null) {
registerClass(clazz, getAlias(clazz));
registerClass(clazz, clazz.getName());
}
}
/**
* Registers the given alias to the specified {@link
* ConfigurationSerializable} class
*
* @param clazz Class to register
* @param alias Alias to register as
* @see SerializableAs
*/
public static void registerClass(final Class<? extends ConfigurationSerializable> clazz, final String alias) {
aliases.put(alias, clazz);
}
/**
* Unregisters the specified alias to a {@link ConfigurationSerializable}
*
* @param alias Alias to unregister
*/
public static void unregisterClass(final String alias) {
aliases.remove(alias);
}
/**
* Unregisters any aliases for the specified {@link
* ConfigurationSerializable} class
*
* @param clazz Class to unregister
*/
public static void unregisterClass(final Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) {}
}
/**
* Attempts to get a registered {@link ConfigurationSerializable} class by
* its alias
*
* @param alias Alias of the serializable
* @return Registered class, or null if not found
*/
public static Class<? extends ConfigurationSerializable> getClassByAlias(final String alias) {
return aliases.get(alias);
}
/**
* Gets the correct alias for the given {@link ConfigurationSerializable}
* class
*
* @param clazz Class to get alias for
* @return Alias to use for the class
*/
public static String getAlias(final Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate != null) {
if ((delegate.value() == null) || (delegate.value() == clazz)) {
delegate = null;
} else {
return getAlias(delegate.value());
}
}
final SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
if (alias != null) {
return alias.value();
}
return clazz.getName();
}
}

View File

@ -9,6 +9,7 @@ import java.util.Map;
* The {@code TAG_Compound} tag.
*/
public final class CompoundTag extends Tag {
private Map<String, Tag> value;
/**
@ -16,7 +17,7 @@ public final class CompoundTag extends Tag {
*
* @param value the value of the tag
*/
public CompoundTag(final Map<String, Tag> value) {
public CompoundTag(Map<String, Tag> value) {
super();
this.value = Collections.unmodifiableMap(value);
}
@ -27,7 +28,7 @@ public final class CompoundTag extends Tag {
* @param name the name of the tag
* @param value the value of the tag
*/
public CompoundTag(final String name, final Map<String, Tag> value) {
public CompoundTag(String name, Map<String, Tag> value) {
super(name);
this.value = Collections.unmodifiableMap(value);
}
@ -39,13 +40,13 @@ public final class CompoundTag extends Tag {
*
* @return true if the tag contains the given key
*/
public boolean containsKey(final String key) {
return value.containsKey(key);
public boolean containsKey(String key) {
return this.value.containsKey(key);
}
@Override
public Map<String, Tag> getValue() {
return value;
return this.value;
}
/**
@ -55,11 +56,10 @@ public final class CompoundTag extends Tag {
*
* @return the new compound tag
*/
public CompoundTag setValue(final Map<String, Tag> value) {
public CompoundTag setValue(Map<String, Tag> value) {
if (value == null) {
this.value = Collections.unmodifiableMap(new HashMap<String, Tag>());
}
else {
} else {
this.value = Collections.unmodifiableMap(value);
}
return this;
@ -71,19 +71,21 @@ public final class CompoundTag extends Tag {
* @return the builder
*/
public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(value));
return new CompoundTagBuilder(new HashMap<String, Tag>(this.value));
}
/**
* Get a byte array named with the given key. <p> If the key does not exist or its value is not a byte array
* Get a byte array named with the given key.
*
* <p> If the key does not exist or its value is not a byte array
* tag, then an empty byte array will be returned. </p>
*
* @param key the key
*
* @return a byte array
*/
public byte[] getByteArray(final String key) {
final Tag tag = value.get(key);
public byte[] getByteArray(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
} else {
@ -99,8 +101,8 @@ public final class CompoundTag extends Tag {
*
* @return a byte
*/
public byte getByte(final String key) {
final Tag tag = value.get(key);
public byte getByte(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else {
@ -116,8 +118,8 @@ public final class CompoundTag extends Tag {
*
* @return a double
*/
public double getDouble(final String key) {
final Tag tag = value.get(key);
public double getDouble(String key) {
Tag tag = this.value.get(key);
if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
@ -133,8 +135,8 @@ public final class CompoundTag extends Tag {
*
* @return a double
*/
public double asDouble(final String key) {
final Tag tag = value.get(key);
public double asDouble(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
@ -160,8 +162,8 @@ public final class CompoundTag extends Tag {
*
* @return a float
*/
public float getFloat(final String key) {
final Tag tag = value.get(key);
public float getFloat(String key) {
Tag tag = this.value.get(key);
if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else {
@ -177,8 +179,8 @@ public final class CompoundTag extends Tag {
*
* @return an int array
*/
public int[] getIntArray(final String key) {
final Tag tag = value.get(key);
public int[] getIntArray(String key) {
Tag tag = this.value.get(key);
if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
} else {
@ -194,8 +196,8 @@ public final class CompoundTag extends Tag {
*
* @return an int
*/
public int getInt(final String key) {
final Tag tag = value.get(key);
public int getInt(String key) {
Tag tag = this.value.get(key);
if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else {
@ -211,8 +213,8 @@ public final class CompoundTag extends Tag {
*
* @return an int
*/
public int asInt(final String key) {
final Tag tag = value.get(key);
public int asInt(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
@ -238,8 +240,8 @@ public final class CompoundTag extends Tag {
*
* @return a list of tags
*/
public List<Tag> getList(final String key) {
final Tag tag = value.get(key);
public List<Tag> getList(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
} else {
@ -255,12 +257,12 @@ public final class CompoundTag extends Tag {
*
* @return a tag list instance
*/
public ListTag getListTag(final String key) {
final Tag tag = value.get(key);
public ListTag getListTag(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ListTag) {
return (ListTag) tag;
} else {
return new ListTag(key, StringTag.class, Collections.<Tag> emptyList());
return new ListTag(key, StringTag.class, Collections.<Tag>emptyList());
}
}
@ -276,10 +278,10 @@ public final class CompoundTag extends Tag {
* @return a list of tags
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(final String key, final Class<T> listType) {
final Tag tag = value.get(key);
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
Tag tag = this.value.get(key);
if (tag instanceof ListTag) {
final ListTag listTag = (ListTag) tag;
ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
@ -298,8 +300,8 @@ public final class CompoundTag extends Tag {
*
* @return a long
*/
public long getLong(final String key) {
final Tag tag = value.get(key);
public long getLong(String key) {
Tag tag = this.value.get(key);
if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else {
@ -315,8 +317,8 @@ public final class CompoundTag extends Tag {
*
* @return a long
*/
public long asLong(final String key) {
final Tag tag = value.get(key);
public long asLong(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
@ -342,8 +344,8 @@ public final class CompoundTag extends Tag {
*
* @return a short
*/
public short getShort(final String key) {
final Tag tag = value.get(key);
public short getShort(String key) {
Tag tag = this.value.get(key);
if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else {
@ -359,8 +361,8 @@ public final class CompoundTag extends Tag {
*
* @return a string
*/
public String getString(final String key) {
final Tag tag = value.get(key);
public String getString(String key) {
Tag tag = this.value.get(key);
if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
} else {
@ -370,14 +372,14 @@ public final class CompoundTag extends Tag {
@Override
public String toString() {
final String name = getName();
String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n");
for (final Map.Entry<String, Tag> entry : value.entrySet()) {
StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n");
for (Map.Entry<String, Tag> entry : this.value.entrySet()) {
bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");

View File

@ -18,6 +18,7 @@ package com.intellectualcrafters.json;
* @version 2014-05-03
*/
public class CDL {
/**
* Get the next value. The value can be wrapped in quotes. The value can be empty.
*
@ -27,7 +28,7 @@ public class CDL {
*
* @throws JSONException if the quoted string is badly formed.
*/
private static String getValue(final JSONTokener x) throws JSONException {
private static String getValue(JSONTokener x) throws JSONException {
char c;
char q;
StringBuffer sb;
@ -41,7 +42,7 @@ public class CDL {
case '\'':
q = c;
sb = new StringBuffer();
for (;;) {
for (; ; ) {
c = x.next();
if (c == q) {
break;
@ -70,16 +71,16 @@ public class CDL {
*
* @throws JSONException
*/
public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException {
final JSONArray ja = new JSONArray();
for (;;) {
final String value = getValue(x);
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray();
for (; ; ) {
String value = getValue(x);
char c = x.next();
if ((value == null) || ((ja.length() == 0) && (value.isEmpty()) && (c != ','))) {
if ((value == null) || ((ja.length() == 0) && value.isEmpty() && (c != ','))) {
return null;
}
ja.put(value);
for (;;) {
for (; ; ) {
if (c == ',') {
break;
}
@ -106,8 +107,8 @@ public class CDL {
*
* @throws JSONException
*/
public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException {
final JSONArray ja = rowToJSONArray(x);
public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException {
JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null;
}
@ -119,21 +120,21 @@ public class CDL {
*
* @return A string ending in NEWLINE.
*/
public static String rowToString(final JSONArray ja) {
final StringBuilder sb = new StringBuilder();
public static String rowToString(JSONArray ja) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ja.length(); i += 1) {
if (i > 0) {
sb.append(',');
}
final Object object = ja.opt(i);
Object object = ja.opt(i);
if (object != null) {
final String string = object.toString();
if ((!string.isEmpty()) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (
String string = object.toString();
if (!string.isEmpty() && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (
string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
sb.append('"');
final int length = string.length();
int length = string.length();
for (int j = 0; j < length; j += 1) {
final char c = string.charAt(j);
char c = string.charAt(j);
if ((c >= ' ') && (c != '"')) {
sb.append(c);
}
@ -157,7 +158,7 @@ public class CDL {
*
* @throws JSONException
*/
public static JSONArray toJSONArray(final String string) throws JSONException {
public static JSONArray toJSONArray(String string) throws JSONException {
return toJSONArray(new JSONTokener(string));
}
@ -170,7 +171,7 @@ public class CDL {
*
* @throws JSONException
*/
public static JSONArray toJSONArray(final JSONTokener x) throws JSONException {
public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
return toJSONArray(rowToJSONArray(x), x);
}
@ -185,7 +186,7 @@ public class CDL {
*
* @throws JSONException
*/
public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException {
public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException {
return toJSONArray(names, new JSONTokener(string));
}
@ -200,13 +201,13 @@ public class CDL {
*
* @throws JSONException
*/
public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException {
public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException {
if ((names == null) || (names.length() == 0)) {
return null;
}
final JSONArray ja = new JSONArray();
for (;;) {
final JSONObject jo = rowToJSONObject(names, x);
JSONArray ja = new JSONArray();
for (; ; ) {
JSONObject jo = rowToJSONObject(names, x);
if (jo == null) {
break;
}
@ -228,10 +229,10 @@ public class CDL {
*
* @throws JSONException
*/
public static String toString(final JSONArray ja) throws JSONException {
final JSONObject jo = ja.optJSONObject(0);
public static String toString(JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0);
if (jo != null) {
final JSONArray names = jo.names();
JSONArray names = jo.names();
if (names != null) {
return rowToString(names) + toString(names, ja);
}
@ -250,13 +251,13 @@ public class CDL {
*
* @throws JSONException
*/
public static String toString(final JSONArray names, final JSONArray ja) throws JSONException {
public static String toString(JSONArray names, JSONArray ja) throws JSONException {
if ((names == null) || (names.length() == 0)) {
return null;
}
final StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ja.length(); i += 1) {
final JSONObject jo = ja.optJSONObject(i);
JSONObject jo = ja.optJSONObject(i);
if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names)));
}

View File

@ -2443,7 +2443,8 @@ public class PS {
}
/**
* Get a list of PlotArea objects
* Get a list of PlotArea objects.
* @param world
* @return Collection of PlotArea objects
*/
public Set<PlotArea> getPlotAreas(String world) {

View File

@ -68,7 +68,7 @@ public class Load extends SubCommand {
String schem;
try {
schem = schematics.get(Integer.parseInt(args[0]) - 1);
} catch (Exception e) {
} catch (NumberFormatException e) {
// use /plot load <index>
MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ")");
return false;

View File

@ -64,11 +64,11 @@ public class Visit extends SubCommand {
@Override
public boolean onCommand(PlotPlayer player, String[] args) {
int page = Integer.MIN_VALUE;
Collection<Plot> unsorted = null;
if (args.length == 1 && args[0].contains(":")) {
args = args[0].split(":");
}
int page = Integer.MIN_VALUE;
Collection<Plot> unsorted = null;
switch (args.length) {
case 2: {
if (!MathMan.isInteger(args[1])) {

View File

@ -35,87 +35,87 @@ public class Configuration {
public static final SettingValue<String> STRING = new SettingValue<String>("STRING") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
return true;
}
@Override
public String parseString(final String string) {
public String parseString(String string) {
return string;
}
};
public static final SettingValue<String[]> STRINGLIST = new SettingValue<String[]>("STRINGLIST") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
return true;
}
@Override
public String[] parseString(final String string) {
public String[] parseString(String string) {
return string.split(",");
}
};
public static final SettingValue<Integer> INTEGER = new SettingValue<Integer>("INTEGER") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
try {
Integer.parseInt(string);
return true;
} catch (final Exception e) {
} catch (Exception e) {
return false;
}
}
@Override
public Integer parseString(final String string) {
public Integer parseString(String string) {
return Integer.parseInt(string);
}
};
public static final SettingValue<Boolean> BOOLEAN = new SettingValue<Boolean>("BOOLEAN") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
try {
Boolean.parseBoolean(string);
return true;
} catch (final Exception e) {
} catch (Exception e) {
return false;
}
}
@Override
public Boolean parseString(final String string) {
public Boolean parseString(String string) {
return Boolean.parseBoolean(string);
}
};
public static final SettingValue<Double> DOUBLE = new SettingValue<Double>("DOUBLE") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
try {
Double.parseDouble(string);
return true;
} catch (final Exception e) {
} catch (Exception e) {
return false;
}
}
@Override
public Double parseString(final String string) {
public Double parseString(String string) {
return Double.parseDouble(string);
}
};
public static final SettingValue<String> BIOME = new SettingValue<String>("BIOME") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
try {
final int biome = WorldUtil.IMP.getBiomeFromString(string.toUpperCase());
int biome = WorldUtil.IMP.getBiomeFromString(string.toUpperCase());
return biome != -1;
} catch (final Exception e) {
} catch (Exception e) {
return false;
}
}
@Override
public String parseString(final String string) {
public String parseString(String string) {
if (validateValue(string)) {
return string.toUpperCase();
}
@ -124,14 +124,14 @@ public class Configuration {
};
public static final SettingValue<PlotBlock> BLOCK = new SettingValue<PlotBlock>("BLOCK") {
@Override
public boolean validateValue(final String string) {
final StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string);
public boolean validateValue(String string) {
StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string);
return !(value == null || value.match > 1);
}
@Override
public PlotBlock parseString(final String string) {
final StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string);
public PlotBlock parseString(String string) {
StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string);
if (value == null || value.match > 1) {
return null;
}
@ -140,15 +140,15 @@ public class Configuration {
};
public static final SettingValue<PlotBlock[]> BLOCKLIST = new SettingValue<PlotBlock[]>("BLOCKLIST") {
@Override
public boolean validateValue(final String string) {
public boolean validateValue(String string) {
try {
for (String block : string.split(",")) {
if (block.contains("%")) {
final String[] split = block.split("%");
String[] split = block.split("%");
Integer.parseInt(split[0]);
block = split[1];
}
final StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(block);
StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(block);
if (value == null || value.match > 1) {
return false;
}
@ -160,18 +160,18 @@ public class Configuration {
}
@Override
public PlotBlock[] parseString(final String string) {
final String[] blocks = string.split(",");
final ArrayList<PlotBlock> parsedvalues = new ArrayList<>();
final PlotBlock[] values = new PlotBlock[blocks.length];
final int[] counts = new int[blocks.length];
public PlotBlock[] parseString(String string) {
String[] blocks = string.split(",");
ArrayList<PlotBlock> parsedvalues = new ArrayList<>();
PlotBlock[] values = new PlotBlock[blocks.length];
int[] counts = new int[blocks.length];
int min = 100;
for (int i = 0; i < blocks.length; i++) {
try {
if (blocks[i].contains("%")) {
final String[] split = blocks[i].split("%");
String[] split = blocks[i].split("%");
blocks[i] = split[1];
final int value = Integer.parseInt(split[0]);
int value = Integer.parseInt(split[0]);
counts[i] = value;
if (value < min) {
min = value;
@ -182,16 +182,16 @@ public class Configuration {
min = 1;
}
}
final StringComparison<PlotBlock>.ComparisonResult result = WorldUtil.IMP.getClosestBlock(blocks[i]);
StringComparison<PlotBlock>.ComparisonResult result = WorldUtil.IMP.getClosestBlock(blocks[i]);
if (result != null && result.match < 2) {
values[i] = result.best;
}
} catch (NumberFormatException e) {
}
}
final int gcd = gcd(counts);
int gcd = gcd(counts);
for (int i = 0; i < counts.length; i++) {
final int num = counts[i];
int num = counts[i];
for (int j = 0; j < num / gcd; j++) {
parsedvalues.add(values[i]);
}
@ -200,14 +200,14 @@ public class Configuration {
}
};
public static int gcd(final int a, final int b) {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static int gcd(final int[] a) {
private static int gcd(int[] a) {
int result = a[0];
for (int i = 1; i < a.length; i++) {
result = gcd(result, a[i]);
@ -219,9 +219,10 @@ public class Configuration {
* Create your own SettingValue object to make the management of plotworld configuration easier
*/
public static abstract class SettingValue<T> {
private final String type;
public SettingValue(final String type) {
public SettingValue(String type) {
this.type = type;
}
@ -229,8 +230,8 @@ public class Configuration {
return this.type;
}
public abstract T parseString(final String string);
public abstract T parseString(String string);
public abstract boolean validateValue(final String string);
public abstract boolean validateValue(String string);
}
}

View File

@ -61,7 +61,7 @@ public abstract class Database {
public abstract Connection getConnection();
/**
* Closes the connection with the database
* Closes the connection with the database.
*
* @return true if successful
*
@ -70,7 +70,8 @@ public abstract class Database {
public abstract boolean closeConnection() throws SQLException;
/**
* Executes a SQL Query<br> If the connection is closed, it will be opened
* Executes a SQL Query.
* If the connection is closed, it will be opened.
*
* @param query Query to be run
*
@ -79,7 +80,7 @@ public abstract class Database {
* @throws SQLException If the query cannot be executed
* @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()}
*/
public abstract ResultSet querySQL(final String query) throws SQLException, ClassNotFoundException;
public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException;
/**
* Executes an Update SQL Query<br> See {@link java.sql.Statement#executeUpdate(String)}<br> If the connection is
@ -92,5 +93,5 @@ public abstract class Database {
* @throws SQLException If the query cannot be executed
* @throws ClassNotFoundException If the driver cannot be found; see {@link #openConnection()}
*/
public abstract int updateSQL(final String query) throws SQLException, ClassNotFoundException;
public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException;
}

View File

@ -31,6 +31,7 @@ import com.intellectualcrafters.plot.object.PlotSettings;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.Permissions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@ -53,7 +54,7 @@ public class FlagManager {
* Reserve a flag so that it cannot be set by players
* @param flag
*/
public static void reserveFlag(final String flag) {
public static void reserveFlag(String flag) {
reserved.add(flag);
}
@ -62,7 +63,7 @@ public class FlagManager {
* @param flag
* @return
*/
public static boolean isReserved(final String flag) {
public static boolean isReserved(String flag) {
return reserved.contains(flag);
}
@ -78,7 +79,7 @@ public class FlagManager {
* Unreserve a flag
* @param flag
*/
public static void unreserveFlag(final String flag) {
public static void unreserveFlag(String flag) {
reserved.remove(flag);
}
@ -89,16 +90,16 @@ public class FlagManager {
*
* @return boolean success
*/
public static boolean addFlag(final AbstractFlag af) {
public static boolean addFlag(AbstractFlag af) {
return addFlag(af, false);
}
public static boolean addFlag(final AbstractFlag af, final boolean reserved) {
public static boolean addFlag(final AbstractFlag af, boolean reserved) {
PS.debug(C.PREFIX + "&8 - Adding flag: &7" + af);
PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override
public void run(PlotArea value) {
final Flag flag = value.DEFAULT_FLAGS.get(af.getKey());
Flag flag = value.DEFAULT_FLAGS.get(af.getKey());
if (flag != null) {
flag.setKey(af);
}
@ -107,7 +108,7 @@ public class FlagManager {
PS.get().foreachPlotRaw(new RunnableVal<Plot>() {
@Override
public void run(Plot value) {
final Flag flag = value.getFlags().get(af.getKey());
Flag flag = value.getFlags().get(af.getKey());
if (flag != null) {
flag.setKey(af);
}
@ -124,9 +125,9 @@ public class FlagManager {
}
public static String toString(Collection<Flag> flags) {
final StringBuilder flag_string = new StringBuilder();
StringBuilder flag_string = new StringBuilder();
int i = 0;
for (final Flag flag : flags) {
for (Flag flag : flags) {
if (i != 0) {
flag_string.append(",");
}
@ -136,7 +137,7 @@ public class FlagManager {
return flag_string.toString();
}
public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) {
public static Flag getSettingFlag(PlotArea area, PlotSettings settings, String id) {
Flag flag;
if (settings.flags.isEmpty() || (flag = settings.flags.get(id)) == null) {
if (area == null) {
@ -150,12 +151,12 @@ public class FlagManager {
return flag;
}
public static boolean isBooleanFlag(final Plot plot, final String key, final boolean defaultValue) {
final Flag flag = FlagManager.getPlotFlagRaw(plot, key);
public static boolean isBooleanFlag(Plot plot, String key, boolean defaultValue) {
Flag flag = FlagManager.getPlotFlagRaw(plot, key);
if (flag == null) {
return defaultValue;
}
final Object value = flag.getValue();
Object value = flag.getValue();
if (value instanceof Boolean) {
return (boolean) value;
}
@ -168,7 +169,7 @@ public class FlagManager {
* @param flag
* @return Flag
*/
public static Flag getPlotFlag(final Plot plot, final String flag) {
public static Flag getPlotFlag(Plot plot, String flag) {
Flag result = getPlotFlagRaw(plot, flag);
return result == null ? null : (Flag) result.clone();
}
@ -181,26 +182,26 @@ public class FlagManager {
* @param flag
* @return
*/
public static Flag getPlotFlagRaw(final Plot plot, final String flag) {
public static Flag getPlotFlagRaw(Plot plot, String flag) {
if (plot.owner == null) {
return null;
}
return getSettingFlag(plot.getArea(), plot.getSettings(), flag);
}
public static boolean isPlotFlagTrue(final Plot plot, final String strFlag) {
public static boolean isPlotFlagTrue(Plot plot, String strFlag) {
if (plot.owner == null) {
return false;
}
final Flag flag = getPlotFlagRaw(plot, strFlag);
Flag flag = getPlotFlagRaw(plot, strFlag);
return !(flag == null || !((Boolean) flag.getValue()));
}
public static boolean isPlotFlagFalse(final Plot plot, final String strFlag) {
public static boolean isPlotFlagFalse(Plot plot, String strFlag) {
if (plot.owner == null) {
return false;
}
final Flag flag = getPlotFlagRaw(plot, strFlag);
Flag flag = getPlotFlagRaw(plot, strFlag);
if (flag == null || (Boolean) flag.getValue()) {
return false;
}
@ -213,11 +214,11 @@ public class FlagManager {
* @param flag
* @return Flag
*/
public static Flag getPlotFlagAbs(final Plot plot, final String flag) {
public static Flag getPlotFlagAbs(Plot plot, String flag) {
return getSettingFlagAbs(plot.getSettings(), flag);
}
public static Flag getSettingFlagAbs(final PlotSettings settings, final String flag) {
public static Flag getSettingFlagAbs(PlotSettings settings, String flag) {
if (settings.flags.isEmpty()) {
return null;
}
@ -229,8 +230,8 @@ public class FlagManager {
* @param origin
* @param flag
*/
public static boolean addPlotFlag(final Plot origin, final Flag flag) {
final boolean result = EventUtil.manager.callFlagAdd(flag, origin);
public static boolean addPlotFlag(Plot origin, Flag flag) {
boolean result = EventUtil.manager.callFlagAdd(flag, origin);
if (!result) {
return false;
}
@ -242,8 +243,8 @@ public class FlagManager {
return true;
}
public static boolean addPlotFlagAbs(final Plot plot, final Flag flag) {
final boolean result = EventUtil.manager.callFlagAdd(flag, plot);
public static boolean addPlotFlagAbs(Plot plot, Flag flag) {
boolean result = EventUtil.manager.callFlagAdd(flag, plot);
if (!result) {
return false;
}
@ -251,7 +252,7 @@ public class FlagManager {
return true;
}
public static boolean addClusterFlag(final PlotCluster cluster, final Flag flag) {
public static boolean addClusterFlag(PlotCluster cluster, Flag flag) {
getSettingFlag(cluster.area, cluster.settings, flag.getKey());
cluster.settings.flags.put(flag.getKey(), flag);
DBFunc.setFlags(cluster, cluster.settings.flags.values());
@ -263,20 +264,20 @@ public class FlagManager {
* @param plot
* @return set of flags
*/
public static HashMap<String, Flag> getPlotFlags(final Plot plot) {
public static HashMap<String, Flag> getPlotFlags(Plot plot) {
if (!plot.hasOwner()) {
return null;
}
return getSettingFlags(plot.getArea(), plot.getSettings());
}
public static HashMap<String, Flag> getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) {
final HashMap<String, Flag> flags = new HashMap<>();
public static HashMap<String, Flag> getPlotFlags(PlotArea area, PlotSettings settings, boolean ignorePluginflags) {
HashMap<String, Flag> flags = new HashMap<>();
if (area != null && !area.DEFAULT_FLAGS.isEmpty()) {
flags.putAll(area.DEFAULT_FLAGS);
}
if (ignorePluginflags) {
for (final Map.Entry<String, Flag> flag : settings.flags.entrySet()) {
for (Map.Entry<String, Flag> flag : settings.flags.entrySet()) {
if (isReserved(flag.getValue().getAbstractFlag().getKey())) {
continue;
}
@ -289,16 +290,16 @@ public class FlagManager {
return flags;
}
public static HashMap<String, Flag> getSettingFlags(PlotArea area, final PlotSettings settings) {
public static HashMap<String, Flag> getSettingFlags(PlotArea area, PlotSettings settings) {
return getPlotFlags(area, settings, false);
}
public static boolean removePlotFlag(final Plot plot, final String id) {
final Flag flag = plot.getFlags().remove(id);
public static boolean removePlotFlag(Plot plot, String id) {
Flag flag = plot.getFlags().remove(id);
if (flag == null) {
return false;
}
final boolean result = EventUtil.manager.callFlagRemove(flag, plot);
boolean result = EventUtil.manager.callFlagRemove(flag, plot);
if (!result) {
plot.getFlags().put(id, flag);
return false;
@ -308,12 +309,12 @@ public class FlagManager {
return true;
}
public static boolean removeClusterFlag(final PlotCluster cluster, final String id) {
final Flag flag = cluster.settings.flags.remove(id);
public static boolean removeClusterFlag(PlotCluster cluster, String id) {
Flag flag = cluster.settings.flags.remove(id);
if (flag == null) {
return false;
}
final boolean result = EventUtil.manager.callFlagRemove(flag, cluster);
boolean result = EventUtil.manager.callFlagRemove(flag, cluster);
if (!result) {
cluster.settings.flags.put(id, flag);
return false;
@ -322,11 +323,11 @@ public class FlagManager {
return true;
}
public static void setPlotFlags(final Plot origin, final Set<Flag> flags) {
public static void setPlotFlags(Plot origin, Set<Flag> flags) {
for (Plot plot : origin.getConnectedPlots()) {
if (flags != null && !flags.isEmpty()) {
plot.getFlags().clear();
for (final Flag flag : flags) {
for (Flag flag : flags) {
plot.getFlags().put(flag.getKey(), flag);
}
} else if (plot.getFlags().isEmpty()) {
@ -339,10 +340,10 @@ public class FlagManager {
}
}
public static void setClusterFlags(final PlotCluster cluster, final Set<Flag> flags) {
public static void setClusterFlags(PlotCluster cluster, Set<Flag> flags) {
if (flags != null && !flags.isEmpty()) {
cluster.settings.flags.clear();
for (final Flag flag : flags) {
for (Flag flag : flags) {
cluster.settings.flags.put(flag.getKey(), flag);
}
} else if (cluster.settings.flags.isEmpty()) {
@ -353,10 +354,10 @@ public class FlagManager {
DBFunc.setFlags(cluster, cluster.settings.flags.values());
}
public static Flag[] removeFlag(final Flag[] flags, final String r) {
final Flag[] f = new Flag[flags.length - 1];
public static Flag[] removeFlag(Flag[] flags, String r) {
Flag[] f = new Flag[flags.length - 1];
int index = 0;
for (final Flag flag : flags) {
for (Flag flag : flags) {
if (!flag.getKey().equals(r)) {
f[index++] = flag;
}
@ -364,9 +365,9 @@ public class FlagManager {
return f;
}
public static Set<Flag> removeFlag(final Set<Flag> flags, final String r) {
final HashSet<Flag> newflags = new HashSet<>();
for (final Flag flag : flags) {
public static Set<Flag> removeFlag(Set<Flag> flags, String r) {
HashSet<Flag> newflags = new HashSet<>();
for (Flag flag : flags) {
if (!flag.getKey().equalsIgnoreCase(r)) {
newflags.add(flag);
}
@ -390,9 +391,9 @@ public class FlagManager {
*
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getFlags(final PlotPlayer player) {
final List<AbstractFlag> returnFlags = new ArrayList<>();
for (final AbstractFlag flag : flags) {
public static List<AbstractFlag> getFlags(PlotPlayer player) {
List<AbstractFlag> returnFlags = new ArrayList<>();
for (AbstractFlag flag : flags) {
if (Permissions.hasPermission(player, "plots.set.flag." + flag.getKey().toLowerCase())) {
returnFlags.add(flag);
}
@ -407,8 +408,8 @@ public class FlagManager {
*
* @return AbstractFlag
*/
public static AbstractFlag getFlag(final String string) {
for (final AbstractFlag flag : flags) {
public static AbstractFlag getFlag(String string) {
for (AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) {
return flag;
}
@ -424,7 +425,7 @@ public class FlagManager {
*
* @return AbstractFlag
*/
public static AbstractFlag getFlag(final String string, final boolean create) {
public static AbstractFlag getFlag(String string, boolean create) {
if (getFlag(string) == null && create) {
return new AbstractFlag(string);
}
@ -438,14 +439,14 @@ public class FlagManager {
*
* @return boolean Result of operation
*/
public static boolean removeFlag(final AbstractFlag flag) {
public static boolean removeFlag(AbstractFlag flag) {
return flags.remove(flag);
}
public static HashMap<String, Flag> parseFlags(final List<String> flagstrings) {
final HashMap<String, Flag> map = new HashMap<>();
for (final String key : flagstrings) {
final String[] split;
public static HashMap<String, Flag> parseFlags(List<String> flagstrings) {
HashMap<String, Flag> map = new HashMap<>();
for (String key : flagstrings) {
String[] split;
if (key.contains(";")) {
split = key.split(";");
} else {

View File

@ -1,20 +1,17 @@
package com.intellectualcrafters.plot.flag;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
/**
* Created 2014-11-17 for PlotSquared
*
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public abstract class FlagValue<T> {
private final Class<T> clazz;
@SuppressWarnings("unchecked")
@ -22,35 +19,43 @@ public abstract class FlagValue<T> {
this.clazz = (Class<T>) getClass();
}
public FlagValue(final Class<T> clazz) {
public FlagValue(Class<T> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
public boolean validValue(final Object value) {
public boolean validValue(Object value) {
return (value != null) && (value.getClass() == this.clazz);
}
public String toString(final Object t) {
public String toString(Object t) {
return t.toString();
}
public abstract T getValue(final Object t);
public abstract T getValue(Object t);
public abstract T parse(final String t);
public abstract T parse(String t);
public abstract String getDescription();
public interface ListValue extends Cloneable {
void add(Object t, String value);
void remove(Object t, String value);
}
public static class BooleanValue extends FlagValue<Boolean> {
@Override
public Boolean getValue(final Object t) {
public Boolean getValue(Object t) {
return (Boolean) t;
}
@Override
public Boolean parse(final String t) {
public Boolean parse(String t) {
switch (t.toLowerCase()) {
case "1":
case "yes":
@ -77,16 +82,17 @@ public abstract class FlagValue<T> {
}
public static class IntegerValue extends FlagValue<Integer> {
@Override
public Integer getValue(final Object t) {
public Integer getValue(Object t) {
return (Integer) t;
}
@Override
public Integer parse(final String t) {
public Integer parse(String t) {
try {
return Integer.parseInt(t);
} catch (final IllegalArgumentException e) {
} catch (IllegalArgumentException e) {
return null;
}
}
@ -98,38 +104,39 @@ public abstract class FlagValue<T> {
}
public static class IntervalValue extends FlagValue<Integer[]> {
@Override
public String toString(final Object t) {
final Integer[] value = ((Integer[]) t);
public String toString(Object t) {
Integer[] value = (Integer[]) t;
return value[0] + " " + value[1];
}
@Override
public Integer[] getValue(final Object t) {
public Integer[] getValue(Object t) {
return (Integer[]) t;
}
@Override
public Integer[] parse(final String t) {
public Integer[] parse(String t) {
int seconds;
int amount;
final String[] values = t.split(" ");
String[] values = t.split(" ");
if (values.length < 2) {
seconds = 1;
try {
amount = Integer.parseInt(values[0]);
} catch (final Exception e) {
} catch (Exception e) {
return null;
}
} else {
try {
amount = Integer.parseInt(values[0]);
seconds = Integer.parseInt(values[1]);
} catch (final Exception e) {
} catch (Exception e) {
return null;
}
}
return new Integer[] { amount, seconds };
return new Integer[]{amount, seconds};
}
@Override
@ -139,20 +146,21 @@ public abstract class FlagValue<T> {
}
public static class UnsignedIntegerValue extends FlagValue<Integer> {
@Override
public Integer getValue(final Object t) {
public Integer getValue(Object t) {
return (Integer) t;
}
@Override
public Integer parse(final String t) {
public Integer parse(String t) {
try {
final int value = Integer.parseInt(t);
int value = Integer.parseInt(t);
if (value < 0) {
return null;
}
return value;
} catch (final IllegalArgumentException e) {
} catch (IllegalArgumentException e) {
return null;
}
}
@ -164,16 +172,17 @@ public abstract class FlagValue<T> {
}
public static class DoubleValue extends FlagValue<Double> {
@Override
public Double getValue(final Object t) {
public Double getValue(Object t) {
return (Double) t;
}
@Override
public Double parse(final String t) {
public Double parse(String t) {
try {
return Double.parseDouble(t);
} catch (final IllegalArgumentException e) {
} catch (IllegalArgumentException e) {
return null;
}
}
@ -185,16 +194,17 @@ public abstract class FlagValue<T> {
}
public static class LongValue extends FlagValue<Long> {
@Override
public Long getValue(final Object t) {
public Long getValue(Object t) {
return (Long) t;
}
@Override
public Long parse(final String t) {
public Long parse(String t) {
try {
return Long.parseLong(t);
} catch (final IllegalArgumentException e) {
} catch (IllegalArgumentException e) {
return null;
}
}
@ -206,20 +216,21 @@ public abstract class FlagValue<T> {
}
public static class UnsignedLongValue extends FlagValue<Long> {
@Override
public Long getValue(final Object t) {
public Long getValue(Object t) {
return (Long) t;
}
@Override
public Long parse(final String t) {
public Long parse(String t) {
try {
final long value = Long.parseLong(t);
long value = Long.parseLong(t);
if (value < 0) {
return null;
}
return value;
} catch (final IllegalArgumentException e) {
} catch (IllegalArgumentException e) {
return null;
}
}
@ -231,20 +242,21 @@ public abstract class FlagValue<T> {
}
public static class UnsignedDoubleValue extends FlagValue<Double> {
@Override
public Double getValue(final Object t) {
public Double getValue(Object t) {
return (Double) t;
}
@Override
public Double parse(final String t) {
public Double parse(String t) {
try {
final double value = Double.parseDouble(t);
double value = Double.parseDouble(t);
if (value < 0) {
return null;
}
return value;
} catch (final IllegalArgumentException e) {
} catch (IllegalArgumentException e) {
return null;
}
}
@ -256,15 +268,16 @@ public abstract class FlagValue<T> {
}
public static class PlotBlockValue extends FlagValue<PlotBlock> {
@Override
public PlotBlock getValue(final Object t) {
public PlotBlock getValue(Object t) {
return (PlotBlock) t;
}
@Override
public PlotBlock parse(final String t) {
public PlotBlock parse(String t) {
try {
final String[] split = t.split(":");
String[] split = t.split(":");
byte data;
if (split.length == 2) {
if ("*".equals(split[1])) {
@ -275,10 +288,10 @@ public abstract class FlagValue<T> {
} else {
data = -1;
}
final short id = Short.parseShort(split[0]);
short id = Short.parseShort(split[0]);
return new PlotBlock(id, data);
} catch (final Exception e) {
final StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t);
} catch (Exception e) {
StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t);
if ((value == null) || (value.match > 1)) {
return null;
}
@ -292,32 +305,27 @@ public abstract class FlagValue<T> {
}
}
public interface ListValue extends Cloneable {
void add(final Object t, final String value);
void remove(final Object t, final String value);
}
public static class PlotBlockListValue extends FlagValue<HashSet<PlotBlock>> implements ListValue {
@SuppressWarnings("unchecked")
@Override
public String toString(final Object t) {
public String toString(Object t) {
return StringMan.join((HashSet<PlotBlock>) t, ",");
}
@SuppressWarnings("unchecked")
@Override
public HashSet<PlotBlock> getValue(final Object t) {
public HashSet<PlotBlock> getValue(Object t) {
return (HashSet<PlotBlock>) t;
}
@Override
public HashSet<PlotBlock> parse(final String t) {
final HashSet<PlotBlock> list = new HashSet<PlotBlock>();
for (final String item : t.split(",")) {
public HashSet<PlotBlock> parse(String t) {
HashSet<PlotBlock> list = new HashSet<PlotBlock>();
for (String item : t.split(",")) {
PlotBlock block;
try {
final String[] split = item.split(":");
String[] split = item.split(":");
byte data;
if (split.length == 2) {
if ("*".equals(split[1])) {
@ -328,10 +336,10 @@ public abstract class FlagValue<T> {
} else {
data = -1;
}
final short id = Short.parseShort(split[0]);
short id = Short.parseShort(split[0]);
block = new PlotBlock(id, data);
} catch (Exception e) {
final StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t);
StringComparison<PlotBlock>.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t);
if ((value == null) || (value.match > 1)) {
continue;
}
@ -348,40 +356,45 @@ public abstract class FlagValue<T> {
}
@Override
public void add(final Object t, final String value) {
public void add(Object t, String value) {
try {
((HashSet<PlotBlock>) t).addAll(parse(value));
} catch (final Exception e) {}
} catch (Exception ignored) {
//ignored
}
}
@Override
public void remove(final Object t, final String value) {
public void remove(Object t, String value) {
try {
for (final PlotBlock item : parse(value)) {
for (PlotBlock item : parse(value)) {
((HashSet<PlotBlock>) t).remove(item);
}
} catch (final Exception e) {}
} catch (Exception ignored) {
//ignored
}
}
}
public static class IntegerListValue extends FlagValue<List<Integer>> implements ListValue {
@SuppressWarnings("unchecked")
@Override
public String toString(final Object t) {
public String toString(Object t) {
return StringMan.join((List<Integer>) t, ",");
}
@SuppressWarnings("unchecked")
@Override
public List<Integer> getValue(final Object t) {
public List<Integer> getValue(Object t) {
return (List<Integer>) t;
}
@Override
public List<Integer> parse(final String t) {
final String[] split = (t.split(","));
final ArrayList<Integer> numbers = new ArrayList<Integer>();
for (final String element : split) {
public List<Integer> parse(String t) {
String[] split = t.split(",");
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (String element : split) {
numbers.add(Integer.parseInt(element));
}
return numbers;
@ -393,19 +406,23 @@ public abstract class FlagValue<T> {
}
@Override
public void add(final Object t, final String value) {
public void add(Object t, String value) {
try {
((List<Integer>) t).addAll(parse(value));
} catch (final Exception e) {}
} catch (Exception ignored) {
//ignored
}
}
@Override
public void remove(final Object t, final String value) {
public void remove(Object t, String value) {
try {
for (final Integer item : parse(value)) {
for (Integer item : parse(value)) {
((List<Integer>) t).remove(item);
}
} catch (final Exception e) {}
} catch (Exception ignored) {
//ignored
}
}
}
@ -436,7 +453,8 @@ public abstract class FlagValue<T> {
public void add(final Object t, final String value) {
try {
((List<String>) t).addAll(parse(value));
} catch (final Exception ignored) {}
} catch (final Exception ignored) {
}
}
@Override
@ -445,28 +463,30 @@ public abstract class FlagValue<T> {
for (final String item : parse(value)) {
((List<String>) t).remove(item);
}
} catch (final Exception e) {}
} catch (final Exception e) {
}
}
}
public static class DoubleListValue extends FlagValue<List<Double>> implements ListValue {
@SuppressWarnings("unchecked")
@Override
public String toString(final Object t) {
public String toString(Object t) {
return StringMan.join((List<Double>) t, ",");
}
@SuppressWarnings("unchecked")
@Override
public List<Double> getValue(final Object t) {
public List<Double> getValue(Object t) {
return (List<Double>) t;
}
@Override
public List<Double> parse(final String t) {
final String[] split = (t.split(","));
final ArrayList<Double> numbers = new ArrayList<Double>();
for (final String element : split) {
public List<Double> parse(String t) {
String[] split = t.split(",");
ArrayList<Double> numbers = new ArrayList<Double>();
for (String element : split) {
numbers.add(Double.parseDouble(element));
}
return numbers;
@ -478,25 +498,28 @@ public abstract class FlagValue<T> {
}
@Override
public void add(final Object t, final String value) {
public void add(Object t, String value) {
try {
((List<Double>) t).addAll(parse(value));
} catch (final Exception e) {}
} catch (Exception e) {
}
}
@Override
public void remove(final Object t, final String value) {
public void remove(Object t, String value) {
try {
for (final Double item : parse(value)) {
for (Double item : parse(value)) {
((List<Double>) t).remove(item);
}
} catch (final Exception e) {}
} catch (Exception e) {
}
}
}
public static class StringValue extends FlagValue<String> {
@Override
public String parse(final String s) {
public String parse(String s) {
return s;
}
@ -506,7 +529,7 @@ public abstract class FlagValue<T> {
}
@Override
public String getValue(final Object t) {
public String getValue(Object t) {
return t.toString();
}
}

View File

@ -42,7 +42,6 @@ public class HybridPlotWorld extends ClassicPlotWorld {
public boolean ROAD_SCHEMATIC_ENABLED;
public short SCHEMATIC_HEIGHT;
public boolean PLOT_SCHEMATIC = false;
public short REQUIRED_CHANGES = 0;
public short PATH_WIDTH_LOWER;
public short PATH_WIDTH_UPPER;
public HashMap<Integer, HashMap<Integer, PlotBlock>> G_SCH;

View File

@ -1,13 +1,15 @@
package com.intellectualcrafters.plot.object;
public class BlockLoc {
public int x;
public int y;
public int z;
public float yaw, pitch;
public final int x;
public final int y;
public final int z;
public BlockLoc(final int x, final int y, final int z, final float yaw, final float pitch) {
public final float yaw;
public final float pitch;
public BlockLoc(int x, int y, int z, float yaw, float pitch) {
this.x = x;
this.y = y;
this.z = z;
@ -16,12 +18,12 @@ public class BlockLoc {
this.pitch = pitch;
}
public BlockLoc(final int x, final int y, final int z) {
public BlockLoc(int x, int y, int z) {
this(x, y, z, 0f, 0f);
}
public static BlockLoc fromString(final String string) {
final String[] parts = string.split(",");
public static BlockLoc fromString(String string) {
String[] parts = string.split(",");
float yaw, pitch;
if (parts.length == 3) {
@ -34,44 +36,44 @@ public class BlockLoc {
} else {
return new BlockLoc(0, 0, 0);
}
final int x = Integer.parseInt(parts[0]);
final int y = Integer.parseInt(parts[1]);
final int z = Integer.parseInt(parts[2]);
int x = Integer.parseInt(parts[0]);
int y = Integer.parseInt(parts[1]);
int z = Integer.parseInt(parts[2]);
return new BlockLoc(x, y, z, yaw, pitch);
}
@Override
public int hashCode() {
final int prime = 31;
int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
result = prime * result + this.x;
result = prime * result + this.y;
result = prime * result + this.z;
return result;
}
@Override
public boolean equals(final Object obj) {
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return x == 0 && y == 0 && z == 0;
return this.x == 0 && this.y == 0 && this.z == 0;
}
if (getClass() != obj.getClass()) {
return false;
}
final BlockLoc other = (BlockLoc) obj;
return x == other.x && y == other.y && z == other.z;
BlockLoc other = (BlockLoc) obj;
return this.x == other.x && this.y == other.y && this.z == other.z;
}
@Override
public String toString() {
if (x == 0 && y == 0 && z == 0) {
if (this.x == 0 && this.y == 0 && this.z == 0) {
return "";
}
return x + "," + y + "," + z + "," + yaw + "," + pitch;
return this.x + "," + this.y + "," + this.z + "," + this.yaw + "," + this.pitch;
}
}

View File

@ -1,67 +0,0 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.object;
/**
* Wrapper class for blocks, using pure data rather than the object.
*
* Useful for NMS
*
*/
public class BlockWrapper {
/**
* X Coordinate
*/
public final int x;
/**
* Y Coordinate
*/
public final int y;
/**
* Z Coordinate
*/
public final int z;
/**
* Block ID
*/
public final int id;
/**
* Block Data Value
*/
public final byte data;
/**
* Constructor
*
* @param x X Loc Value
* @param y Y Loc Value
* @param z Z Loc Value
* @param id Material ID
* @param data Data Value
*/
public BlockWrapper(final int x, final int y, final int z, final short id, final byte data) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
this.data = data;
}
}

View File

@ -2,8 +2,8 @@ package com.intellectualcrafters.plot.object;
public class FileBytes {
public String path;
public byte[] data;
public final String path;
public final byte[] data;
public FileBytes(String path, byte[] data) {
this.path = path;

View File

@ -419,19 +419,19 @@ public class Plot {
}
/**
* Should the player be denied from entering?
* Should the player be denied from entering.
*
* @param uuid
*
* @return boolean false if the player is allowed to enter
*/
public boolean isDenied(UUID uuid) {
return this.denied != null && (this.denied.contains(DBFunc.everyone) && !this.isAdded(uuid) ||
!this.isAdded(uuid) && this.denied.contains(uuid));
return this.denied != null && (this.denied.contains(DBFunc.everyone) && !this.isAdded(uuid)
|| !this.isAdded(uuid) && this.denied.contains(uuid));
}
/**
* Get the plot ID
* Get the {@link PlotId}.
*/
public PlotId getId() {
return this.id;

View File

@ -518,12 +518,11 @@ public class PlotAnalysis {
bucket[i] = new ArrayList<Integer>();
}
boolean maxLength = false;
int tmp;
int placement = 1;
while (!maxLength) {
maxLength = true;
for (Integer i : input) {
tmp = i / placement;
int tmp = i / placement;
bucket[tmp % SIZE].add(i);
if (maxLength && tmp > 0) {
maxLength = false;

View File

@ -397,7 +397,7 @@ public abstract class PlotArea {
public abstract ConfigurationNode[] getSettingNodes();
/**
* Get the Plot at a location
* Get the Plot at a location.
* @param location
* @return Plot
*/
@ -410,7 +410,7 @@ public abstract class PlotArea {
}
/**
* Get the base plot at a location
* Get the base plot at a location.
* @param location
* @return base Plot
*/
@ -423,7 +423,7 @@ public abstract class PlotArea {
}
/**
* Get the base owned plot at a location
* Get the base owned plot at a location.
* @param location
* @return base Plot or null
*/
@ -437,7 +437,7 @@ public abstract class PlotArea {
}
/**
* Get the owned plot at a location
* Get the owned plot at a location.
* @param location
* @return Plot or null
*/
@ -450,7 +450,7 @@ public abstract class PlotArea {
}
/**
* Get the owned Plot at a PlotId
* Get the owned Plot at a PlotId.
* @param id
* @return Plot or null
*/

View File

@ -1,49 +1,45 @@
package com.intellectualcrafters.plot.object.comment;
import java.util.List;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.TaskManager;
import java.util.List;
public class InboxReport extends CommentInbox {
@Override
public boolean canRead(final Plot plot, final PlotPlayer player) {
public boolean canRead(Plot plot, PlotPlayer player) {
if (plot == null) {
return Permissions.hasPermission(player, "plots.inbox.read." + toString());
}
return (Permissions.hasPermission(player, "plots.inbox.read." + toString()) && (plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, "plots.inbox.read."
+ toString()
+ ".other")));
return Permissions.hasPermission(player, "plots.inbox.read." + toString()) && (plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, "plots.inbox.read." + toString() + ".other"));
}
@Override
public boolean canWrite(final Plot plot, final PlotPlayer player) {
public boolean canWrite(Plot plot, PlotPlayer player) {
if (plot == null) {
return Permissions.hasPermission(player, "plots.inbox.write." + toString());
}
return (Permissions.hasPermission(player, "plots.inbox.write." + toString()) && (plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, "plots.inbox.write."
+ toString()
+ ".other")));
return Permissions.hasPermission(player, "plots.inbox.write." + toString()) && (plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, "plots.inbox.write." + toString() + ".other"));
}
@Override
public boolean canModify(final Plot plot, final PlotPlayer player) {
public boolean canModify(Plot plot, PlotPlayer player) {
if (plot == null) {
return Permissions.hasPermission(player, "plots.inbox.modify." + toString());
}
return (Permissions.hasPermission(player, "plots.inbox.modify." + toString()) && (plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, "plots.inbox.modify."
+ toString()
+ ".other")));
return Permissions.hasPermission(player, "plots.inbox.modify." + toString()) && (plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, "plots.inbox.modify." + toString() + ".other"));
}
@Override
public boolean getComments(final Plot plot, final RunnableVal whenDone) {
public boolean getComments(Plot plot, final RunnableVal whenDone) {
DBFunc.getComments(null, toString(), new RunnableVal<List<PlotComment>>() {
@Override
public void run(List<PlotComment> value) {
@ -55,7 +51,7 @@ public class InboxReport extends CommentInbox {
}
@Override
public boolean addComment(final Plot plot, final PlotComment comment) {
public boolean addComment(Plot plot, PlotComment comment) {
if ((plot == null) || (plot.owner == null)) {
return false;
}
@ -69,8 +65,8 @@ public class InboxReport extends CommentInbox {
}
@Override
public boolean removeComment(final Plot plot, final PlotComment comment) {
if ((plot == null) || (plot.owner == null)) {
public boolean removeComment(Plot plot, PlotComment comment) {
if (plot == null || plot.owner == null) {
return false;
}
DBFunc.removeComment(plot, comment);
@ -78,7 +74,7 @@ public class InboxReport extends CommentInbox {
}
@Override
public boolean clearInbox(final Plot plot) {
public boolean clearInbox(Plot plot) {
if ((plot == null) || (plot.owner == null)) {
return false;
}

View File

@ -177,7 +177,8 @@ public class BO3Handler {
}
}
if (parentLoc == null) {
MainUtil.sendMessage(plr, "Exporting BO3 cancelled due to detached chunk: " + chunk + " - Make sure you only have one object per plot");
MainUtil.sendMessage(plr,
"Exporting BO3 cancelled due to detached chunk: " + chunk + " - Make sure you only have one object per plot");
return false;
}
}
@ -211,8 +212,7 @@ public class BO3Handler {
}
}
});
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
whenDone.run();
return;

View File

@ -5,21 +5,22 @@ import com.intellectualcrafters.plot.object.CmdInstance;
import com.intellectualcrafters.plot.object.PlotPlayer;
public class CmdConfirm {
public static CmdInstance getPending(final PlotPlayer player) {
public static CmdInstance getPending(PlotPlayer player) {
return player.getMeta("cmdConfirm");
}
public static void removePending(final PlotPlayer player) {
public static void removePending(PlotPlayer player) {
player.deleteMeta("cmdConfirm");
}
public static void addPending(final PlotPlayer player, final String commandStr, final Runnable runnable) {
public static void addPending(final PlotPlayer player, String commandStr, final Runnable runnable) {
removePending(player);
MainUtil.sendMessage(player, C.REQUIRES_CONFIRM, commandStr);
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
final CmdInstance cmd = new CmdInstance(runnable);
CmdInstance cmd = new CmdInstance(runnable);
player.setMeta("cmdConfirm", cmd);
}
}, 1);

View File

@ -17,6 +17,7 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class CommentManager {
public static HashMap<String, CommentInbox> inboxes = new HashMap<>();
public static void sendTitle(final PlotPlayer player, final Plot plot) {
@ -29,7 +30,7 @@ public class CommentManager {
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
public void run() {
final Collection<CommentInbox> boxes = CommentManager.inboxes.values();
Collection<CommentInbox> boxes = CommentManager.inboxes.values();
final AtomicInteger count = new AtomicInteger(0);
final AtomicInteger size = new AtomicInteger(boxes.size());
for (final CommentInbox inbox : inboxes.values()) {
@ -39,7 +40,7 @@ public class CommentManager {
int total;
if (value != null) {
int num = 0;
for (final PlotComment comment : value) {
for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) {
num++;
}
@ -58,15 +59,11 @@ public class CommentManager {
}, 20);
}
public static long getTimestamp(final PlotPlayer player, final String inbox) {
final Object meta = player.getMeta("inbox:" + inbox);
if (meta == null) {
return player.getPreviousLogin();
}
return (Long) meta;
public static long getTimestamp(PlotPlayer player, String inbox) {
return player.getMeta("inbox:" + inbox, player.getPreviousLogin());
}
public static void addInbox(final CommentInbox inbox) {
public static void addInbox(CommentInbox inbox) {
inboxes.put(inbox.toString().toLowerCase(), inbox);
}

View File

@ -5,9 +5,10 @@ import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
public abstract class EconHandler {
public static EconHandler manager;
public double getMoney(final PlotPlayer player) {
public double getMoney(PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) {
return Double.MAX_VALUE;
}
@ -16,21 +17,15 @@ public abstract class EconHandler {
public abstract double getBalance(PlotPlayer player);
public abstract void withdrawMoney(final PlotPlayer player, final double amount);
public abstract void withdrawMoney(PlotPlayer player, double amount);
public abstract void depositMoney(final PlotPlayer player, final double amount);
public abstract void depositMoney(PlotPlayer player, double amount);
public abstract void depositMoney(final OfflinePlotPlayer player, final double amount);
public abstract void depositMoney(OfflinePlotPlayer player, double amount);
public void setPermission(final String player, final String perm, final boolean value) {
setPermission(null, player, perm, value);
}
public abstract boolean hasPermission(String world, String player, String perm);
public abstract void setPermission(final String world, final String player, final String perm, final boolean value);
public abstract boolean hasPermission(final String world, final String player, final String perm);
public boolean hasPermission(final String player, final String perm) {
public boolean hasPermission(String player, String perm) {
return hasPermission(null, player, perm);
}
}

View File

@ -40,19 +40,21 @@ public class ExpireManager {
}
public void handleEntry(PlotPlayer pp, Plot plot) {
if (Settings.AUTO_CLEAR_CONFIRMATION && plotsToDelete != null && !plotsToDelete.isEmpty() && pp.hasPermission("plots.admin.command.autoclear") && plotsToDelete.contains(plot) && !isExpired(plot)) {
if (Settings.AUTO_CLEAR_CONFIRMATION && plotsToDelete != null && !plotsToDelete.isEmpty() && pp.hasPermission("plots.admin.command.autoclear")
&& plotsToDelete.contains(plot) && !isExpired(plot)) {
plotsToDelete.remove(plot);
confirmExpiry(pp);
}
}
public long getTimestamp(UUID uuid) {
Long value = dates_cache.get(uuid);
Long value = this.dates_cache.get(uuid);
return value == null ? 0 : value;
}
public void confirmExpiry(final PlotPlayer pp) {
if (Settings.AUTO_CLEAR_CONFIRMATION && plotsToDelete != null && !plotsToDelete.isEmpty() && pp.hasPermission("plots.admin.command.autoclear")) {
if (Settings.AUTO_CLEAR_CONFIRMATION && plotsToDelete != null && !plotsToDelete.isEmpty() && pp
.hasPermission("plots.admin.command.autoclear")) {
final int num = plotsToDelete.size();
for (final Plot current : plotsToDelete) {
if (isExpired(current)) {
@ -82,10 +84,10 @@ public class ExpireManager {
public boolean cancelTask() {
if (running != 2) {
if (this.running != 2) {
return false;
}
running = 1;
this.running = 1;
return true;
}
@ -112,24 +114,24 @@ public class ExpireManager {
}
public boolean runTask(final RunnableVal2<Plot, Runnable> expiredTask) {
if (running != 0) {
if (this.running != 0) {
return false;
}
running = 2;
this.running = 2;
final Set<Plot> plots = PS.get().getPlots();
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
if (running != 2) {
running = 0;
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
final Runnable task = this;
long start = System.currentTimeMillis();
Iterator<Plot> iter = plots.iterator();
while (iter.hasNext() && System.currentTimeMillis() - start < 2) {
if (running != 2) {
running = 0;
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
final Plot plot = iter.next();
@ -139,7 +141,7 @@ public class ExpireManager {
}
PlotArea area = plot.getArea();
if ((Settings.CLEAR_THRESHOLD != -1) && (area.TYPE == 0)) {
final PlotAnalysis analysis = plot.getComplexity();
PlotAnalysis analysis = plot.getComplexity();
if (analysis != null) {
if (analysis.getComplexity() > Settings.CLEAR_THRESHOLD) {
PS.debug("$2[&5Expire&dManager$2] &bSkipping modified: " + plot);
@ -150,7 +152,8 @@ public class ExpireManager {
@Override
public void run(PlotAnalysis changed) {
if ((changed.changes != 0) && (changed.getComplexity() > Settings.CLEAR_THRESHOLD)) {
PS.debug("$2[&5Expire&dManager$2] &bIgnoring modified plot: " + plot + " : " + changed.getComplexity() + " - " + changed.changes);
PS.debug("$2[&5Expire&dManager$2] &bIgnoring modified plot: " + plot + " : " + changed.getComplexity() + " - "
+ changed.changes);
FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("analysis"), changed.asList()));
TaskManager.runTaskLaterAsync(task, Settings.CLEAR_INTERVAL * 20);
} else {
@ -169,12 +172,12 @@ public class ExpireManager {
return;
}
if (plots.isEmpty()) {
running = 3;
ExpireManager.this.running = 3;
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
if (running == 3) {
running = 2;
if (ExpireManager.this.running == 3) {
ExpireManager.this.running = 2;
runTask(expiredTask);
}
}
@ -188,7 +191,7 @@ public class ExpireManager {
}
public void storeDate(UUID uuid, long time) {
dates_cache.put(uuid, time);
this.dates_cache.put(uuid, time);
}
public HashSet<Plot> getPendingExpired() {
@ -199,22 +202,22 @@ public class ExpireManager {
if (plot.isMerged()) {
plot.unlinkPlot(true, false);
}
for (final UUID helper : plot.getTrusted()) {
final PlotPlayer player = UUIDHandler.getPlayer(helper);
for (UUID helper : plot.getTrusted()) {
PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.toString());
}
}
for (final UUID helper : plot.getMembers()) {
final PlotPlayer player = UUIDHandler.getPlayer(helper);
for (UUID helper : plot.getMembers()) {
PlotPlayer player = UUIDHandler.getPlayer(helper);
if (player != null) {
MainUtil.sendMessage(player, C.PLOT_REMOVED_USER, plot.toString());
}
}
plot.deletePlot(whenDone);
final PlotAnalysis changed = plot.getComplexity();
final int complexity = changed == null ? 0 : changed.getComplexity();
final int modified = changed == null ? 0 : changed.changes;
PlotAnalysis changed = plot.getComplexity();
int complexity = changed == null ? 0 : changed.getComplexity();
int modified = changed == null ? 0 : changed.changes;
PS.debug("$2[&5Expire&dManager$2] &cDeleted expired plot: " + plot + " : " + complexity + " - " + modified);
PS.debug("$4 - Area: " + plot.getArea());
if (plot.hasOwner()) {
@ -224,13 +227,13 @@ public class ExpireManager {
}
}
public boolean isExpired(final UUID uuid) {
public boolean isExpired(UUID uuid) {
if (UUIDHandler.getPlayer(uuid) != null) {
return false;
}
final String name = UUIDHandler.getName(uuid);
String name = UUIDHandler.getName(uuid);
if (name != null) {
Long last = dates_cache.get(uuid);
Long last = this.dates_cache.get(uuid);
if (last == null) {
OfflinePlotPlayer opp;
if (Settings.TWIN_MODE_UUID) {
@ -239,7 +242,7 @@ public class ExpireManager {
opp = UUIDHandler.getUUIDWrapper().getOfflinePlayer(name);
}
if ((last = opp.getLastPlayed()) != 0) {
dates_cache.put(uuid, last);
this.dates_cache.put(uuid, last);
} else {
return false;
}
@ -247,7 +250,7 @@ public class ExpireManager {
if (last == 0) {
return false;
}
final long compared = System.currentTimeMillis() - last;
long compared = System.currentTimeMillis() - last;
if (compared >= TimeUnit.DAYS.toMillis(Settings.AUTO_CLEAR_DAYS)) {
return true;
}
@ -255,7 +258,7 @@ public class ExpireManager {
return false;
}
public boolean isExpired(final Plot plot) {
public boolean isExpired(Plot plot) {
if (!plot.hasOwner() || DBFunc.everyone.equals(plot.owner) || UUIDHandler.getPlayer(plot.owner) != null || plot.getRunning() > 0) {
return false;
}
@ -274,7 +277,7 @@ public class ExpireManager {
return false;
}
}
for (final UUID owner : plot.getOwners()) {
for (UUID owner : plot.getOwners()) {
if (!isExpired(owner)) {
return false;
}

View File

@ -180,22 +180,22 @@ public class MainUtil {
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
}
// try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) {
// final char[] buffer = new char[256];
// final StringBuilder result = new StringBuilder();
// while (true) {
// final int r = response.read(buffer);
// if (r < 0) {
// break;
// }
// result.append(buffer, 0, r);
// }
// if (!result.toString().startsWith("Success")) {
// PS.debug(result);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) {
// final char[] buffer = new char[256];
// final StringBuilder result = new StringBuilder();
// while (true) {
// final int r = response.read(buffer);
// if (r < 0) {
// break;
// }
// result.append(buffer, 0, r);
// }
// if (!result.toString().startsWith("Success")) {
// PS.debug(result);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
int responseCode = ((HttpURLConnection) con).getResponseCode();
if (responseCode == 200) {
whenDone.value = url;
@ -272,7 +272,7 @@ public class MainUtil {
case "second":
case "secs":
case "sec":
case "s":{
case "s": {
time += nums;
}
}
@ -366,7 +366,7 @@ public class MainUtil {
min.setZ(pos1.getZ());
}
}
return new Location[] { min, max };
return new Location[]{min, max};
}
/**
@ -529,30 +529,6 @@ public class MainUtil {
return new File(base, path);
}
/**
* Set a cuboid in the world to a set of blocks.
* @param world
* @param pos1
* @param pos2
* @param blocks If multiple blocks are provided, the result will be a random mix
*/
public static void setCuboid(String world, Location pos1, Location pos2, PlotBlock[] blocks) {
if (blocks.length == 1) {
setSimpleCuboid(world, pos1, pos2, blocks[0]);
return;
}
for (int y = pos1.getY(); y <= pos2.getY(); y++) {
for (int x = pos1.getX(); x <= pos2.getX(); x++) {
for (int z = pos1.getZ(); z <= pos2.getZ(); z++) {
int i = PseudoRandom.random.random(blocks.length);
PlotBlock block = blocks[i];
SetQueue.IMP.setBlock(world, x, y, z, block);
}
}
}
while (SetQueue.IMP.forceChunkSet());
}
/**
* Set a cuboid asynchronously to a set of blocks
* @param world
@ -577,25 +553,7 @@ public class MainUtil {
}
/**
* Set a cuboid to a block
* @param world
* @param pos1
* @param pos2
* @param newblock
*/
public static void setSimpleCuboid(String world, Location pos1, Location pos2, PlotBlock newblock) {
for (int y = pos1.getY(); y <= pos2.getY(); y++) {
for (int x = pos1.getX(); x <= pos2.getX(); x++) {
for (int z = pos1.getZ(); z <= pos2.getZ(); z++) {
SetQueue.IMP.setBlock(world, x, y, z, newblock);
}
}
}
while (SetQueue.IMP.forceChunkSet());
}
/**
* Set a cuboid asynchronously to a block
* Set a cuboid asynchronously to a block.
* @param world
* @param pos1
* @param pos2
@ -612,7 +570,7 @@ public class MainUtil {
}
/**
* Synchronously set the biome in a selection
* Synchronously set the biome in a selection.
* @param world
* @param p1x
* @param p1z
@ -626,7 +584,7 @@ public class MainUtil {
}
/**
* Get the highest block at a location
* Get the highest block at a location.
* @param world
* @param x
* @param z
@ -662,7 +620,7 @@ public class MainUtil {
}
/**
* Send a message to a player
* Send a message to a player.
* @param plr Can be null to represent console, or use ConsolePlayer.getConsole()
* @param msg
* @param prefix If the message should be prefixed with the configured prefix
@ -680,7 +638,7 @@ public class MainUtil {
}
/**
* Send a message to the player
* Send a message to the player.
*
* @param plr Player to receive message
* @param c Caption to send

View File

@ -25,8 +25,7 @@ import java.util.Collection;
import java.util.Collections;
/**
* String comparison library
*
* String comparison library.
*/
public class StringComparison<T> {
@ -40,37 +39,19 @@ public class StringComparison<T> {
* @param input Input Base Value
* @param objects Objects to compare
*/
public StringComparison(final String input, final T[] objects) {
public StringComparison(String input, T[] objects) {
init(input, objects);
}
public StringComparison(final String input, final Collection<T> objects) {
public StringComparison(String input, Collection<T> objects) {
init(input, (T[]) objects.toArray());
}
/**
* You should call init(...) when you are ready to get a String comparison value
* You should call init(...) when you are ready to get a String comparison value.
*/
public StringComparison() {}
public void init(String input, final T[] objects) {
int c;
this.bestMatch = objects[0];
this.bestMatchObject = objects[0];
input = input.toLowerCase();
for (final T o : objects) {
if ((c = compare(input, getString(o).toLowerCase())) < this.match) {
this.match = c;
this.bestMatch = o;
this.bestMatchObject = o;
}
}
}
public String getString(final T o) {
return o.toString();
}
/**
* Compare two strings
*
@ -79,10 +60,10 @@ public class StringComparison<T> {
*
* @return match
*/
public static int compare(final String s1, final String s2) {
public static int compare(String s1, String s2) {
int distance = StringMan.getLevenshteinDistance(s1, s2);
if (s2.contains(s1)) {
distance -= (Math.min(s1.length(), s2.length()));
distance -= Math.min(s1.length(), s2.length());
}
if (s2.startsWith(s1)) {
distance -= 4;
@ -97,11 +78,11 @@ public class StringComparison<T> {
*
* @return ArrayList
*/
public static ArrayList<String> wLetterPair(final String s) {
final ArrayList<String> aPairs = new ArrayList<>();
final String[] wo = s.split("\\s");
for (final String aWo : wo) {
final String[] po = sLetterPair(aWo);
public static ArrayList<String> wLetterPair(String s) {
ArrayList<String> aPairs = new ArrayList<>();
String[] wo = s.split("\\s");
for (String aWo : wo) {
String[] po = sLetterPair(aWo);
Collections.addAll(aPairs, po);
}
return aPairs;
@ -114,15 +95,33 @@ public class StringComparison<T> {
*
* @return Array
*/
public static String[] sLetterPair(final String s) {
final int numPair = s.length() - 1;
final String[] p = new String[numPair];
public static String[] sLetterPair(String s) {
int numPair = s.length() - 1;
String[] p = new String[numPair];
for (int i = 0; i < numPair; i++) {
p[i] = s.substring(i, i + 2);
}
return p;
}
public void init(String input, T[] objects) {
int c;
this.bestMatch = objects[0];
this.bestMatchObject = objects[0];
input = input.toLowerCase();
for (T o : objects) {
if ((c = compare(input, getString(o).toLowerCase())) < this.match) {
this.match = c;
this.bestMatch = o;
this.bestMatchObject = o;
}
}
}
public String getString(T o) {
return o.toString();
}
/**
* Get the object
*
@ -163,7 +162,7 @@ public class StringComparison<T> {
* @param match Match value
* @param best Best Match
*/
public ComparisonResult(final double match, final T best) {
public ComparisonResult(double match, T best) {
this.match = match;
this.best = best;
}

View File

@ -63,10 +63,10 @@ public abstract class WorldUtil {
@Override
public void run(OutputStream output) {
try (final ZipOutputStream zos = new ZipOutputStream(output)) {
byte[] buffer = new byte[1024];
File dat = getDat(plot.getArea().worldname);
Location spawn = getSpawn(plot.getArea().worldname);
setSpawn(home);
byte[] buffer = new byte[1024];
if (dat != null) {
ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName());
zos.putNextEntry(ze);

View File

@ -1,29 +0,0 @@
package com.plotsquared.listener;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
public class HeightLimitExtent extends AbstractDelegateExtent {
private final int max;
private final int min;
public HeightLimitExtent(final int min, final int max, final Extent child) {
super(child);
this.min = min;
this.max = max;
}
@Override
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException {
final int y = location.getBlockY();
if ((y < min) || (y > max)) {
return false;
}
return super.setBlock(location, block);
}
}

View File

@ -6,8 +6,20 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.util.*;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.listener.PlotListener;
import com.plotsquared.sponge.SpongeMain;
import com.plotsquared.sponge.object.SpongePlayer;
@ -41,8 +53,13 @@ import org.spongepowered.api.event.world.ExplosionEvent.Detonate;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.World;
import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
@ -74,7 +91,7 @@ public class MainListener {
*/
@Listener
public void onCommand(final SendCommandEvent event) {
public void onCommand(SendCommandEvent event) {
switch (event.getCommand().toLowerCase()) {
case "plotme": {
Player source = SpongeUtil.getCause(event.getCause(), Player.class);
@ -84,7 +101,7 @@ public class MainListener {
if (Settings.USE_PLOTME_ALIAS) {
SpongeMain.THIS.getGame().getCommandManager().process(source, ("plots " + event.getArguments()).trim());
} else {
source.sendMessage(SpongeUtil.getText(C.NOT_USING_PLOTME));
source.sendMessage(SpongeUtil.getText(C.NOT_USING_PLOTME.s()));
}
event.setCancelled(true);
}
@ -92,34 +109,34 @@ public class MainListener {
}
@Listener
public void onChat(final MessageEvent event) {
public void onChat(MessageEvent event) {
// TODO
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
final String world = player.getWorld().getName();
String world = player.getWorld().getName();
if (!PS.get().hasPlotArea(world)) {
return;
}
final PlotArea plotworld = PS.get().getPlotAreaByString(world);
final PlotPlayer plr = SpongeUtil.getPlayer(player);
PlotArea plotworld = PS.get().getPlotAreaByString(world);
PlotPlayer plr = SpongeUtil.getPlayer(player);
if (!plotworld.PLOT_CHAT && ((plr.getMeta("chat") == null) || !(Boolean) plr.getMeta("chat"))) {
return;
}
final Location loc = SpongeUtil.getLocation(player);
final Plot plot = loc.getPlot();
Location loc = SpongeUtil.getLocation(player);
Plot plot = loc.getPlot();
if (plot == null) {
return;
}
final Text message = event.getMessage();
Text message = event.getMessage();
// TODO use display name rather than username
// - Getting displayname currently causes NPE, so wait until sponge fixes that
final String sender = player.getName();
final PlotId id = plot.getId();
final String newMessage = StringMan.replaceAll(C.PLOT_CHAT_FORMAT.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
String sender = player.getName();
PlotId id = plot.getId();
String newMessage = StringMan.replaceAll(C.PLOT_CHAT_FORMAT.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
// String forcedMessage = StringMan.replaceAll(C.PLOT_CHAT_FORCED.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer user = entry.getValue();
@ -132,10 +149,10 @@ public class MainListener {
} else {
continue;
}
final String[] split = (toSend + " ").split("%msg%");
final List<Text> components = new ArrayList<>();
String[] split = (toSend + " ").split("%msg%");
List<Text> components = new ArrayList<>();
Text prefix = null;
for (final String part : split) {
for (String part : split) {
if (prefix != null) {
components.add(prefix);
} else {
@ -149,14 +166,14 @@ public class MainListener {
}
@Listener
public void onBreedEntity(final BreedEntityEvent.Breed event) {
final Location loc = SpongeUtil.getLocation(event.getTargetEntity());
final String world = loc.getWorld();
final PlotArea plotworld = PS.get().getPlotAreaByString(world);
public void onBreedEntity(BreedEntityEvent.Breed event) {
Location loc = SpongeUtil.getLocation(event.getTargetEntity());
String world = loc.getWorld();
PlotArea plotworld = PS.get().getPlotAreaByString(world);
if (plotworld == null) {
return;
}
final Plot plot = loc.getPlot();
Plot plot = loc.getPlot();
if (plot == null) {
if (loc.isPlotRoad()) {
event.setCancelled(true);
@ -170,7 +187,7 @@ public class MainListener {
public void onSpawnEntity(SpawnEntityEvent event) throws Exception {
World world = event.getTargetWorld();
final PlotArea plotworld = PS.get().getPlotAreaByString(world.getName());
PlotArea plotworld = PS.get().getPlotAreaByString(world.getName());
if (plotworld == null) {
return;
}
@ -178,13 +195,10 @@ public class MainListener {
if (entity instanceof Player) {
return true;
}
final Location loc = SpongeUtil.getLocation(entity);
final Plot plot = loc.getPlot();
Location loc = SpongeUtil.getLocation(entity);
Plot plot = loc.getPlot();
if (plot == null) {
if (loc.isPlotRoad()) {
return false;
}
return true;
return !loc.isPlotRoad();
}
// Player player = this.<Player> getCause(event.getCause());
// TODO selectively cancel depending on spawn reason
@ -195,19 +209,16 @@ public class MainListener {
// }
if (entity.getType() == EntityTypes.ITEM) {
if (FlagManager.isPlotFlagFalse(plot, "item-drop")) {
return false;
}
return true;
return !FlagManager.isPlotFlagFalse(plot, "item-drop");
}
int[] mobs = null;
if (entity instanceof Living) {
if (!plotworld.MOB_SPAWNING) {
return false;
}
final Flag mobCap = FlagManager.getPlotFlagRaw(plot, "mob-cap");
Flag mobCap = FlagManager.getPlotFlagRaw(plot, "mob-cap");
if (mobCap != null) {
final Integer cap = (Integer) mobCap.getValue();
Integer cap = (Integer) mobCap.getValue();
if (cap == 0) {
return false;
}
@ -217,9 +228,9 @@ public class MainListener {
}
}
if ((entity instanceof Ambient) || (entity instanceof Animal)) {
final Flag animalFlag = FlagManager.getPlotFlagRaw(plot, "animal-cap");
Flag animalFlag = FlagManager.getPlotFlagRaw(plot, "animal-cap");
if (animalFlag != null) {
final int cap = ((Integer) animalFlag.getValue());
int cap = (Integer) animalFlag.getValue();
if (cap == 0) {
return false;
}
@ -232,9 +243,9 @@ public class MainListener {
}
}
if (entity instanceof Monster) {
final Flag monsterFlag = FlagManager.getPlotFlagRaw(plot, "hostile-cap");
Flag monsterFlag = FlagManager.getPlotFlagRaw(plot, "hostile-cap");
if (monsterFlag != null) {
final int cap = ((Integer) monsterFlag.getValue());
int cap = (Integer) monsterFlag.getValue();
if (cap == 0) {
return false;
}
@ -249,9 +260,9 @@ public class MainListener {
return true;
}
if ((entity instanceof Minecart) || (entity instanceof Boat)) {
final Flag vehicleFlag = FlagManager.getPlotFlagRaw(plot, "vehicle-cap");
Flag vehicleFlag = FlagManager.getPlotFlagRaw(plot, "vehicle-cap");
if (vehicleFlag != null) {
final int cap = ((Integer) vehicleFlag.getValue());
int cap = (Integer) vehicleFlag.getValue();
if (cap == 0) {
return false;
}
@ -261,9 +272,9 @@ public class MainListener {
}
}
}
final Flag entityCap = FlagManager.getPlotFlagRaw(plot, "entity-cap");
Flag entityCap = FlagManager.getPlotFlagRaw(plot, "entity-cap");
if (entityCap != null) {
final Integer cap = (Integer) entityCap.getValue();
Integer cap = (Integer) entityCap.getValue();
if (cap == 0) {
return false;
}
@ -283,7 +294,7 @@ public class MainListener {
}
public void onNotifyNeighborBlock(NotifyNeighborBlockEvent event) throws Exception {
final AtomicBoolean cancelled = new AtomicBoolean(false);
AtomicBoolean cancelled = new AtomicBoolean(false);
// SpongeUtil.printCause("physics", event.getCause());
// PlotArea area = plotloc.getPlotArea();
// event.filterDirections(new Predicate<Direction>() {
@ -320,7 +331,7 @@ public class MainListener {
@Listener
public void onInteract(InteractEvent event) throws Exception {
final Player player = SpongeUtil.getCause(event.getCause(), Player.class);
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
event.setCancelled(true);
return;
@ -354,7 +365,7 @@ public class MainListener {
if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) {
return;
} else {
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
if ((flag != null) && ((HashSet<PlotBlock>) flag.getValue()).contains(SpongeUtil.getPlotBlock(l.getBlock()))) {
return;
}
@ -368,8 +379,8 @@ public class MainListener {
public void onExplosion(ExplosionEvent e) throws Exception {
if (e instanceof ExplosionEvent.Detonate) {
ExplosionEvent.Detonate event = (Detonate) e;
final World world = event.getTargetWorld();
final String worldname = world.getName();
World world = event.getTargetWorld();
String worldname = world.getName();
if (!PS.get().hasPlotArea(worldname)) {
return;
}
@ -382,7 +393,7 @@ public class MainListener {
Location origin = SpongeUtil.getLocation(worldname, tnt.getRotation());
Plot originPlot = origin.getPlot();
Location current = SpongeUtil.getLocation(tnt);
final Plot currentPlot = current.getPlot();
Plot currentPlot = current.getPlot();
if (!Objects.equals(originPlot, currentPlot)) {
event.setCancelled(true);
return;
@ -410,8 +421,8 @@ public class MainListener {
}
public void onChangeBlock(ChangeBlockEvent event) {
final World world = event.getTargetWorld();
final String worldname = world.getName();
World world = event.getTargetWorld();
String worldname = world.getName();
if (!PS.get().hasPlotArea(worldname)) {
return;
}
@ -429,39 +440,36 @@ public class MainListener {
event.filter(new Predicate<org.spongepowered.api.world.Location<World>>() {
@Override
public boolean test(org.spongepowered.api.world.Location<World> loc) {
if (SpongeUtil.getLocation(worldname, loc).isPlotRoad()) {
return false;
}
return true;
return !SpongeUtil.getLocation(worldname, loc).isPlotRoad();
}
});
}
@Listener
public void onBlockBreak(final ChangeBlockEvent.Decay event) {
public void onBlockBreak(ChangeBlockEvent.Decay event) {
onChangeBlock(event);
}
@Listener
public void onBlockBreak(final ChangeBlockEvent.Grow event) {
public void onBlockBreak(ChangeBlockEvent.Grow event) {
onChangeBlock(event);
}
@Listener
public void onBlockBreak(final ChangeBlockEvent.Modify event) {
public void onBlockBreak(ChangeBlockEvent.Modify event) {
onChangeBlock(event);
}
@Listener
public void onBlockBreak(final ChangeBlockEvent.Break event) {
public void onBlockBreak(ChangeBlockEvent.Break event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
// SpongeUtil.printCause("break", event.getCause());
return;
}
final PlotPlayer pp = SpongeUtil.getPlayer(player);
final World world = event.getTargetWorld();
final String worldname = world.getName();
PlotPlayer pp = SpongeUtil.getPlayer(player);
World world = event.getTargetWorld();
String worldname = world.getName();
if (!PS.get().hasPlotArea(worldname)) {
return;
}
@ -491,8 +499,8 @@ public class MainListener {
return;
} else {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER);
final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break");
final BlockState state = pos.getState();
Flag destroy = FlagManager.getPlotFlagRaw(plot, "break");
BlockState state = pos.getState();
if ((destroy == null) || !((HashSet<PlotBlock>) destroy.getValue()).contains(SpongeUtil.getPlotBlock(state))) {
event.setCancelled(true);
return;
@ -509,10 +517,7 @@ public class MainListener {
if (loc.getPlotAbs() == null) {
return true;
}
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) {
return false;
}
return true;
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD);
}
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) {
@ -524,8 +529,8 @@ public class MainListener {
if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) {
return true;
} else {
final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break");
final BlockState state = l.getBlock();
Flag destroy = FlagManager.getPlotFlagRaw(plot, "break");
BlockState state = l.getBlock();
if ((destroy != null) && ((HashSet<PlotBlock>) destroy.getValue()).contains(SpongeUtil.getPlotBlock(state))) {
return true;
}
@ -537,15 +542,15 @@ public class MainListener {
}
@Listener
public void onBlockPlace(final ChangeBlockEvent.Place event) {
public void onBlockPlace(ChangeBlockEvent.Place event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
// SpongeUtil.printCause("place", event.getCause());
return;
}
final PlotPlayer pp = SpongeUtil.getPlayer(player);
final World world = event.getTargetWorld();
final String worldname = world.getName();
PlotPlayer pp = SpongeUtil.getPlayer(player);
World world = event.getTargetWorld();
String worldname = world.getName();
if (!PS.get().hasPlotArea(worldname)) {
return;
}
@ -575,8 +580,8 @@ public class MainListener {
return;
} else {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
final Flag BUILD = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s());
final BlockState state = pos.getState();
Flag BUILD = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s());
BlockState state = pos.getState();
if ((BUILD == null) || !((HashSet<PlotBlock>) BUILD.getValue()).contains(SpongeUtil.getPlotBlock(state))) {
event.setCancelled(true);
return;
@ -593,10 +598,7 @@ public class MainListener {
if (loc.getPlotAbs() == null) {
return true;
}
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) {
return false;
}
return true;
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD);
}
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) {
@ -608,8 +610,8 @@ public class MainListener {
if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
return true;
} else {
final Flag build = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s());
final BlockState state = l.getBlock();
Flag build = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s());
BlockState state = l.getBlock();
if ((build != null) && ((HashSet<PlotBlock>) build.getValue()).contains(SpongeUtil.getPlotBlock(state))) {
return true;
}
@ -621,19 +623,19 @@ public class MainListener {
}
@Listener
public void onJoin(final ClientConnectionEvent.Join event) {
final Player player = event.getTargetEntity();
public void onJoin(ClientConnectionEvent.Join event) {
Player player = event.getTargetEntity();
SpongeUtil.getPlayer(player).unregister();
final PlotPlayer pp = SpongeUtil.getPlayer(player);
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Now
String name = pp.getName();
StringWrapper sw = new StringWrapper(name);
final UUID uuid = pp.getUUID();
UUID uuid = pp.getUUID();
UUIDHandler.add(sw, uuid);
Location loc = pp.getLocation();
PlotArea area = loc.getPlotArea();
final Plot plot;
Plot plot;
if (area != null) {
plot = area.getPlot(loc);
if (plot != null) {
@ -654,20 +656,20 @@ public class MainListener {
}
@Listener
public void onQuit(final ClientConnectionEvent.Disconnect event) {
final Player player = event.getTargetEntity();
final PlotPlayer pp = SpongeUtil.getPlayer(player);
public void onQuit(ClientConnectionEvent.Disconnect event) {
Player player = event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
pp.unregister();
}
@Listener
public void onMove(final DisplaceEntityEvent.TargetPlayer event) {
public void onMove(DisplaceEntityEvent.TargetPlayer event) {
org.spongepowered.api.world.Location<World> from = event.getFromTransform().getLocation();
org.spongepowered.api.world.Location<World> to = event.getToTransform().getLocation();
int x2;
if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) {
final Player player = event.getTargetEntity();
final PlotPlayer pp = SpongeUtil.getPlayer(player);
Player player = event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location
@ -679,7 +681,7 @@ public class MainListener {
return;
}
Plot now = area.getPlotAbs(loc);
final Plot lastPlot = pp.getMeta("lastplot");
Plot lastPlot = pp.getMeta("lastplot");
if (now == null) {
if (lastPlot != null && !PlotListener.plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
@ -699,7 +701,7 @@ public class MainListener {
event.setCancelled(true);
return;
}
final Integer border = area.getBorder();
Integer border = area.getBorder();
if (x2 > border) {
to.sub(x2 - border + 4, 0, 0);
player.setLocation(to);
@ -715,8 +717,8 @@ public class MainListener {
}
int z2;
if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) {
final Player player = event.getTargetEntity();
final PlotPlayer pp = SpongeUtil.getPlayer(player);
Player player = event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location
@ -728,7 +730,7 @@ public class MainListener {
return;
}
Plot now = area.getPlotAbs(loc);
final Plot lastPlot = pp.getMeta("lastplot");
Plot lastPlot = pp.getMeta("lastplot");
if (now == null) {
if (lastPlot != null && !PlotListener.plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
@ -748,7 +750,7 @@ public class MainListener {
event.setCancelled(true);
return;
}
final Integer border = area.getBorder();
Integer border = area.getBorder();
if (z2 > border) {
to.add(0, 0, z2 - border - 4);
player.setLocation(to);

View File

@ -30,7 +30,7 @@ public class FastQueue extends SlowQueue {
public final SendChunk chunkSender;
public HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
public FastQueue() throws NoSuchMethodException, RuntimeException {
public FastQueue() throws RuntimeException {
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {