diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index ff6bdf1ea..59b9dc034 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java index 1a4176a6a..0d2ffb8e6 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java @@ -18,7 +18,7 @@ import java.util.Collection; */ public final class ArrayWrapper { - private E[] _array; + private E[] array; /** * Creates an array wrapper with some elements. @@ -64,7 +64,7 @@ public final class ArrayWrapper { * @return The array wrapped by this instance. */ public E[] getArray() { - return this._array; + return this.array; } /** @@ -73,7 +73,7 @@ public final class ArrayWrapper { */ 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 { 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 { */ @Override public int hashCode() { - return Arrays.hashCode(this._array); + return Arrays.hashCode(this.array); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java index d31ffb194..f1207485d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java @@ -41,12 +41,12 @@ import java.util.logging.Level; * provided by the vanilla Minecraft JSON message formatter. * This class allows plugins to emulate the functionality of the vanilla Minecraft * tellraw command. - *

- * 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. - *

+ *

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.

*/ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java index a78f0d3fb..e7589ab84 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java @@ -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, including the trailing dot. */ - 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); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java index 414384309..47f1dfc7e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java @@ -178,25 +178,23 @@ public class ClassicPlotMeConnector extends APlotMeConnector { if (denied == null) { if ("*".equals(name)) { denied = DBFunc.everyone; - } else { - if (DBFunc.hasColumn(resultSet, "playerid")) { - try { - byte[] bytes = resultSet.getBytes("playerid"); - if (bytes != null) { - try { - ByteBuffer bb = ByteBuffer.wrap(bytes); - long high = bb.getLong(); - long low = bb.getLong(); - denied = new UUID(high, low); - } catch (Exception e) { - e.printStackTrace(); - denied = UUID.nameUUIDFromBytes(bytes); - } - UUIDHandler.add(new StringWrapper(name), denied); + } else if (DBFunc.hasColumn(resultSet, "playerid")) { + try { + byte[] bytes = resultSet.getBytes("playerid"); + if (bytes != null) { + try { + ByteBuffer bb = ByteBuffer.wrap(bytes); + long high = bb.getLong(); + long low = bb.getLong(); + denied = new UUID(high, low); + } catch (Exception e) { + e.printStackTrace(); + denied = UUID.nameUUIDFromBytes(bytes); } - } catch (SQLException e) { - e.printStackTrace(); + UUIDHandler.add(new StringWrapper(name), denied); } + } catch (SQLException e) { + e.printStackTrace(); } } if (denied == null) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java index b6f857aa6..711ed0139 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java @@ -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,60 +51,56 @@ 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(); } } 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 getPlotMeWorlds(final FileConfiguration plotConfig) { + + public Set 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,36 +112,35 @@ 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; } - + String version = plotConfig.getString("Version"); if (version == null) { version = plotConfig.getString("version"); @@ -153,66 +148,67 @@ public class LikePlotMeConverter { if (!connector.accepts(version)) { return false; } - + 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'"); - - mergeWorldYml(plugin, plotConfig); - - sendMessage("Connecting to " + plugin + " DB"); - final ArrayList createdPlots = new ArrayList<>(); - + sendMessage(this.plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'"); + + mergeWorldYml(this.plugin, plotConfig); + + sendMessage("Connecting to " + this.plugin + " DB"); + + ArrayList createdPlots = new ArrayList<>(); + sendMessage("Collecting plot data"); - - final String dbPrefix = plugin.toLowerCase(); + + String dbPrefix = this.plugin.toLowerCase(); sendMessage(" - " + dbPrefix + "Plots"); final Set 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> plots = connector.getPlotMePlots(connection); + HashMap> plots = connector.getPlotMePlots(connection); int plotCount = 0; - for (final Entry> entry : plots.entrySet()) { + for (Entry> entry : plots.entrySet()) { plotCount += entry.getValue().size(); } if (!Settings.CONVERT_PLOTME) { return false; } - + 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> 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,13 +384,13 @@ public class LikePlotMeConverter { } } }); - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); PS.debug("&/end/"); } return true; } - + public void done() { PS.get().setPlots(DBFunc.getPlots()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java index d21dbaab4..c55334be0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java @@ -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> getPlotMePlots(final Connection connection) throws SQLException { - ResultSet r; - PreparedStatement stmt; - final HashMap plotWidth = new HashMap<>(); - final HashMap roadWidth = new HashMap<>(); - final HashMap plots = new HashMap<>(); - final HashMap> merges = new HashMap<>(); + public HashMap> getPlotMePlots(Connection connection) throws SQLException { + ResultSet resultSet; + PreparedStatement statement; + HashMap plotWidth = new HashMap<>(); + HashMap roadWidth = new HashMap<>(); + HashMap plots = new HashMap<>(); + HashMap> 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()); } 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 entry : plots.entrySet()) { - final Plot plot = entry.getValue(); - final HashMap mergeMap = merges.get(plot.getArea().worldname); + for (Entry entry : plots.entrySet()) { + Plot plot = entry.getValue(); + HashMap 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> processed = new HashMap<>(); - - for (final Entry entry : plots.entrySet()) { - final Plot plot = entry.getValue(); + HashMap> processed = new HashMap<>(); + + for (Entry entry : plots.entrySet()) { + Plot plot = entry.getValue(); HashMap map = processed.get(plot.getArea().worldname); if (map == null) { map = new HashMap<>(); @@ -187,9 +190,9 @@ public class PlotMeConnector_017 extends APlotMeConnector { } return processed; } - + @Override - public boolean accepts(final String version) { + public boolean accepts(String version) { if (version == null) { return false; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java index 0e1797ff2..bd6f78de9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java @@ -29,17 +29,20 @@ import java.util.Collections; import java.util.HashSet; public class WEListener implements Listener { - - public final HashSet rad1 = new HashSet<>(Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size")); + + public final HashSet rad1 = new HashSet<>( + Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size")); public final HashSet rad2 = new HashSet<>(Arrays.asList("fill", "fillr", "removenear", "remove")); public final HashSet rad2_1 = new HashSet<>(Arrays.asList("hcyl", "cyl")); public final HashSet rad2_2 = new HashSet<>(Arrays.asList("sphere", "pyramid")); public final HashSet rad2_3 = new HashSet<>(Collections.singletonList("brush smooth")); public final HashSet rad3_1 = new HashSet<>(Collections.singletonList("brush gravity")); public final HashSet rad3_2 = new HashSet<>(Arrays.asList("brush sphere", "brush cylinder")); - - public final HashSet 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 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 regionExtend = new HashSet<>(Collections.singletonList("stack")); public final HashSet restricted = new HashSet<>(Collections.singletonList("up")); public final HashSet other = new HashSet<>(Arrays.asList("undo", "redo")); @@ -152,7 +155,7 @@ public class WEListener implements Listener { } return true; } - + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public boolean onPlayerCommand(PlayerCommandPreprocessEvent e) { WorldEditPlugin worldedit = BukkitMain.worldEdit; @@ -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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java index 3d3ad540d..ec7da5fa9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java @@ -6,32 +6,34 @@ import org.bukkit.OfflinePlayer; import java.util.UUID; 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. + *

Please do not use this method. Instead use BukkitUtil.getPlayer(Player), + * as it caches player objects.

+ * * @param player */ public BukkitOfflinePlayer(OfflinePlayer player) { this.player = player; } - + @Override public UUID getUUID() { return this.player.getUniqueId(); } - + @Override public long getLastPlayed() { return this.player.getLastPlayed(); } - + @Override public boolean isOnline() { return this.player.isOnline(); } - + @Override public String getName() { return this.player.getName(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java index d9ddf5761..f8929f4e0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java @@ -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. + *

Please do not use this method. Instead use BukkitUtil.getPlayer(Player), + * as it caches player objects.

* @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; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java index 0654b8509..20377192e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java @@ -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; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java index e87d146b8..3365d2653 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -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 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 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)) { @@ -61,30 +60,30 @@ public class StateWrapper { } return true; } - + 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 values = new HashMap<>(); + if (this.state instanceof InventoryHolder) { + InventoryHolder inv = (InventoryHolder) this.state; + ItemStack[] contents = inv.getInventory().getContents(); + Map values = new HashMap<>(); values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents))); return new CompoundTag(values); } return null; } - + public String getId() { return "Chest"; } - - public List serializeInventory(final ItemStack[] items) { - final List tags = new ArrayList<>(); + + public List serializeInventory(ItemStack[] items) { + List tags = new ArrayList<>(); for (int i = 0; i < items.length; ++i) { if (items[i] != null) { - final Map tagData = serializeItem(items[i]); + Map tagData = serializeItem(items[i]); tagData.put("Slot", new ByteTag("Slot", (byte) i)); tags.add(new CompoundTag(tagData)); } @@ -103,21 +102,21 @@ public class StateWrapper { return data; } */ - - public Map serializeItem(final ItemStack item) { - final Map data = new HashMap<>(); + + public Map serializeItem(ItemStack item) { + Map 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 enchantmentList = new ArrayList<>(); - for (final Entry entry : item.getEnchantments().entrySet()) { - final Map enchantment = new HashMap<>(); + List enchantmentList = new ArrayList<>(); + for (Entry entry : item.getEnchantments().entrySet()) { + Map 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 auxData = new HashMap<>(); + Map auxData = new HashMap<>(); auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList)); data.put("tag", new CompoundTag("tag", auxData)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java index a0481190a..8a8f2c3b1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java @@ -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; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java index fc23d0cbd..7dad3d86e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java @@ -18,6 +18,8 @@ import java.util.Map; * */ public class DefaultTitleManager_183 { + + private static final Map, Class> CORRESPONDING_TYPES = new HashMap<>(); /* Title packet */ private Class packetTitle; /* Title packet actions ENUM */ @@ -36,8 +38,7 @@ public class DefaultTitleManager_183 { private int stayTime = -1; private int fadeOutTime = -1; private boolean ticks = false; - private static final Map, Class> CORRESPONDING_TYPES = new HashMap<>(); - + /** * Create a new 1.8 title * @@ -45,11 +46,11 @@ 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(); } - + /** * Create a new 1.8 title * @@ -59,12 +60,12 @@ 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(); } - + /** * Copy 1.8 title * @@ -72,19 +73,19 @@ 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(); } - + /** * Create a new 1.8 title * @@ -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; @@ -108,121 +109,133 @@ public class DefaultTitleManager_183 { this.fadeOutTime = fadeOutTime; 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; } - + /** * Get subtitle text * * @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; + } + /** * Set the title 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 * * @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 * * @param time * Time */ - public void setFadeInTime(final int time) { - fadeInTime = time; + public void setFadeInTime(int time) { + this.fadeInTime = time; } - + /** * Set title fade out time * * @param time * Time */ - public void setFadeOutTime(final int time) { - fadeOutTime = time; + public void setFadeOutTime(int time) { + this.fadeOutTime = time; } - + /** * Set title stay time * * @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; } - + /** * Send the title to a player * @@ -232,46 +245,54 @@ 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); } } } - + /** * Broadcast the title to all players * @throws Exception */ public void broadcast() throws Exception { - for (final Player p : Bukkit.getOnlinePlayers()) { + for (Player p : Bukkit.getOnlinePlayers()) { send(p); } } - + /** * Clear the title * @@ -280,16 +301,16 @@ 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); } - + /** * Reset the title settings * @@ -302,85 +323,73 @@ 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; } } return null; } - + 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; @@ -388,8 +397,8 @@ 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; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 357068f11..c4abbde65 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -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 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 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) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java index 999bdff4a..9d7f52d2b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java @@ -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() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java index d0262d184..d578e2297 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java index 9cb43a190..334127b15 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java @@ -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 diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java index 3666a1b9d..0ccb98fd0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java @@ -48,7 +48,7 @@ public class FastChunk_1_8_3 extends PlotChunk { } /** - * 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 { } /** - * Get the raw data for a section + * Get the raw data for a section. * @param i * @return */ diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java index 73502bbd3..ef6fcca73 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java @@ -48,7 +48,7 @@ public class FastChunk_1_9 extends PlotChunk { } /** - * 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 { } /** - * 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 { } /** - * Get the raw data for a section + * Get the raw data for a section. * @param i * @return */ diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java index bd5d0c413..91a734ead 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java @@ -39,7 +39,7 @@ public class FastQueue_1_7 extends SlowQueue { private final HashMap 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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java index f1dafe14c..c391e4743 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java @@ -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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java index fa7d165ae..7d7f3833b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java @@ -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"); diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java index 587f14167..7fa508a0a 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java @@ -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. *

@@ -22,8 +23,8 @@ public interface ConfigurationSection { * list. * @return Set of keys contained within this ConfigurationSection. */ - Set getKeys(final boolean deep); - + Set getKeys(boolean deep); + /** * Gets a Map containing all keys and their values for this section. *

@@ -38,8 +39,8 @@ public interface ConfigurationSection { * list. * @return Map of keys and values of this section. */ - Map getValues(final boolean deep); - + Map getValues(boolean deep); + /** * Checks if this {@link ConfigurationSection} contains the given path. *

@@ -51,8 +52,8 @@ 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 * given path. @@ -65,8 +66,8 @@ 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 * Configuration} @@ -83,7 +84,7 @@ public interface ConfigurationSection { * @return Path of this section relative to its root */ String getCurrentPath(); - + /** * Gets the name of this individual {@link ConfigurationSection}, in the * path. @@ -94,7 +95,7 @@ public interface ConfigurationSection { * @return Name of this section */ String getName(); - + /** * Gets the root {@link Configuration} that contains this {@link * ConfigurationSection} @@ -108,7 +109,7 @@ public interface ConfigurationSection { * @return Root configuration containing this section. */ Configuration getRoot(); - + /** * Gets the parent {@link ConfigurationSection} that directly contains * this {@link ConfigurationSection}. @@ -121,7 +122,7 @@ public interface ConfigurationSection { * @return Parent section containing this section. */ ConfigurationSection getParent(); - + /** * Gets the requested Object by path. *

@@ -132,8 +133,8 @@ 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 * found. @@ -146,8 +147,8 @@ 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,8 +163,8 @@ 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,8 +175,8 @@ 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 * specified values. @@ -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. *

@@ -201,8 +203,8 @@ 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 * found. @@ -216,60 +218,60 @@ 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. - *

- * If the path exists but is not a String, this will return false. If the + * + *

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.

* * @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. - *

- * If the int does not exist but a default value has been specified, this + * + *

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.

* * @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. - *

- * If the int does not exist then the specified default value will + * + *

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}.

* * @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. - *

- * If the path exists but is not a int, this will return false. If the + * + *

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.

* * @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,8 +282,8 @@ 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 * found. @@ -295,8 +297,8 @@ 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,8 +310,8 @@ 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,8 +322,8 @@ 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 * found. @@ -335,8 +337,8 @@ 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,8 +350,8 @@ 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,8 +362,8 @@ 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 * found. @@ -375,8 +377,8 @@ 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. *

@@ -401,8 +404,8 @@ 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 * found. @@ -416,8 +419,8 @@ 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,8 +432,8 @@ 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,8 +447,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of String. */ - List getStringList(final String path); - + List getStringList(String path); + /** * Gets the requested List of Integer by path. *

@@ -459,8 +462,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Integer. */ - List getIntegerList(final String path); - + List getIntegerList(String path); + /** * Gets the requested List of Boolean by path. *

@@ -474,8 +477,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Boolean. */ - List getBooleanList(final String path); - + List getBooleanList(String path); + /** * Gets the requested List of Double by path. *

@@ -489,8 +492,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Double. */ - List getDoubleList(final String path); - + List getDoubleList(String path); + /** * Gets the requested List of Float by path. *

@@ -504,8 +507,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Float. */ - List getFloatList(final String path); - + List getFloatList(String path); + /** * Gets the requested List of Long by path. *

@@ -519,8 +522,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Long. */ - List getLongList(final String path); - + List getLongList(String path); + /** * Gets the requested List of Byte by path. *

@@ -534,8 +537,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Byte. */ - List getByteList(final String path); - + List getByteList(String path); + /** * Gets the requested List of Character by path. *

@@ -549,8 +552,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Character. */ - List getCharacterList(final String path); - + List getCharacterList(String path); + /** * Gets the requested List of Short by path. *

@@ -564,8 +567,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Short. */ - List getShortList(final String path); - + List getShortList(String path); + /** * Gets the requested List of Maps by path. *

@@ -579,8 +582,8 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Maps. */ - List> getMapList(final String path); - + List> getMapList(String path); + /** * Gets the requested ConfigurationSection by path. *

@@ -592,8 +595,8 @@ 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,8 +609,8 @@ 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 * {@link Configuration} defined in {@link #getRoot()}. @@ -619,7 +622,7 @@ public interface ConfigurationSection { * @return Equivalent section in root configuration */ ConfigurationSection getDefaultSection(); - + /** * Sets the default value in the root at the given path as provided. *

@@ -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); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java index 6099d235f..b170567ac 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java @@ -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 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,15 +77,15 @@ 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); } } 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,15 +95,15 @@ 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); } } 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,14 +113,14 @@ 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); } } return def; } - + /** * Creates a full path to the given {@link ConfigurationSection} from its * root {@link Configuration}. @@ -131,10 +132,10 @@ 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()); } - + /** * Creates a relative path to the given {@link ConfigurationSection} from * the given relative section. @@ -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); @@ -176,14 +177,14 @@ public class MemorySection implements ConfigurationSection { return builder.toString(); } - - @Override - public Set getKeys(final boolean deep) { - final Set result = new LinkedHashSet<>(); - final Configuration root = getRoot(); + @Override + public Set getKeys(boolean deep) { + Set result = new LinkedHashSet<>(); + + Configuration root = getRoot(); if ((root != null) && root.options().copyDefaults()) { - final ConfigurationSection defaults = getDefaultSection(); + ConfigurationSection defaults = getDefaultSection(); if (defaults != null) { result.addAll(defaults.getKeys(deep)); @@ -194,14 +195,14 @@ public class MemorySection implements ConfigurationSection { return result; } - - @Override - public Map getValues(final boolean deep) { - final Map result = new LinkedHashMap<>(); - final Configuration root = getRoot(); + @Override + public Map getValues(boolean deep) { + Map result = new LinkedHashMap<>(); + + Configuration root = getRoot(); if ((root != null) && root.options().copyDefaults()) { - final ConfigurationSection defaults = getDefaultSection(); + ConfigurationSection defaults = getDefaultSection(); if (defaults != null) { result.putAll(defaults.getValues(deep)); @@ -212,15 +213,15 @@ public class MemorySection implements ConfigurationSection { return result; } - + @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; } @@ -229,34 +230,34 @@ public class MemorySection implements ConfigurationSection { } return get(path, null) != null; } - + @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"); } @@ -265,11 +266,11 @@ public class MemorySection implements ConfigurationSection { } root.addDefault(createPath(this, path), value); } - + @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())) { @@ -279,26 +280,26 @@ public class MemorySection implements ConfigurationSection { return null; } - + @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,25 +307,25 @@ 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); } } - + @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); - for (final Map.Entry entry : map.entrySet()) { + @Override + public ConfigurationSection createSection(String path, Map map) { + ConfigurationSection section = createSection(path); + + for (Map.Entry entry : map.entrySet()) { if (entry.getValue() instanceof Map) { section.createSection(entry.getKey().toString(), (Map) entry.getValue()); } else { @@ -406,128 +412,140 @@ public class MemorySection implements ConfigurationSection { return section; } - + // 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 getStringList(final String path) { - final List list = getList(path); + public List getStringList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List result = new ArrayList<>(); - for (final Object object : list) { + for (Object object : list) { if ((object instanceof String) || isPrimitiveWrapper(object)) { result.add(String.valueOf(object)); } @@ -535,18 +553,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getIntegerList(final String path) { - final List list = getList(path); + public List getIntegerList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -563,18 +581,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getBooleanList(final String path) { - final List list = getList(path); + public List getBooleanList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -588,18 +606,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getDoubleList(final String path) { - final List list = getList(path); + public List getDoubleList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -616,18 +634,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getFloatList(final String path) { - final List list = getList(path); + public List getFloatList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -644,18 +662,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getLongList(final String path) { - final List list = getList(path); + public List getLongList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -672,18 +690,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getByteList(final String path) { - final List list = getList(path); + public List getByteList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -700,22 +718,22 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getCharacterList(final String path) { - final List list = getList(path); + public List getCharacterList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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)); @@ -727,18 +745,18 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List getShortList(final String path) { - final List list = getList(path); + public List getShortList(String path) { + List list = getList(path); if (list == null) { return new ArrayList<>(0); } - final List result = new ArrayList<>(); + List 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) { @@ -755,17 +773,17 @@ public class MemorySection implements ConfigurationSection { return result; } - + @Override - public List> getMapList(final String path) { - final List list = getList(path); - final List> result = new ArrayList<>(); + public List> getMapList(String path) { + List list = getList(path); + List> 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); } @@ -773,9 +791,9 @@ public class MemorySection implements ConfigurationSection { return result; } - + @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; @@ -784,60 +802,60 @@ public class MemorySection implements ConfigurationSection { val = get(path, getDefault(path)); return (val instanceof ConfigurationSection) ? createSection(path) : null; } - + @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) - || (input instanceof Byte) - || (input instanceof Short) - || (input instanceof Double) - || (input instanceof Long) - || (input instanceof Float); + || (input instanceof Boolean) + || (input instanceof Character) + || (input instanceof Byte) + || (input instanceof Short) + || (input instanceof Double) + || (input instanceof Long) + || (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 output, final ConfigurationSection section, final boolean deep) { - if (section instanceof MemorySection) { - final MemorySection sec = (MemorySection) section; - for (final Map.Entry entry : sec.map.entrySet()) { + protected void mapChildrenKeys(Set output, ConfigurationSection section, boolean deep) { + if (section instanceof MemorySection) { + MemorySection sec = (MemorySection) section; + + for (Map.Entry 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 keys = section.getKeys(deep); + Set keys = section.getKeys(deep); - for (final String key : keys) { + for (String key : keys) { output.add(createPath(section, key, this)); } } } - - protected void mapChildrenValues(final Map output, final ConfigurationSection section, final boolean deep) { - if (section instanceof MemorySection) { - final MemorySection sec = (MemorySection) section; - for (final Map.Entry entry : sec.map.entrySet()) { + protected void mapChildrenValues(Map output, ConfigurationSection section, boolean deep) { + if (section instanceof MemorySection) { + MemorySection sec = (MemorySection) section; + + for (Map.Entry entry : sec.map.entrySet()) { output.put(createPath(section, entry.getKey(), this), entry.getValue()); if (entry.getValue() instanceof ConfigurationSection) { @@ -847,17 +865,17 @@ public class MemorySection implements ConfigurationSection { } } } else { - final Map values = section.getValues(deep); + Map values = section.getValues(deep); - for (final Map.Entry entry : values.entrySet()) { + for (Map.Entry entry : values.entrySet()) { output.put(createPath(section, entry.getKey(), this), entry.getValue()); } } } - + @Override public String toString() { - final Configuration root = getRoot(); + Configuration root = getRoot(); return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + (root == null ? null : root.getClass().getSimpleName()) + "']"; } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java index ba3ae6736..0640894a5 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java @@ -15,73 +15,224 @@ 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 static final Map> aliases = + new HashMap>(); private final Class clazz; - private static Map> aliases = new HashMap>(); - - protected ConfigurationSerialization(final Class clazz) { + + protected ConfigurationSerialization(Class 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. + * + *

The class must implement {@link ConfigurationSerializable}, including + * the extra methods as specified in the javadoc of + * ConfigurationSerializable.

+ * + *

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(Map args, Class clazz) { + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * + * given class. + *

+ * The class must implement {@link ConfigurationSerializable}, including + * the extra methods as specified in the javadoc of + * ConfigurationSerializable.

+ * + *

+ * 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(Map args) { + Class clazz = null; + + if (args.containsKey(SERIALIZED_TYPE_KEY)) { + try { + 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 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 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 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 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 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 { - final Method method = clazz.getDeclaredMethod(name, Map.class); - + Method method = this.clazz.getDeclaredMethod(name, Map.class); + if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { return null; } if (Modifier.isStatic(method.getModifiers()) != isStatic) { return null; } - + return method; - } catch (final NoSuchMethodException ex) { + } catch (NoSuchMethodException ex) { return null; - } catch (final SecurityException ex) { + } catch (SecurityException ex) { return null; } } - + protected Constructor 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 args) { + + protected ConfigurationSerializable deserializeViaMethod(Method method, Map 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", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + } 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 ctor, final Map args) { + + protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map 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", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + } 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 args) { + + public ConfigurationSerializable deserialize(Map args) { if (args == null) { throw new NullPointerException("Args must not be null"); } @@ -94,162 +245,20 @@ public class ConfigurationSerialization { if (result == null) { method = getMethod("valueOf", true); - + if (method != null) { result = deserializeViaMethod(method, args); } } - + if (result == null) { - final Constructor constructor = getConstructor(); - + Constructor constructor = getConstructor(); + if (constructor != null) { result = deserializeViaCtor(constructor, args); } } - + return result; } - - /** - * Attempts to deserialize the given arguments into a new instance of the - * given class. - *

- * The class must implement {@link ConfigurationSerializable}, including - * the extra methods as specified in the javadoc of - * ConfigurationSerializable. - *

- * 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 args, final Class clazz) { - return new ConfigurationSerialization(clazz).deserialize(args); - } - - /** - * Attempts to deserialize the given arguments into a new instance of the - * given class. - *

- * The class must implement {@link ConfigurationSerializable}, including - * the extra methods as specified in the javadoc of - * ConfigurationSerializable. - *

- * 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 args) { - Class 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 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 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 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 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 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(); - } } diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java index 03fa21b42..ea5547aa2 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java @@ -9,29 +9,30 @@ import java.util.Map; * The {@code TAG_Compound} tag. */ public final class CompoundTag extends Tag { + private Map value; - + /** * Creates the tag with an empty name. * * @param value the value of the tag */ - public CompoundTag(final Map value) { + public CompoundTag(Map value) { super(); this.value = Collections.unmodifiableMap(value); } - + /** * Creates the tag. * * @param name the name of the tag * @param value the value of the tag */ - public CompoundTag(final String name, final Map value) { + public CompoundTag(String name, Map value) { super(name); this.value = Collections.unmodifiableMap(value); } - + /** * Returns whether this compound tag contains the given key. * @@ -39,15 +40,15 @@ 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 getValue() { - return value; + return this.value; } - + /** * Return a new compound tag with the given values. * @@ -55,42 +56,43 @@ public final class CompoundTag extends Tag { * * @return the new compound tag */ - public CompoundTag setValue(final Map value) { + public CompoundTag setValue(Map value) { if (value == null) { this.value = Collections.unmodifiableMap(new HashMap()); - } - else { + } else { this.value = Collections.unmodifiableMap(value); } return this; } - + /** * Create a compound tag builder. * * @return the builder */ public CompoundTagBuilder createBuilder() { - return new CompoundTagBuilder(new HashMap(value)); + return new CompoundTagBuilder(new HashMap(this.value)); } - + /** - * Get a byte array named with the given key.

If the key does not exist or its value is not a byte array + * Get a byte array named with the given key. + * + *

If the key does not exist or its value is not a byte array * tag, then an empty byte array will be returned.

* * @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 { return new byte[0]; } } - + /** * Get a byte named with the given key.

If the key does not exist or its value is not a byte tag, then * {@code 0} will be returned.

@@ -99,15 +101,15 @@ 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 { return (byte) 0; } } - + /** * Get a double named with the given key.

If the key does not exist or its value is not a double tag, then * {@code 0} will be returned.

@@ -116,15 +118,15 @@ 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 { return 0; } } - + /** * Get a double named with the given key, even if it's another type of number.

If the key does not exist or * its value is not a number, then {@code 0} will be returned.

@@ -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) { @@ -151,7 +153,7 @@ public final class CompoundTag extends Tag { return 0; } } - + /** * Get a float named with the given key.

If the key does not exist or its value is not a float tag, then * {@code 0} will be returned.

@@ -160,15 +162,15 @@ 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 { return 0; } } - + /** * Get a {@code int[]} named with the given key.

If the key does not exist or its value is not an int array * tag, then an empty array will be returned.

@@ -177,15 +179,15 @@ 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 { return new int[0]; } } - + /** * Get an int named with the given key.

If the key does not exist or its value is not an int tag, then * {@code 0} will be returned.

@@ -194,15 +196,15 @@ 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 { return 0; } } - + /** * Get an int named with the given key, even if it's another type of number.

If the key does not exist or * its value is not a number, then {@code 0} will be returned.

@@ -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) { @@ -229,7 +231,7 @@ public final class CompoundTag extends Tag { return 0; } } - + /** * Get a list of tags named with the given key.

If the key does not exist or its value is not a list tag, * then an empty list will be returned.

@@ -238,15 +240,15 @@ public final class CompoundTag extends Tag { * * @return a list of tags */ - public List getList(final String key) { - final Tag tag = value.get(key); + public List getList(String key) { + Tag tag = this.value.get(key); if (tag instanceof ListTag) { return ((ListTag) tag).getValue(); } else { return Collections.emptyList(); } } - + /** * Get a {@code TagList} named with the given key.

If the key does not exist or its value is not a list * tag, then an empty tag list will be returned.

@@ -255,15 +257,15 @@ 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. emptyList()); + return new ListTag(key, StringTag.class, Collections.emptyList()); } } - + /** * Get a list of tags named with the given key.

If the key does not exist or its value is not a list tag, * then an empty list will be returned. If the given key references a list but the list of of a different type, then @@ -276,10 +278,10 @@ public final class CompoundTag extends Tag { * @return a list of tags */ @SuppressWarnings("unchecked") - public List getList(final String key, final Class listType) { - final Tag tag = value.get(key); + public List getList(String key, Class 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) listTag.getValue(); } else { @@ -289,7 +291,7 @@ public final class CompoundTag extends Tag { return Collections.emptyList(); } } - + /** * Get a long named with the given key.

If the key does not exist or its value is not a long tag, then * {@code 0} will be returned.

@@ -298,15 +300,15 @@ 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 { return 0L; } } - + /** * Get a long named with the given key, even if it's another type of number.

If the key does not exist or * its value is not a number, then {@code 0} will be returned.

@@ -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) { @@ -333,7 +335,7 @@ public final class CompoundTag extends Tag { return 0L; } } - + /** * Get a short named with the given key.

If the key does not exist or its value is not a short tag, then * {@code 0} will be returned.

@@ -342,15 +344,15 @@ 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 { return 0; } } - + /** * Get a string named with the given key.

If the key does not exist or its value is not a string tag, then * {@code ""} will be returned.

@@ -359,25 +361,25 @@ 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 { return ""; } } - + @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 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 entry : this.value.entrySet()) { bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); } bldr.append("}"); diff --git a/Core/src/main/java/com/intellectualcrafters/json/CDL.java b/Core/src/main/java/com/intellectualcrafters/json/CDL.java index 0c791c6e4..e09a05478 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/CDL.java +++ b/Core/src/main/java/com/intellectualcrafters/json/CDL.java @@ -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; @@ -60,7 +61,7 @@ public class CDL { return x.nextTo(','); } } - + /** * Produce a JSONArray of strings from a row of comma delimited values. * @@ -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; } @@ -93,7 +94,7 @@ public class CDL { } } } - + /** * Produce a JSONObject from a row of comma delimited text, using a parallel JSONArray of strings to provides the * names of the elements. @@ -106,11 +107,11 @@ 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; } - + /** * Produce a comma delimited text row from a JSONArray. Values containing the comma character will be quoted. * Troublesome characters may be removed. @@ -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); } @@ -147,7 +148,7 @@ public class CDL { sb.append('\n'); return sb.toString(); } - + /** * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * @@ -157,10 +158,10 @@ 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)); } - + /** * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * @@ -170,10 +171,10 @@ 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); } - + /** * Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of * element names. @@ -185,10 +186,10 @@ 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)); } - + /** * Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of * element names. @@ -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; } @@ -217,7 +218,7 @@ public class CDL { } return ja; } - + /** * Produce a comma delimited text from a JSONArray of JSONObjects. The first row will be a list of names obtained by * inspecting the first JSONObject. @@ -228,17 +229,17 @@ 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); } } return null; } - + /** * Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names. The list of names * is not included in the output. @@ -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))); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PS.java b/Core/src/main/java/com/intellectualcrafters/plot/PS.java index e8e726521..e8f81cf02 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/PS.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/PS.java @@ -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 getPlotAreas(String world) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java index a80686607..ae03d2211 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java @@ -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 MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ")"); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Visit.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Visit.java index 234fbe406..19e9b6cf0 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Visit.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Visit.java @@ -64,11 +64,11 @@ public class Visit extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { - int page = Integer.MIN_VALUE; - Collection unsorted = null; if (args.length == 1 && args[0].contains(":")) { args = args[0].split(":"); } + int page = Integer.MIN_VALUE; + Collection unsorted = null; switch (args.length) { case 2: { if (!MathMan.isInteger(args[1])) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/config/Configuration.java b/Core/src/main/java/com/intellectualcrafters/plot/config/Configuration.java index dc6ef9625..39219bd9f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/config/Configuration.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/config/Configuration.java @@ -32,90 +32,90 @@ import java.util.ArrayList; */ public class Configuration { - + public static final SettingValue STRING = new SettingValue("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 STRINGLIST = new SettingValue("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 = new SettingValue("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 = new SettingValue("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 = new SettingValue("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 BIOME = new SettingValue("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 BLOCK = new SettingValue("BLOCK") { @Override - public boolean validateValue(final String string) { - final StringComparison.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string); + public boolean validateValue(String string) { + StringComparison.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string); return !(value == null || value.match > 1); } - + @Override - public PlotBlock parseString(final String string) { - final StringComparison.ComparisonResult value = WorldUtil.IMP.getClosestBlock(string); + public PlotBlock parseString(String string) { + StringComparison.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 BLOCKLIST = new SettingValue("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.ComparisonResult value = WorldUtil.IMP.getClosestBlock(block); + StringComparison.ComparisonResult value = WorldUtil.IMP.getClosestBlock(block); if (value == null || value.match > 1) { return false; } @@ -158,20 +158,20 @@ public class Configuration { return false; } } - + @Override - public PlotBlock[] parseString(final String string) { - final String[] blocks = string.split(","); - final ArrayList 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 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.ComparisonResult result = WorldUtil.IMP.getClosestBlock(blocks[i]); + StringComparison.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]); } @@ -199,38 +199,39 @@ public class Configuration { return parsedvalues.toArray(new PlotBlock[parsedvalues.size()]); } }; - - 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]); } return result; } - + /** * Create your own SettingValue object to make the management of plotworld configuration easier */ public static abstract class SettingValue { + private final String type; - - public SettingValue(final String type) { + + public SettingValue(String type) { this.type = type; } - + public String getType() { return this.type; } - - public abstract T parseString(final String string); - - public abstract boolean validateValue(final String string); + + public abstract T parseString(String string); + + public abstract boolean validateValue(String string); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/database/Database.java b/Core/src/main/java/com/intellectualcrafters/plot/database/Database.java index c81648294..6b488e7d4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/database/Database.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/database/Database.java @@ -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
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
See {@link java.sql.Statement#executeUpdate(String)}
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; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java index 6c4894ca4..04ea0ae59 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java @@ -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() { @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() { @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 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 getPlotFlags(final Plot plot) { + public static HashMap getPlotFlags(Plot plot) { if (!plot.hasOwner()) { return null; } return getSettingFlags(plot.getArea(), plot.getSettings()); } - public static HashMap getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) { - final HashMap flags = new HashMap<>(); + public static HashMap getPlotFlags(PlotArea area, PlotSettings settings, boolean ignorePluginflags) { + HashMap flags = new HashMap<>(); if (area != null && !area.DEFAULT_FLAGS.isEmpty()) { flags.putAll(area.DEFAULT_FLAGS); } if (ignorePluginflags) { - for (final Map.Entry flag : settings.flags.entrySet()) { + for (Map.Entry flag : settings.flags.entrySet()) { if (isReserved(flag.getValue().getAbstractFlag().getKey())) { continue; } @@ -289,16 +290,16 @@ public class FlagManager { return flags; } - public static HashMap getSettingFlags(PlotArea area, final PlotSettings settings) { + public static HashMap 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 flags) { + public static void setPlotFlags(Plot origin, Set 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 flags) { + public static void setClusterFlags(PlotCluster cluster, Set 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 removeFlag(final Set flags, final String r) { - final HashSet newflags = new HashSet<>(); - for (final Flag flag : flags) { + public static Set removeFlag(Set flags, String r) { + HashSet 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 getFlags(final PlotPlayer player) { - final List returnFlags = new ArrayList<>(); - for (final AbstractFlag flag : flags) { + public static List getFlags(PlotPlayer player) { + List 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 parseFlags(final List flagstrings) { - final HashMap map = new HashMap<>(); - for (final String key : flagstrings) { - final String[] split; + public static HashMap parseFlags(List flagstrings) { + HashMap map = new HashMap<>(); + for (String key : flagstrings) { + String[] split; if (key.contains(";")) { split = key.split(";"); } else { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java index 18e8a5504..56b65d6a4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java @@ -1,56 +1,61 @@ 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 { + private final Class clazz; - + @SuppressWarnings("unchecked") public FlagValue() { this.clazz = (Class) getClass(); } - - public FlagValue(final Class clazz) { + + public FlagValue(Class 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 parse(final String t); - + + public abstract T getValue(Object 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 { + @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": @@ -69,202 +74,210 @@ public abstract class FlagValue { } } } - + @Override public String getDescription() { return "Flag value must be a boolean (true|false)"; } } - + public static class IntegerValue extends FlagValue { + @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; } } - + @Override public String getDescription() { return "Flag value must be a whole number"; } } - + public static class IntervalValue extends FlagValue { + @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 public String getDescription() { return "Value(s) must be numeric. /plot set flag [amount]"; } } - + public static class UnsignedIntegerValue extends FlagValue { + @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; } } - + @Override public String getDescription() { return "Flag value must be a positive whole number (includes 0)"; } } - + public static class DoubleValue extends FlagValue { + @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; } } - + @Override public String getDescription() { return "Flag value must be a number (negative decimals are allowed)"; } } - + public static class LongValue extends FlagValue { + @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; } } - + @Override public String getDescription() { return "Flag value must be a whole number (large numbers allowed)"; } } - + public static class UnsignedLongValue extends FlagValue { + @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; } } - + @Override public String getDescription() { return "Flag value must be a positive whole number (large numbers allowed)"; } } - + public static class UnsignedDoubleValue extends FlagValue { + @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; } } - + @Override public String getDescription() { return "Flag value must be a positive number (decimals allowed)"; } } - + public static class PlotBlockValue extends FlagValue { + @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,49 +288,44 @@ public abstract class FlagValue { } 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.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t); + } catch (Exception e) { + StringComparison.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t); if ((value == null) || (value.match > 1)) { return null; } return value.best; } } - + @Override public String getDescription() { return "Flag value must be a number (negative decimals are allowed)"; } } - - 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> implements ListValue { + @SuppressWarnings("unchecked") @Override - public String toString(final Object t) { + public String toString(Object t) { return StringMan.join((HashSet) t, ","); } - + @SuppressWarnings("unchecked") @Override - public HashSet getValue(final Object t) { + public HashSet getValue(Object t) { return (HashSet) t; } - + @Override - public HashSet parse(final String t) { - final HashSet list = new HashSet(); - for (final String item : t.split(",")) { + public HashSet parse(String t) { + HashSet list = new HashSet(); + 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 { } 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.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t); + StringComparison.ComparisonResult value = WorldUtil.IMP.getClosestBlock(t); if ((value == null) || (value.match > 1)) { continue; } @@ -341,172 +349,187 @@ public abstract class FlagValue { } return list; } - + @Override public String getDescription() { return "Flag value must be a block list"; } - + @Override - public void add(final Object t, final String value) { + public void add(Object t, String value) { try { ((HashSet) 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) t).remove(item); } - } catch (final Exception e) {} + } catch (Exception ignored) { + //ignored + } } } - + public static class IntegerListValue extends FlagValue> implements ListValue { + @SuppressWarnings("unchecked") @Override - public String toString(final Object t) { + public String toString(Object t) { return StringMan.join((List) t, ","); } - + @SuppressWarnings("unchecked") @Override - public List getValue(final Object t) { + public List getValue(Object t) { return (List) t; } - + @Override - public List parse(final String t) { - final String[] split = (t.split(",")); - final ArrayList numbers = new ArrayList(); - for (final String element : split) { + public List parse(String t) { + String[] split = t.split(","); + ArrayList numbers = new ArrayList(); + for (String element : split) { numbers.add(Integer.parseInt(element)); } return numbers; } - + @Override public String getDescription() { return "Flag value must be a integer list"; } - + @Override - public void add(final Object t, final String value) { + public void add(Object t, String value) { try { ((List) 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) t).remove(item); } - } catch (final Exception e) {} + } catch (Exception ignored) { + //ignored + } } } - + @SuppressWarnings("ALL") public static class StringListValue extends FlagValue> implements ListValue { - + @Override public String toString(final Object t) { return StringMan.join((List) t, ","); } - + @Override public List getValue(final Object t) { return (List) t; } - + @Override public List parse(final String t) { return Arrays.asList(t.split(",")); } - + @Override public String getDescription() { return "Flag value must be a string list"; } - + @Override public void add(final Object t, final String value) { try { ((List) t).addAll(parse(value)); - } catch (final Exception ignored) {} + } catch (final Exception ignored) { + } } - + @Override public void remove(final Object t, final String value) { try { for (final String item : parse(value)) { ((List) t).remove(item); } - } catch (final Exception e) {} + } catch (final Exception e) { + } } } - + public static class DoubleListValue extends FlagValue> implements ListValue { + @SuppressWarnings("unchecked") @Override - public String toString(final Object t) { + public String toString(Object t) { return StringMan.join((List) t, ","); } - + @SuppressWarnings("unchecked") @Override - public List getValue(final Object t) { + public List getValue(Object t) { return (List) t; } - + @Override - public List parse(final String t) { - final String[] split = (t.split(",")); - final ArrayList numbers = new ArrayList(); - for (final String element : split) { + public List parse(String t) { + String[] split = t.split(","); + ArrayList numbers = new ArrayList(); + for (String element : split) { numbers.add(Double.parseDouble(element)); } return numbers; } - + @Override public String getDescription() { return "Flag value must be a integer list"; } - + @Override - public void add(final Object t, final String value) { + public void add(Object t, String value) { try { ((List) 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) t).remove(item); } - } catch (final Exception e) {} + } catch (Exception e) { + } } } - + public static class StringValue extends FlagValue { + @Override - public String parse(final String s) { + public String parse(String s) { return s; } - + @Override public String getDescription() { return "Flag value must be alphanumeric. Some special characters are allowed."; } - + @Override - public String getValue(final Object t) { + public String getValue(Object t) { return t.toString(); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java index 5a085d84a..642bbf642 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java @@ -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> G_SCH; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java b/Core/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java index 94df25558..acecd07be 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java @@ -1,27 +1,29 @@ package com.intellectualcrafters.plot.object; public class BlockLoc { - public int x; - public int y; - public int z; - - public float yaw, pitch; - - public BlockLoc(final int x, final int y, final int z, final float yaw, final float pitch) { + + public final int x; + public final int y; + public final int z; + + 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; - + this.yaw = yaw; 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; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java b/Core/src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java deleted file mode 100644 index d148cf2be..000000000 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java +++ /dev/null @@ -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; - } -} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java b/Core/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java index a4fc14aba..97b1ad0d8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java @@ -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; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java b/Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java index cc882cdf2..91c519e13 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java @@ -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; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java index 3e6f26195..2186ce540 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java @@ -518,12 +518,11 @@ public class PlotAnalysis { bucket[i] = new ArrayList(); } 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; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java index da56ec573..88a1be682 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java @@ -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 */ diff --git a/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java index 866097be2..ed4ea3775 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java @@ -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>() { @Override public void run(List value) { @@ -53,32 +49,32 @@ public class InboxReport extends CommentInbox { }); return true; } - + @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; } DBFunc.setComment(plot, comment); return true; } - + @Override public String toString() { return "report"; } - + @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); return false; } - + @Override - public boolean clearInbox(final Plot plot) { + public boolean clearInbox(Plot plot) { if ((plot == null) || (plot.owner == null)) { return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java b/Core/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java index 81cb73723..a9e822608 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java @@ -33,7 +33,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class BO3Handler { - + /** * @see #saveBO3(PlotPlayer, Plot, RunnableVal) * @param plot @@ -60,7 +60,7 @@ public class BO3Handler { } return false; } - + /** * Save a plot as a BO3 file
* - Use null for the player object if no player is applicable @@ -88,7 +88,7 @@ public class BO3Handler { int cz = (bot.getZ() + top.getZ()) / 2; HashMap map = new HashMap<>(); - + HashSet regions = plot.getRegions(); ArrayList chunks = new ArrayList<>(); for (RegionWrapper region : regions) { @@ -148,7 +148,7 @@ public class BO3Handler { } } } - + if (!content) { MainUtil.sendMessage(plr, "No content found!"); return false; @@ -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; } } @@ -187,7 +188,7 @@ public class BO3Handler { for (Entry entry : map.entrySet()) { saveTask.run(entry.getValue()); } - + MainUtil.sendMessage(plr, "BO3 exporting was successful!"); return true; } @@ -211,8 +212,7 @@ public class BO3Handler { } } }); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); whenDone.run(); return; @@ -239,7 +239,7 @@ public class BO3Handler { String result = StringMan .replaceAll(line, "%owner%", MainUtil.getName(plot.owner), "%alias%", plot.toString(), "%blocks%", bo3.getBlocks(), "%branches%", bo3.getChildren(), - "%flags%", StringMan.join(FlagManager.getPlotFlags(plot).values(), ",")); + "%flags%", StringMan.join(FlagManager.getPlotFlags(plot).values(), ",")); if (!StringMan.isEqual(result, line)) { lines.set(i, result); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java b/Core/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java index 385e50e9a..5b359a473 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java @@ -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); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java index c7e2e66d6..69d14f57e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java @@ -17,8 +17,9 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class CommentManager { + public static HashMap inboxes = new HashMap<>(); - + public static void sendTitle(final PlotPlayer player, final Plot plot) { if (!Settings.COMMENT_NOTIFICATIONS) { return; @@ -29,7 +30,7 @@ public class CommentManager { TaskManager.runTaskLaterAsync(new Runnable() { @Override public void run() { - final Collection boxes = CommentManager.inboxes.values(); + Collection 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++; } @@ -57,19 +58,15 @@ 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); } - + public static void registerDefaultInboxes() { addInbox(new InboxReport()); addInbox(new InboxPublic()); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java b/Core/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java index c1e1d09d5..36290c2ad 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java @@ -5,32 +5,27 @@ 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; } return getBalance(player); } - + public abstract double getBalance(PlotPlayer player); - public abstract void withdrawMoney(final PlotPlayer player, final double amount); - - public abstract void depositMoney(final PlotPlayer player, final double amount); - - public abstract void depositMoney(final OfflinePlotPlayer player, final double amount); - - public void setPermission(final String player, final String perm, final boolean value) { - setPermission(null, player, perm, value); - } - - 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 abstract void withdrawMoney(PlotPlayer player, double amount); + + public abstract void depositMoney(PlotPlayer player, double amount); + + public abstract void depositMoney(OfflinePlotPlayer player, double amount); + + public abstract boolean hasPermission(String world, String player, String perm); + + public boolean hasPermission(String player, String perm) { return hasPermission(null, player, perm); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java index 9988818a7..095b2266a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java @@ -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; } @@ -110,26 +112,26 @@ public class ExpireManager { } }); } - + public boolean runTask(final RunnableVal2 expiredTask) { - if (running != 0) { + if (this.running != 0) { return false; } - running = 2; + this.running = 2; final Set 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 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 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()) { @@ -223,14 +226,14 @@ public class ExpireManager { PS.debug("$4 - Owner: Unowned"); } } - - 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,15 +250,15 @@ 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; } } 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; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java index ac29cce81..25f102a1c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java @@ -162,7 +162,7 @@ public class MainUtil { con.setDoOutput(true); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream output = con.getOutputStream(); - PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { + PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { String CRLF = "\r\n"; writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); @@ -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 diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java b/Core/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java index 1d05cd1ca..3b9b8f19d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java @@ -25,8 +25,7 @@ import java.util.Collection; import java.util.Collections; /** - * String comparison library - * + * String comparison library. */ public class StringComparison { @@ -40,37 +39,19 @@ public class StringComparison { * @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 objects) { + + public StringComparison(String input, Collection 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 { * * @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 { * * @return ArrayList */ - public static ArrayList wLetterPair(final String s) { - final ArrayList aPairs = new ArrayList<>(); - final String[] wo = s.split("\\s"); - for (final String aWo : wo) { - final String[] po = sLetterPair(aWo); + public static ArrayList wLetterPair(String s) { + ArrayList aPairs = new ArrayList<>(); + String[] wo = s.split("\\s"); + for (String aWo : wo) { + String[] po = sLetterPair(aWo); Collections.addAll(aPairs, po); } return aPairs; @@ -114,14 +95,32 @@ public class StringComparison { * * @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 { * @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; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java index 86e2b20c5..b07293636 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java @@ -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); diff --git a/Core/src/main/java/com/plotsquared/listener/HeightLimitExtent.java b/Core/src/main/java/com/plotsquared/listener/HeightLimitExtent.java deleted file mode 100644 index 03504cc52..000000000 --- a/Core/src/main/java/com/plotsquared/listener/HeightLimitExtent.java +++ /dev/null @@ -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); - } - -} diff --git a/Sponge/src/main/java/com/plotsquared/sponge/listener/MainListener.java b/Sponge/src/main/java/com/plotsquared/sponge/listener/MainListener.java index 7dc01806b..c1e13317e 100644 --- a/Sponge/src/main/java/com/plotsquared/sponge/listener/MainListener.java +++ b/Sponge/src/main/java/com/plotsquared/sponge/listener/MainListener.java @@ -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 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 components = new ArrayList<>(); + String[] split = (toSend + " ").split("%msg%"); + List 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. 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() { @@ -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) 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>() { @Override public boolean test(org.spongepowered.api.world.Location 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) 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) 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) 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) 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 from = event.getFromTransform().getLocation(); org.spongepowered.api.world.Location 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); diff --git a/Sponge/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java b/Sponge/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java index 3df47f836..0abd7d481 100644 --- a/Sponge/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java +++ b/Sponge/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java @@ -30,7 +30,7 @@ public class FastQueue extends SlowQueue { public final SendChunk chunkSender; public HashMap toUpdate = new HashMap<>(); - public FastQueue() throws NoSuchMethodException, RuntimeException { + public FastQueue() throws RuntimeException { TaskManager.runTaskRepeat(new Runnable() { @Override public void run() {