diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index d3bd24b9b..ff6bdf1ea 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -42,8 +42,8 @@ import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import com.plotsquared.bukkit.listeners.ChunkListener; import com.plotsquared.bukkit.listeners.ForceFieldListener; import com.plotsquared.bukkit.listeners.PlayerEvents; +import com.plotsquared.bukkit.listeners.PlayerEvents183; import com.plotsquared.bukkit.listeners.PlayerEvents_1_8; -import com.plotsquared.bukkit.listeners.PlayerEvents_1_8_3; import com.plotsquared.bukkit.listeners.PlotPlusListener; import com.plotsquared.bukkit.listeners.WorldEvents; import com.plotsquared.bukkit.listeners.worldedit.WEListener; @@ -87,6 +87,7 @@ import org.bukkit.generator.ChunkGenerator; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -104,14 +105,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { @Override public int[] getServerVersion() { - if (version == null) { + if (this.version == null) { try { - version = new int[3]; - final String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\."); - version[0] = Integer.parseInt(split[0]); - version[1] = Integer.parseInt(split[1]); + this.version = new int[3]; + String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\."); + this.version[0] = Integer.parseInt(split[0]); + this.version[1] = Integer.parseInt(split[1]); if (split.length == 3) { - version[2] = Integer.parseInt(split[2]); + this.version[2] = Integer.parseInt(split[2]); } } catch (NumberFormatException e) { e.printStackTrace(); @@ -120,7 +121,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { return new int[]{Integer.MAX_VALUE, 0, 0}; } } - return version; + return this.version; } @Override @@ -146,7 +147,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } Bukkit.getServer().getConsoleSender().sendMessage(message); return; - } catch (final Throwable e) {} + } catch (Throwable ignored) { + } } System.out.println(ConsoleColors.fromString(message)); } @@ -160,14 +162,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { @Override public int[] getPluginVersion() { - final String[] split = getDescription().getVersion().split("\\."); - return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]) }; + String[] split = getDescription().getVersion().split("\\."); + return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; } @Override public void registerCommands() { - final BukkitCommand bcmd = new BukkitCommand(); - final PluginCommand plotCommand = getCommand("plots"); + BukkitCommand bcmd = new BukkitCommand(); + PluginCommand plotCommand = getCommand("plots"); plotCommand.setExecutor(bcmd); plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot")); plotCommand.setTabCompleter(bcmd); @@ -204,15 +206,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { return; } List entities = world.getEntities(); - Iterator iter = entities.iterator(); - while (iter.hasNext()) { - Entity entity = iter.next(); + Iterator iterator = entities.iterator(); + while (iterator.hasNext()) { + Entity entity = iterator.next(); switch (entity.getType()) { case EGG: case ENDER_CRYSTAL: case COMPLEX_PART: case FISHING_HOOK: case ENDER_SIGNAL: + case LINGERING_POTION: + case AREA_EFFECT_CLOUD: case EXPERIENCE_ORB: case LEASH_HITCH: case FIREWORK: @@ -227,6 +231,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { case THROWN_EXP_BOTTLE: case SPLASH_POTION: case SNOWBALL: + case SHULKER_BULLET: + case SPECTRAL_ARROW: + case TIPPED_ARROW: case ENDER_PEARL: case ARROW: { // managed elsewhere | projectile @@ -248,11 +255,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (!Settings.KILL_ROAD_VEHICLES) { continue; } - com.intellectualcrafters.plot.object.Location loc = BukkitUtil.getLocation(entity.getLocation()); - Plot plot = loc.getPlot(); + com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation()); + Plot plot = location.getPlot(); if (plot == null) { - if (loc.isPlotArea()) { - iter.remove(); + if (location.isPlotArea()) { + iterator.remove(); entity.remove(); } continue; @@ -263,13 +270,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } Plot origin = (Plot) meta.get(0).value(); if (!plot.equals(origin.getBasePlot(false))) { - iter.remove(); + iterator.remove(); entity.remove(); } continue; } case SMALL_FIREBALL: case FIREBALL: + case DRAGON_FIREBALL: case DROPPED_ITEM: { // dropped item continue; @@ -311,22 +319,23 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { case WITHER: case WOLF: case ZOMBIE: + case SHULKER: default: { if (!Settings.KILL_ROAD_MOBS) { continue; } - final Location loc = entity.getLocation(); - if (BukkitUtil.getLocation(loc).isPlotRoad()) { - final Entity passenger = entity.getPassenger(); + Location location = entity.getLocation(); + if (BukkitUtil.getLocation(location).isPlotRoad()) { + Entity passenger = entity.getPassenger(); if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { - iter.remove(); + iterator.remove(); entity.remove(); } } } } } - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); } } @@ -336,8 +345,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } @Override - final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { - final HybridGen result = new HybridGen(); + final public ChunkGenerator getDefaultWorldGenerator(String world, String id) { + HybridGen result = new HybridGen(); if (!PS.get().setupPlotWorld(world, id, result)) { return null; } @@ -351,7 +360,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this); } if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) { - getServer().getPluginManager().registerEvents(new PlayerEvents_1_8_3(), this); + getServer().getPluginManager().registerEvents(new PlayerEvents183(), this); } } @@ -375,15 +384,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { public boolean initWorldEdit() { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { BukkitMain.worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); - final String version = BukkitMain.worldEdit.getDescription().getVersion(); - if (version != null && version.startsWith("5.")) { - log("&cThis version of WorldEdit does not support PlotSquared."); - log("&cPlease use WorldEdit 6+ for masking support"); - log("&c - http://builds.enginehub.org/job/worldedit"); - } else { - getServer().getPluginManager().registerEvents(new WEListener(), this); - return true; - } + getServer().getPluginManager().registerEvents(new WEListener(), this); + return true; } return false; } @@ -391,11 +393,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { @Override public EconHandler getEconomyHandler() { try { - final BukkitEconHandler econ = new BukkitEconHandler(); + BukkitEconHandler econ = new BukkitEconHandler(); if (econ.init()) { return econ; } - } catch (final Throwable ignored) { + } catch (Throwable ignored) { } return null; } @@ -405,15 +407,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { try { new SendChunk(); MainUtil.canSendChunk = true; - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); MainUtil.canSendChunk = false; } if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) { try { return new FastQueue_1_9(); - } - catch (Throwable e) { + } catch (Throwable e) { e.printStackTrace(); return new SlowQueue(); } @@ -464,13 +465,13 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } @Override - public GeneratorWrapper getGenerator(final String world, final String name) { + public GeneratorWrapper getGenerator(String world, String name) { if (name == null) { return null; } - final Plugin gen_plugin = Bukkit.getPluginManager().getPlugin(name); - if (gen_plugin != null && gen_plugin.isEnabled()) { - ChunkGenerator gen = gen_plugin.getDefaultWorldGenerator(world, ""); + Plugin genPlugin = Bukkit.getPluginManager().getPlugin(name); + if (genPlugin != null && genPlugin.isEnabled()) { + ChunkGenerator gen = genPlugin.getDefaultWorldGenerator(world, ""); if (gen instanceof GeneratorWrapper) { return (GeneratorWrapper) gen; } @@ -492,7 +493,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { @Override public UUIDHandlerImplementation initUUIDHandler() { - final boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6); + boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6); UUIDWrapper wrapper; if (Settings.OFFLINE_MODE) { if (Settings.UUID_LOWERCASE) { @@ -523,11 +524,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } } if (Settings.OFFLINE_MODE) { - log(C.PREFIX + " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of Bukkit"); + log(C.PREFIX + + " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " + + "Bukkit"); } else { log(C.PREFIX + " &6PlotSquared is using online UUIDs"); } - return Settings.USE_SQLUUIDHANDLER ? new SQLUUIDHandler(wrapper) : new FileUUIDHandler(wrapper); + if (Settings.USE_SQLUUIDHANDLER) { + return new SQLUUIDHandler(wrapper); + } else { + return new FileUUIDHandler(wrapper); + } } @Override @@ -541,7 +548,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } @Override - public void unregister(final PlotPlayer player) { + public void unregister(PlotPlayer player) { BukkitUtil.removePlayer(player.getName()); } @@ -577,41 +584,41 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } @Override - public void setGenerator(final String worldname) { - World world = BukkitUtil.getWorld(worldname); + public void setGenerator(String worldName) { + World world = BukkitUtil.getWorld(worldName); if (world == null) { // create world - final ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldname); + ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldName); String manager = worldConfig.getString("generator.plugin", "PlotSquared"); String generator = worldConfig.getString("generator.init", manager); - final int type = worldConfig.getInt("generator.type"); - final int terrain = worldConfig.getInt("generator.terrain"); - final SetupObject setup = new SetupObject(); + 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.step = new ConfigurationNode[0]; - setup.world = worldname; + setup.world = worldName; SetupUtils.manager.setupWorld(setup); } else { try { - if (!PS.get().hasPlotArea(worldname)) { - SetGenCB.setGenerator(BukkitUtil.getWorld(worldname)); + if (!PS.get().hasPlotArea(worldName)) { + SetGenCB.setGenerator(BukkitUtil.getWorld(worldName)); } - } catch (final Exception e) { + } catch (Exception e) { log("Failed to reload world: " + world); Bukkit.getServer().unloadWorld(world, false); } } - world = Bukkit.getWorld(worldname); - final ChunkGenerator gen = world.getGenerator(); + world = Bukkit.getWorld(worldName); + ChunkGenerator gen = world.getGenerator(); if (gen instanceof BukkitPlotGenerator) { - PS.get().loadWorld(worldname, (BukkitPlotGenerator) gen); + PS.get().loadWorld(worldName, (BukkitPlotGenerator) gen); } else if (gen != null) { - PS.get().loadWorld(worldname, new BukkitPlotGenerator(worldname, gen)); - } else if (PS.get().config.contains("worlds." + worldname)) { - PS.get().loadWorld(worldname, null); + PS.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen)); + } else if (PS.get().config.contains("worlds." + worldName)) { + PS.get().loadWorld(worldName, null); } } @@ -627,15 +634,15 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } @Override - public PlotPlayer wrapPlayer(final Object obj) { - if (obj instanceof Player) { - return BukkitUtil.getPlayer((Player) obj); - } else if (obj instanceof OfflinePlayer) { - return BukkitUtil.getPlayer((OfflinePlayer) obj); - } else if (obj instanceof String) { - return UUIDHandler.getPlayer((String) obj); - } else if (obj instanceof UUID) { - return UUIDHandler.getPlayer((UUID) obj); + public PlotPlayer wrapPlayer(Object player) { + if (player instanceof Player) { + return BukkitUtil.getPlayer((Player) player); + } else if (player instanceof OfflinePlayer) { + return BukkitUtil.getPlayer((OfflinePlayer) player); + } else if (player instanceof String) { + return UUIDHandler.getPlayer((String) player); + } else if (player instanceof UUID) { + return UUIDHandler.getPlayer((UUID) player); } return null; } 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 6f3deba1a..1a4176a6a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java @@ -1,11 +1,11 @@ package com.plotsquared.bukkit.chat; +import org.apache.commons.lang.Validate; + import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; -import org.apache.commons.lang.Validate; - /** * Represents a wrapper around an array class of an arbitrary reference type, * which properly implements "value" hash code and equality functions. @@ -17,57 +17,17 @@ import org.apache.commons.lang.Validate; * @see Arrays */ public final class ArrayWrapper { - + + private E[] _array; + /** * Creates an array wrapper with some elements. * @param elements The elements of the array. */ - public ArrayWrapper(final E... elements) { + public ArrayWrapper(E... elements) { setArray(elements); } - - private E[] _array; - - /** - * Retrieves a reference to the wrapped array instance. - * @return The array wrapped by this instance. - */ - public E[] getArray() { - return _array; - } - - /** - * Set this wrapper to wrap a new array instance. - * @param array The new wrapped array. - */ - public void setArray(final E[] array) { - Validate.notNull(array, "The array must not be null."); - _array = array; - } - - /** - * Determines if this object has a value equivalent to another object. - * @see Arrays#equals(Object[], Object[]) - */ - @SuppressWarnings("rawtypes") - @Override - public boolean equals(final Object other) { - if (!(other instanceof ArrayWrapper)) { - return false; - } - return Arrays.equals(_array, ((ArrayWrapper) other)._array); - } - - /** - * Gets the hash code represented by this objects value. - * @see Arrays#hashCode(Object[]) - * @return This object's hash code. - */ - @Override - public int hashCode() { - return Arrays.hashCode(_array); - } - + /** * Converts an iterable element collection to an array of elements. * The iteration order of the specified object will be used as the array element order. @@ -76,28 +36,66 @@ public final class ArrayWrapper { * @return An array of elements in the specified iterable. */ @SuppressWarnings("unchecked") - public static T[] toArray(final Iterable list, final Class c) { + public static T[] toArray(Iterable list, Class c) { int size = -1; if (list instanceof Collection) { - @SuppressWarnings("rawtypes") - final Collection coll = (Collection) list; + @SuppressWarnings("rawtypes") Collection coll = (Collection) list; size = coll.size(); } - + if (size < 0) { size = 0; // Ugly hack: Count it ourselves - for (@SuppressWarnings("unused") - final T element : list) { + for (@SuppressWarnings("unused") T element : list) { size++; } } - - final T[] result = (T[]) Array.newInstance(c, size); + + T[] result = (T[]) Array.newInstance(c, size); int i = 0; - for (final T element : list) { // Assumes iteration order is consistent + for (T element : list) { // Assumes iteration order is consistent result[i++] = element; // Assign array element at index THEN increment counter } return result; } + + /** + * Retrieves a reference to the wrapped array instance. + * @return The array wrapped by this instance. + */ + public E[] getArray() { + return this._array; + } + + /** + * Set this wrapper to wrap a new array instance. + * @param array The new wrapped array. + */ + public void setArray(E[] array) { + Validate.notNull(array, "The array must not be null."); + this._array = array; + } + + /** + * Determines if this object has a value equivalent to another object. + * @see Arrays#equals(Object[], Object[]) + */ + @SuppressWarnings("rawtypes") + @Override + public boolean equals(Object other) { + if (!(other instanceof ArrayWrapper)) { + return false; + } + return Arrays.equals(this._array, ((ArrayWrapper) other)._array); + } + + /** + * Gets the hash code represented by this objects value. + * @see Arrays#hashCode(Object[]) + * @return This object's hash code. + */ + @Override + public int hashCode() { + 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 cda63a8d7..d31ffb194 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java @@ -37,8 +37,10 @@ import java.util.Map; import java.util.logging.Level; /** - * Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features provided by the vanilla Minecraft JSON message formatter. - * This class allows plugins to emulate the functionality of the vanilla Minecraft tellraw command. + * Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features + * 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, @@ -53,48 +55,49 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< // The ChatSerializer's instance of Gson private static Object nmsChatSerializerGsonInstance; private static Method fromJsonMethod; - + static { ConfigurationSerialization.registerClass(FancyMessage.class); } - + private List messageParts; private String jsonString; private boolean dirty; - + /** * Creates a JSON message with text. * @param firstPartText The existing text in the message. */ - public FancyMessage(final String firstPartText) { + public FancyMessage(String firstPartText) { this(rawText(firstPartText)); } - - public FancyMessage(final TextualComponent firstPartText) { - messageParts = new ArrayList<>(); - messageParts.add(new MessagePart(firstPartText)); - jsonString = null; - dirty = false; + + public FancyMessage(TextualComponent firstPartText) { + this.messageParts = new ArrayList<>(); + this.messageParts.add(new MessagePart(firstPartText)); + this.jsonString = null; + this.dirty = false; if (nmsPacketPlayOutChatConstructor == null) { try { - nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); + nmsPacketPlayOutChatConstructor = + Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); nmsPacketPlayOutChatConstructor.setAccessible(true); - } catch (final NoSuchMethodException e) { + } catch (NoSuchMethodException e) { Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e); - } catch (final SecurityException e) { + } catch (SecurityException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e); } } } - + /** * Creates a JSON message without text. */ public FancyMessage() { this((TextualComponent) null); } - + /** * Deserialize a JSON-represented message from a mapping of key-value pairs. * This is called by the Bukkit serialization API. @@ -102,8 +105,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @param serialized The key-value mapping which represents a fancy message. */ @SuppressWarnings("unchecked") - public static FancyMessage deserialize(final Map serialized) { - final FancyMessage msg = new FancyMessage(); + public static FancyMessage deserialize(Map serialized) { + FancyMessage msg = new FancyMessage(); msg.messageParts = (List) serialized.get("messageParts"); msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null; msg.dirty = !serialized.containsKey("JSON"); @@ -116,26 +119,26 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @param json The JSON string which represents a fancy message. * @return A {@code FancyMessage} representing the parametrized JSON message. */ - public static FancyMessage deserialize(final String json) { - final JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); - final JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component - final FancyMessage returnVal = new FancyMessage(); + public static FancyMessage deserialize(String json) { + JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); + JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component + FancyMessage returnVal = new FancyMessage(); returnVal.messageParts.clear(); - for (final JsonElement mPrt : extra) { - final MessagePart component = new MessagePart(); - final JsonObject messagePart = mPrt.getAsJsonObject(); - for (final Map.Entry entry : messagePart.entrySet()) { + for (JsonElement mPrt : extra) { + MessagePart component = new MessagePart(); + JsonObject messagePart = mPrt.getAsJsonObject(); + for (Map.Entry entry : messagePart.entrySet()) { // Deserialize text if (TextualComponent.isTextKey(entry.getKey())) { // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields - final Map serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance + Map serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance serializedMapForm.put("key", entry.getKey()); if (entry.getValue().isJsonPrimitive()) { // Assume string serializedMapForm.put("value", entry.getValue().getAsString()); } else { // Composite object, but we assume each element is a string - for (final Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) { + for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) { serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString()); } } @@ -147,11 +150,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } else if (entry.getKey().equals("color")) { component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); } else if (entry.getKey().equals("clickEvent")) { - final JsonObject object = entry.getValue().getAsJsonObject(); + JsonObject object = entry.getValue().getAsJsonObject(); component.clickActionName = object.get("action").getAsString(); component.clickActionData = object.get("value").getAsString(); } else if (entry.getKey().equals("hoverEvent")) { - final JsonObject object = entry.getValue().getAsJsonObject(); + JsonObject object = entry.getValue().getAsJsonObject(); component.hoverActionName = object.get("action").getAsString(); if (object.get("value").isJsonPrimitive()) { // Assume string @@ -166,7 +169,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } else if (entry.getKey().equals("insertion")) { component.insertionData = entry.getValue().getAsString(); } else if (entry.getKey().equals("with")) { - for (final JsonElement object : entry.getValue().getAsJsonArray()) { + for (JsonElement object : entry.getValue().getAsJsonArray()) { if (object.isJsonPrimitive()) { component.translationReplacements.add(new JsonString(object.getAsString())); } else { @@ -184,10 +187,10 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< @Override public FancyMessage clone() throws CloneNotSupportedException { - final FancyMessage instance = (FancyMessage) super.clone(); - instance.messageParts = new ArrayList<>(messageParts.size()); - for (int i = 0; i < messageParts.size(); i++) { - instance.messageParts.add(i, messageParts.get(i).clone()); + FancyMessage instance = (FancyMessage) super.clone(); + instance.messageParts = new ArrayList<>(this.messageParts.size()); + for (int i = 0; i < this.messageParts.size(); i++) { + instance.messageParts.add(i, this.messageParts.get(i).clone()); } instance.dirty = false; instance.jsonString = null; @@ -199,141 +202,149 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @param text The new text of the current editing component. * @return This builder instance. */ - public FancyMessage text(final String text) { - final MessagePart latest = latest(); + public FancyMessage text(String text) { + MessagePart latest = latest(); latest.text = rawText(text); - dirty = true; + this.dirty = true; return this; } - + /** * Sets the text of the current editing component to a value. * @param text The new text of the current editing component. * @return This builder instance. */ - public FancyMessage text(final TextualComponent text) { - final MessagePart latest = latest(); + public FancyMessage text(TextualComponent text) { + MessagePart latest = latest(); latest.text = text; - dirty = true; + this.dirty = true; return this; } - + /** * Sets the color of the current editing component to a value. * @param color The new color of the current editing component. * @return This builder instance. * @exception IllegalArgumentException If the specified {@code ChatColor} enumeration value is not a color (but a format value). */ - public FancyMessage color(final ChatColor color) { + public FancyMessage color(ChatColor color) { latest().color = color; - dirty = true; + this.dirty = true; return this; } - + /** * Sets the stylization of the current editing component. * @param styles The array of styles to apply to the editing component. * @return This builder instance. * @exception IllegalArgumentException If any of the enumeration values in the array do not represent formatters. */ - public FancyMessage style(final ChatColor... styles) { - for (final ChatColor style : styles) { + public FancyMessage style(ChatColor... styles) { + for (ChatColor style : styles) { if (!style.isFormat()) { throw new IllegalArgumentException(style.name() + " is not a style"); } } latest().styles.addAll(Arrays.asList(styles)); - dirty = true; + this.dirty = true; return this; } - + /** - * Set the behavior of the current editing component to instruct the client to open a file on the client side filesystem when the currently edited part of the {@code FancyMessage} is clicked. + * Set the behavior of the current editing component to instruct the client to open a file on the client side filesystem when the currently + * edited part of the {@code FancyMessage} is clicked. * @param path The path of the file on the client filesystem. * @return This builder instance. */ - public FancyMessage file(final String path) { + public FancyMessage file(String path) { onClick("open_file", path); return this; } - + /** - * Set the behavior of the current editing component to instruct the client to open a webpage in the client's web browser when the currently edited part of the {@code FancyMessage} is clicked. + * Set the behavior of the current editing component to instruct the client to open a webpage in the client's web browser when the currently + * edited part of the {@code FancyMessage} is clicked. * @param url The URL of the page to open when the link is clicked. * @return This builder instance. */ - public FancyMessage link(final String url) { + public FancyMessage link(String url) { onClick("open_url", url); return this; } - + /** - * Set the behavior of the current editing component to instruct the client to replace the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is clicked. - * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key. + * Set the behavior of the current editing component to instruct the client to replace the chat input box content with the specified string + * when the currently edited part of the {@code FancyMessage} is clicked. + * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, + * usually with the enter key. * @param command The text to display in the chat bar of the client. * @return This builder instance. */ - public FancyMessage suggest(final String command) { + public FancyMessage suggest(String command) { onClick("suggest_command", command); return this; } - + /** - * Set the behavior of the current editing component to instruct the client to append the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is SHIFT-CLICKED. - * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key. + * Set the behavior of the current editing component to instruct the client to append the chat input box content with the specified string when + * the currently edited part of the {@code FancyMessage} is SHIFT-CLICKED. + * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, + * usually with the enter key. * @param command The text to append to the chat bar of the client. * @return This builder instance. */ - public FancyMessage insert(final String command) { + public FancyMessage insert(String command) { latest().insertionData = command; - dirty = true; + this.dirty = true; return this; } - + /** - * Set the behavior of the current editing component to instruct the client to send the specified string to the server as a chat message when the currently edited part of the {@code FancyMessage} is clicked. + * Set the behavior of the current editing component to instruct the client to send the specified string to the server as a chat message when + * the currently edited part of the {@code FancyMessage} is clicked. * The client will immediately send the command to the server to be executed when the editing component is clicked. * @param command The text to display in the chat bar of the client. * @return This builder instance. */ - public FancyMessage command(final String command) { + public FancyMessage command(String command) { onClick("run_command", command); return this; } - + /** * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param name The name of the achievement to display, excluding the "achievement." prefix. * @return This builder instance. */ - public FancyMessage achievementTooltip(final String name) { + public FancyMessage achievementTooltip(String name) { onHover("show_achievement", new JsonString("achievement." + name)); return this; } - + /** * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param which The achievement to display. * @return This builder instance. */ - public FancyMessage achievementTooltip(final Achievement which) { + public FancyMessage achievementTooltip(Achievement which) { try { - final Object achievement = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which); + Object achievement = + Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which); return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement)); - } catch (final IllegalAccessException e) { + } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; - } catch (final IllegalArgumentException e) { + } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; - } catch (final InvocationTargetException e) { + } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } - + /** * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

@@ -341,36 +352,38 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied. */ - public FancyMessage statisticTooltip(final Statistic which) { - final Type type = which.getType(); + public FancyMessage statisticTooltip(Statistic which) { + Type type = which.getType(); if (type != Type.UNTYPED) { throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!"); } try { - final Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which); + Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which); return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); - } catch (final IllegalAccessException e) { + } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; - } catch (final IllegalArgumentException e) { + } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; - } catch (final InvocationTargetException e) { + } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } - + /** - * Set the behavior of the current editing component to display information about a statistic parameter with a material when the client hovers over the text. + * Set the behavior of the current editing component to display information about a statistic parameter with a material when the client hovers + * over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param which The statistic to display. * @param item The sole material parameter to the statistic. * @return This builder instance. - * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not required. + * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not + * required. */ - public FancyMessage statisticTooltip(final Statistic which, final Material item) { - final Type type = which.getType(); + public FancyMessage statisticTooltip(Statistic which, Material item) { + Type type = which.getType(); if (type == Type.UNTYPED) { throw new IllegalArgumentException("That statistic needs no additional parameter!"); } @@ -378,30 +391,33 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); } try { - final Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item); + Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class) + .invoke(null, which, item); return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); - } catch (final IllegalAccessException e) { + } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; - } catch (final IllegalArgumentException e) { + } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; - } catch (final InvocationTargetException e) { + } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } - + /** - * Set the behavior of the current editing component to display information about a statistic parameter with an entity type when the client hovers over the text. + * Set the behavior of the current editing component to display information about a statistic parameter with an entity type when the client + * hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param which The statistic to display. * @param entity The sole entity type parameter to the statistic. * @return This builder instance. - * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not required. + * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not + * required. */ - public FancyMessage statisticTooltip(final Statistic which, final EntityType entity) { - final Type type = which.getType(); + public FancyMessage statisticTooltip(Statistic which, EntityType entity) { + Type type = which.getType(); if (type == Type.UNTYPED) { throw new IllegalArgumentException("That statistic needs no additional parameter!"); } @@ -409,66 +425,69 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); } try { - final Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity); + Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class) + .invoke(null, which, entity); return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); - } catch (final IllegalAccessException e) { + } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; - } catch (final IllegalArgumentException e) { + } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; - } catch (final InvocationTargetException e) { + } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } - + /** * Set the behavior of the current editing component to display information about an item when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param itemJSON A string representing the JSON-serialized NBT data tag of an {@link ItemStack}. * @return This builder instance. */ - public FancyMessage itemTooltip(final String itemJSON) { + public FancyMessage itemTooltip(String itemJSON) { onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter return this; } - + /** * Set the behavior of the current editing component to display information about an item when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param itemStack The stack for which to display information. * @return This builder instance. */ - public FancyMessage itemTooltip(final ItemStack itemStack) { + public FancyMessage itemTooltip(ItemStack itemStack) { try { - final Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack); + Object nmsItem = + Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack); return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")) - .invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString()); - } catch (final Exception e) { + .invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString()); + } catch (Exception e) { e.printStackTrace(); return this; } } - + /** * Set the behavior of the current editing component to display raw text when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param text The text, which supports newlines, which will be displayed to the client upon hovering. * @return This builder instance. */ - public FancyMessage tooltip(final String text) { + public FancyMessage tooltip(String text) { onHover("show_text", new JsonString(text)); return this; } - + /** * Set the behavior of the current editing component to display raw text when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created. + * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in + * which the lines of the tooltip are created. * @return This builder instance. */ - public FancyMessage tooltip(final Iterable lines) { + public FancyMessage tooltip(Iterable lines) { tooltip(ArrayWrapper.toArray(lines, String.class)); return this; } @@ -497,8 +516,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @param lines The lines of text which will be displayed to the client upon hovering. * @return This builder instance. */ - public FancyMessage tooltip(final String... lines) { - final StringBuilder builder = new StringBuilder(); + public FancyMessage tooltip(String... lines) { + StringBuilder builder = new StringBuilder(); for (int i = 0; i < lines.length; i++) { builder.append(lines[i]); if (i != lines.length - 1) { @@ -508,15 +527,15 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< tooltip(builder.toString()); return this; } - + /** * Set the behavior of the current editing component to display formatted text when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param text The formatted text which will be displayed to the client upon hovering. * @return This builder instance. */ - public FancyMessage formattedTooltip(final FancyMessage text) { - for (final MessagePart component : text.messageParts) { + public FancyMessage formattedTooltip(FancyMessage text) { + for (MessagePart component : text.messageParts) { if (component.clickActionData != null && component.clickActionName != null) { throw new IllegalArgumentException("The tooltip text cannot have click data."); } else if (component.hoverActionData != null && component.hoverActionName != null) { @@ -526,25 +545,25 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< onHover("show_text", text); return this; } - + /** * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

* @param lines The lines of formatted text which will be displayed to the client upon hovering. * @return This builder instance. */ - public FancyMessage formattedTooltip(final FancyMessage... lines) { + public FancyMessage formattedTooltip(FancyMessage... lines) { if (lines.length < 1) { onHover(null, null); // Clear tooltip return this; } - final FancyMessage result = new FancyMessage(); + FancyMessage result = new FancyMessage(); result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object for (int i = 0; i < lines.length; i++) { try { - for (final MessagePart component : lines[i]) { + for (MessagePart component : lines[i]) { if (component.clickActionData != null && component.clickActionName != null) { throw new IllegalArgumentException("The tooltip text cannot have click data."); } else if (component.hoverActionData != null && component.hoverActionName != null) { @@ -557,176 +576,185 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< if (i != lines.length - 1) { result.messageParts.add(new MessagePart(rawText("\n"))); } - } catch (final CloneNotSupportedException e) { + } catch (CloneNotSupportedException e) { Bukkit.getLogger().log(Level.WARNING, "Failed to clone object", e); return this; } } return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended } - + /** * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created. + * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in + * which the lines of the tooltip are created. * @return This builder instance. */ - public FancyMessage formattedTooltip(final Iterable lines) { + public FancyMessage formattedTooltip(Iterable lines) { return formattedTooltip(ArrayWrapper.toArray(lines, FancyMessage.class)); } - + /** - * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the + * message. * @param replacements The replacements, in order, that will be used in the language-specific message. * @return This builder instance. */ - public FancyMessage translationReplacements(final String... replacements) { - for (final String str : replacements) { + public FancyMessage translationReplacements(String... replacements) { + for (String str : replacements) { latest().translationReplacements.add(new JsonString(str)); } - dirty = true; + this.dirty = true; return this; } - + /** - * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the + * message. * @param replacements The replacements, in order, that will be used in the language-specific message. * @return This builder instance. */ - public FancyMessage translationReplacements(final FancyMessage... replacements) { + public FancyMessage translationReplacements(FancyMessage... replacements) { Collections.addAll(latest().translationReplacements, replacements); - dirty = true; + this.dirty = true; return this; } - + /** - * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the + * message. * @param replacements The replacements, in order, that will be used in the language-specific message. * @return This builder instance. */ - public FancyMessage translationReplacements(final Iterable replacements) { + public FancyMessage translationReplacements(Iterable replacements) { return translationReplacements(ArrayWrapper.toArray(replacements, FancyMessage.class)); } - + /** * Terminate construction of the current editing component, and begin construction of a new message component. - * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method. + * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this + * method. * @param text The text which will populate the new message component. * @return This builder instance. */ - public FancyMessage then(final String text) { + public FancyMessage then(String text) { return then(rawText(text)); } - + /** * Terminate construction of the current editing component, and begin construction of a new message component. - * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method. + * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this + * method. * @param text The text which will populate the new message component. * @return This builder instance. */ - public FancyMessage then(final TextualComponent text) { + public FancyMessage then(TextualComponent text) { if (!latest().hasText()) { throw new IllegalStateException("previous message part has no text"); } - messageParts.add(new MessagePart(text)); - dirty = true; + this.messageParts.add(new MessagePart(text)); + this.dirty = true; return this; } - + /** * Terminate construction of the current editing component, and begin construction of a new message component. - * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method. + * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this + * method. * @return This builder instance. */ public FancyMessage then() { if (!latest().hasText()) { throw new IllegalStateException("previous message part has no text"); } - messageParts.add(new MessagePart()); - dirty = true; + this.messageParts.add(new MessagePart()); + this.dirty = true; return this; } @Override - public void writeJson(final JsonWriter writer) throws IOException { - if (messageParts.size() == 1) { + public void writeJson(JsonWriter writer) throws IOException { + if (this.messageParts.size() == 1) { latest().writeJson(writer); } else { writer.beginObject().name("text").value("").name("extra").beginArray(); - for (final MessagePart part : this) { + for (MessagePart part : this) { part.writeJson(writer); } writer.endArray().endObject(); } } - + /** * Serialize this fancy message, converting it into syntactically-valid JSON using a {@link JsonWriter}. * This JSON should be compatible with vanilla formatter commands such as {@code /tellraw}. * @return The JSON string representing this object. */ public String toJSONString() { - if (!dirty && jsonString != null) { - return jsonString; + if (!this.dirty && this.jsonString != null) { + return this.jsonString; } - final StringWriter string = new StringWriter(); - final JsonWriter json = new JsonWriter(string); + StringWriter string = new StringWriter(); + JsonWriter json = new JsonWriter(string); try { writeJson(json); json.close(); - } catch (final IOException e) { + } catch (IOException e) { throw new RuntimeException("invalid message"); } - jsonString = string.toString(); - dirty = false; - return jsonString; + this.jsonString = string.toString(); + this.dirty = false; + return this.jsonString; } - + /** * Sends this message to a player. The player will receive the fully-fledged formatted display of this message. * @param player The player who will receive the message. */ - public void send(final Player player) { + public void send(Player player) { send(player, toJSONString()); } - - private void send(final CommandSender sender, final String jsonString) { + + private void send(CommandSender sender, String jsonString) { if (!(sender instanceof Player)) { sender.sendMessage(toOldMessageFormat()); return; } - final Player player = (Player) sender; + Player player = (Player) sender; try { - final Object handle = Reflection.getHandle(player); - final Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle); - Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString)); - } catch (final IllegalArgumentException e) { + Object handle = Reflection.getHandle(player); + Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle); + Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")) + .invoke(connection, createChatPacket(jsonString)); + } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); - } catch (final IllegalAccessException e) { + } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); - } catch (final InstantiationException e) { + } catch (InstantiationException e) { Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e); - } catch (final InvocationTargetException e) { + } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); - } catch (final NoSuchMethodException e) { + } catch (NoSuchMethodException e) { Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e); - } catch (final ClassNotFoundException e) { + } catch (ClassNotFoundException e) { Bukkit.getLogger().log(Level.WARNING, "Could not find class.", e); } } - - private Object createChatPacket(final String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, - ClassNotFoundException { + + private Object createChatPacket(String json) + throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, + ClassNotFoundException { if (nmsChatSerializerGsonInstance == null) { // Find the field and its value, completely bypassing obfuscation Class chatSerializerClazz; - final String version = Reflection.getVersion(); - final double majorVersion = Double.parseDouble(version.replace('_', '.').substring(1, 4)); - final int lesserVersion = Integer.parseInt(version.substring(6, 7)); + String version = Reflection.getVersion(); + double majorVersion = Double.parseDouble(version.replace('_', '.').substring(1, 4)); + int lesserVersion = Integer.parseInt(version.substring(6, 7)); if (majorVersion < 1.8 || majorVersion == 1.8 && lesserVersion == 1) { chatSerializerClazz = Reflection.getNMSClass("ChatSerializer"); @@ -738,8 +766,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new ClassNotFoundException("Can't find the ChatSerializer class"); } - for (final Field declaredField : chatSerializerClazz.getDeclaredFields()) { - if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().getName().endsWith("Gson")) { + for (Field declaredField : chatSerializerClazz.getDeclaredFields()) { + if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType() + .getName().endsWith("Gson")) { // We've found our field declaredField.setAccessible(true); nmsChatSerializerGsonInstance = declaredField.get(null); @@ -754,11 +783,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< than to reflectively call it Of course, the implementation may change, but fuzzy matches might break with signature changes */ - final Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent")); + Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent")); return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent); } - + /** * Sends this message to a command sender. * If the sender is a player, they will receive the fully-fledged formatted display of this message. @@ -766,22 +795,22 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @param sender The command sender who will receive the message. * @see #toOldMessageFormat() */ - public void send(final CommandSender sender) { + public void send(CommandSender sender) { send(sender, toJSONString()); } - + /** * Sends this message to multiple command senders. * @param senders The command senders who will receive the message. * @see #send(CommandSender) */ - public void send(final Iterable senders) { - final String string = toJSONString(); - for (final CommandSender sender : senders) { + public void send(Iterable senders) { + String string = toJSONString(); + for (CommandSender sender : senders) { send(sender, string); } } - + /** * Convert this message to a human-readable string with limited formatting. * This method is used to send this message to clients without JSON formatting support. @@ -799,49 +828,49 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return A human-readable string representing limited formatting in addition to the core text of this message. */ public String toOldMessageFormat() { - final StringBuilder result = new StringBuilder(); - for (final MessagePart part : this) { + StringBuilder result = new StringBuilder(); + for (MessagePart part : this) { result.append(part.color == null ? "" : part.color); - for (final ChatColor formatSpecifier : part.styles) { + for (ChatColor formatSpecifier : part.styles) { result.append(formatSpecifier); } result.append(part.text); } return result.toString(); } - + private MessagePart latest() { - return messageParts.get(messageParts.size() - 1); + return this.messageParts.get(this.messageParts.size() - 1); } - - private void onClick(final String name, final String data) { - final MessagePart latest = latest(); + + private void onClick(String name, String data) { + MessagePart latest = latest(); latest.clickActionName = name; latest.clickActionData = data; - dirty = true; + this.dirty = true; } - - private void onHover(final String name, final JsonRepresentedObject data) { - final MessagePart latest = latest(); + + private void onHover(String name, JsonRepresentedObject data) { + MessagePart latest = latest(); latest.hoverActionName = name; latest.hoverActionData = data; - dirty = true; + this.dirty = true; } - + // Doc copied from interface @Override public Map serialize() { - final HashMap map = new HashMap<>(); - map.put("messageParts", messageParts); + HashMap map = new HashMap<>(); + map.put("messageParts", this.messageParts); // map.put("JSON", toJSONString()); return map; } - + /** - * Internally called method. Not for API consumption. + * Internally called method. Not for API consumption. */ @Override public Iterator iterator() { - return messageParts.iterator(); + return this.messageParts.iterator(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java index 1344fb18e..0b3d7a98c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java @@ -1,19 +1,19 @@ package com.plotsquared.bukkit.chat; -import java.io.IOException; - import com.google.gson.stream.JsonWriter; +import java.io.IOException; + /** * Represents an object that can be serialized to a JSON writer instance. */ interface JsonRepresentedObject { - + /** * Writes the JSON representation of this object to the specified writer. * @param writer The JSON writer which will receive the object. * @throws IOException If an error occurs writing to the stream. */ - void writeJson(final JsonWriter writer) throws IOException; - + void writeJson(JsonWriter writer) throws IOException; + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java index e6b9138f4..6fe69b265 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java @@ -1,47 +1,47 @@ package com.plotsquared.bukkit.chat; +import com.google.gson.stream.JsonWriter; +import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; + import java.io.IOException; import java.util.HashMap; import java.util.Map; -import com.google.gson.stream.JsonWriter; -import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; - /** * Represents a JSON string value. * Writes by this object will not write name values nor begin/end objects in the JSON stream. * All writes merely write the represented string value. */ final class JsonString implements JsonRepresentedObject, ConfigurationSerializable { - + private final String _value; - - public JsonString(final CharSequence value) { - _value = value == null ? null : value.toString(); + + public JsonString(CharSequence value) { + this._value = value == null ? null : value.toString(); } - - @Override - public void writeJson(final JsonWriter writer) throws IOException { - writer.value(getValue()); - } - - public String getValue() { - return _value; - } - - @Override - public Map serialize() { - final HashMap theSingleValue = new HashMap(); - theSingleValue.put("stringValue", _value); - return theSingleValue; - } - - public static JsonString deserialize(final Map map) { + + public static JsonString deserialize(Map map) { return new JsonString(map.get("stringValue").toString()); } - + + @Override + public void writeJson(JsonWriter writer) throws IOException { + writer.value(getValue()); + } + + public String getValue() { + return this._value; + } + + @Override + public Map serialize() { + HashMap theSingleValue = new HashMap<>(); + theSingleValue.put("stringValue", this._value); + return theSingleValue; + } + @Override public String toString() { - return _value; + return this._value; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java index ccbe2e433..6c5d17e16 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java @@ -22,8 +22,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa static final BiMap stylesToNames; static { - final ImmutableBiMap.Builder builder = ImmutableBiMap.builder(); - for (final ChatColor style : ChatColor.values()) { + ImmutableBiMap.Builder builder = ImmutableBiMap.builder(); + for (ChatColor style : ChatColor.values()) { if (!style.isFormat()) { continue; } @@ -57,18 +57,18 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa TextualComponent text = null; String insertionData = null; ArrayList translationReplacements = new ArrayList<>(); - - MessagePart(final TextualComponent text) { + + MessagePart(TextualComponent text) { this.text = text; } - + MessagePart() { - text = null; + this.text = null; } @SuppressWarnings("unchecked") - public static MessagePart deserialize(final Map serialized) { - final MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); + public static MessagePart deserialize(Map serialized) { + MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); part.styles = (ArrayList) serialized.get("styles"); part.color = ChatColor.getByChar(serialized.get("color").toString()); part.hoverActionName = (String) serialized.get("hoverActionName"); @@ -81,70 +81,71 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa } boolean hasText() { - return text != null; + return this.text != null; } - + @Override @SuppressWarnings("unchecked") public MessagePart clone() throws CloneNotSupportedException { - final MessagePart obj = (MessagePart) super.clone(); - obj.styles = (ArrayList) styles.clone(); - if (hoverActionData instanceof JsonString) { - obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); - } else if (hoverActionData instanceof FancyMessage) { - obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); + MessagePart obj = (MessagePart) super.clone(); + obj.styles = (ArrayList) this.styles.clone(); + if (this.hoverActionData instanceof JsonString) { + obj.hoverActionData = new JsonString(((JsonString) this.hoverActionData).getValue()); + } else if (this.hoverActionData instanceof FancyMessage) { + obj.hoverActionData = ((FancyMessage) this.hoverActionData).clone(); } - obj.translationReplacements = (ArrayList) translationReplacements.clone(); + obj.translationReplacements = (ArrayList) this.translationReplacements.clone(); return obj; } - + @Override - public void writeJson(final JsonWriter json) { + public void writeJson(JsonWriter json) { try { json.beginObject(); - text.writeJson(json); - json.name("color").value(color.name().toLowerCase()); - for (final ChatColor style : styles) { + this.text.writeJson(json); + json.name("color").value(this.color.name().toLowerCase()); + for (ChatColor style : this.styles) { json.name(stylesToNames.get(style)).value(true); } - if ((clickActionName != null) && (clickActionData != null)) { - json.name("clickEvent").beginObject().name("action").value(clickActionName).name("value").value(clickActionData).endObject(); + if ((this.clickActionName != null) && (this.clickActionData != null)) { + json.name("clickEvent").beginObject().name("action").value(this.clickActionName).name("value").value(this.clickActionData) + .endObject(); } - if ((hoverActionName != null) && (hoverActionData != null)) { - json.name("hoverEvent").beginObject().name("action").value(hoverActionName).name("value"); - hoverActionData.writeJson(json); + if ((this.hoverActionName != null) && (this.hoverActionData != null)) { + json.name("hoverEvent").beginObject().name("action").value(this.hoverActionName).name("value"); + this.hoverActionData.writeJson(json); json.endObject(); } - if (insertionData != null) { - json.name("insertion").value(insertionData); + if (this.insertionData != null) { + json.name("insertion").value(this.insertionData); } - if ((!translationReplacements.isEmpty()) && (text != null) && TextualComponent.isTranslatableText(text)) { + if (!this.translationReplacements.isEmpty() && (this.text != null) && TextualComponent.isTranslatableText(this.text)) { json.name("with").beginArray(); - for (final JsonRepresentedObject obj : translationReplacements) { + for (JsonRepresentedObject obj : this.translationReplacements) { obj.writeJson(json); } json.endArray(); } json.endObject(); - } catch (final IOException e) { + } catch (IOException e) { Bukkit.getLogger().log(Level.WARNING, "A problem occurred during writing of JSON string", e); } } - + @Override public Map serialize() { - final HashMap map = new HashMap<>(); - map.put("text", text); - map.put("styles", styles); - map.put("color", color.getChar()); - map.put("hoverActionName", hoverActionName); - map.put("hoverActionData", hoverActionData); - map.put("clickActionName", clickActionName); - map.put("clickActionData", clickActionData); - map.put("insertion", insertionData); - map.put("translationReplacements", translationReplacements); + HashMap map = new HashMap<>(); + map.put("text", this.text); + map.put("styles", this.styles); + map.put("color", this.color.getChar()); + map.put("hoverActionName", this.hoverActionName); + map.put("hoverActionData", this.hoverActionData); + map.put("clickActionName", this.clickActionName); + map.put("clickActionData", this.clickActionData); + map.put("insertion", this.insertionData); + map.put("translationReplacements", this.translationReplacements); return map; } - + } 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 8e4a2ece9..a78f0d3fb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java @@ -33,7 +33,7 @@ public final class Reflection { private Reflection() { } - + /** * Gets the version string from the package name of the CraftBukkit server implementation. * This is needed to bypass the JAR package name changing on each update. @@ -42,19 +42,20 @@ public final class Reflection { public synchronized static String getVersion() { return PS.get().IMP.getNMSPackage(); } - + /** * Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package. - * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously). + * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this + * method simultaneously). * @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(final String className) { + public synchronized static Class getNMSClass(String className) { if (_loadedNMSClasses.containsKey(className)) { return _loadedNMSClasses.get(className); } - final String fullName = "net.minecraft.server." + getVersion() + "." + className; + String fullName = "net.minecraft.server." + getVersion() + "." + className; Class clazz; try { clazz = Class.forName(fullName); @@ -66,7 +67,7 @@ public final class Reflection { _loadedNMSClasses.put(className, clazz); return clazz; } - + /** * Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package. * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this @@ -75,12 +76,12 @@ 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(final String className) { + public synchronized static Class getOBCClass(String className) { if (_loadedOBCClasses.containsKey(className)) { return _loadedOBCClasses.get(className); } - final String fullName = "org.bukkit.craftbukkit." + getVersion() + "." + className; + String fullName = "org.bukkit.craftbukkit." + getVersion() + "." + className; Class clazz; try { clazz = Class.forName(fullName); @@ -92,7 +93,7 @@ public final class Reflection { _loadedOBCClasses.put(className, clazz); return clazz; } - + /** * Attempts to get the NMS handle of a CraftBukkit object. *

@@ -102,7 +103,7 @@ public final class Reflection { * @param obj The object for which to retrieve an NMS handle. * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}. */ - public synchronized static Object getHandle(final Object obj) { + public synchronized static Object getHandle(Object obj) { try { return getMethod(obj.getClass(), "getHandle").invoke(obj); } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { @@ -110,7 +111,7 @@ public final class Reflection { return null; } } - + /** * Retrieves a {@link Field} instance declared by the specified class with the specified name. * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field @@ -129,7 +130,7 @@ public final class Reflection { * @return A field object with the specified name declared by the specified class. * @see Class#getDeclaredField(String) */ - public synchronized static Field getField(final Class clazz, final String name) { + public synchronized static Field getField(Class clazz, String name) { Map loaded; if (!_loadedFields.containsKey(clazz)) { loaded = new HashMap<>(); @@ -142,7 +143,7 @@ public final class Reflection { return loaded.get(name); } try { - final Field field = clazz.getDeclaredField(name); + Field field = clazz.getDeclaredField(name); field.setAccessible(true); loaded.put(name, field); return field; @@ -154,7 +155,7 @@ public final class Reflection { return null; } } - + /** * Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types. * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field @@ -164,7 +165,8 @@ public final class Reflection { * no method will be reflectively looked up twice. *

*

- * If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned. + * If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code + * true} before it is returned. * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance. *

*

@@ -175,23 +177,23 @@ public final class Reflection { * @param args The formal argument types of the method. * @return A method object with the specified name declared by the specified class. */ - public synchronized static Method getMethod(final Class clazz, final String name, final Class... args) { + public synchronized static Method getMethod(Class clazz, String name, Class... args) { if (!_loadedMethods.containsKey(clazz)) { _loadedMethods.put(clazz, new HashMap>, Method>>()); } - - final Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); + + Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); if (!loadedMethodNames.containsKey(name)) { loadedMethodNames.put(name, new HashMap>, Method>()); } - - final Map>, Method> loadedSignatures = loadedMethodNames.get(name); - final ArrayWrapper> wrappedArg = new ArrayWrapper<>(args); + + Map>, Method> loadedSignatures = loadedMethodNames.get(name); + ArrayWrapper> wrappedArg = new ArrayWrapper<>(args); if (loadedSignatures.containsKey(wrappedArg)) { return loadedSignatures.get(wrappedArg); } - - for (final Method m : clazz.getMethods()) { + + for (Method m : clazz.getMethods()) { if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) { m.setAccessible(true); loadedSignatures.put(wrappedArg, m); @@ -201,5 +203,5 @@ public final class Reflection { loadedSignatures.put(wrappedArg, null); return null; } - + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java index 41491ff87..ad90d4b7b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java @@ -23,6 +23,107 @@ public abstract class TextualComponent implements Cloneable { ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class); } + static TextualComponent deserialize(Map map) { + if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) { + // Arbitrary text component + return ArbitraryTextTypeComponent.deserialize(map); + } else if ((map.size() >= 2) && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) { + // Complex JSON object + return ComplexTextTypeComponent.deserialize(map); + } + + return null; + } + + static boolean isTextKey(String key) { + return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); + } + + static boolean isTranslatableText(TextualComponent component) { + return (component instanceof ComplexTextTypeComponent) && component.getKey().equals("translate"); + } + + /** + * Create a textual component representing a string literal. + * This is the default type of textual component when a single string literal is given to a method. + * @param textValue The text which will be represented. + * @return The text component representing the specified literal text. + */ + public static TextualComponent rawText(String textValue) { + return new ArbitraryTextTypeComponent("text", textValue); + } + + /** + * Create a textual component representing a localized string. + * The client will see this text component as their localized version of the specified string key, which can be overridden by a + * resource pack. + *

+ * If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to + * the client. + *

+ * @param translateKey The string key which maps to localized text. + * @return The text component representing the specified localized text. + */ + public static TextualComponent localizedText(String translateKey) { + return new ArbitraryTextTypeComponent("translate", translateKey); + } + + private static void throwUnsupportedSnapshot() { + throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); + } + + /** + * Create a textual component representing a scoreboard value. + * The client will see their own score for the specified objective as the text represented by this component. + *

+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. + *

+ * @param scoreboardObjective The name of the objective for which to display the score. + * @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during + * JSON serialization. + */ + public static TextualComponent objectiveScore(String scoreboardObjective) { + return objectiveScore("*", scoreboardObjective); + } + + /** + * Create a textual component representing a scoreboard value. + * The client will see the score of the specified player for the specified objective as the text represented by this component. + *

+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. + *

+ * @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing + * player's score will be displayed. + * Standard minecraft selectors (@a, @p, etc) are not supported. + * @param scoreboardObjective The name of the objective for which to display the score. + * @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during + * JSON serialization. + */ + public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) { + throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE + // OVERLOADS documentation accordingly + + return new ComplexTextTypeComponent("score", + ImmutableMap.builder().put("name", playerName).put("objective", scoreboardObjective).build()); + } + + /** + * Create a textual component representing a player name, retrievable by using a standard minecraft selector. + * The client will see the players or entities captured by the specified selector as the text represented by this component. + *

+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. + *

+ * @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in + * the place of this text component. + * @return The text component representing the name of the entities captured by the selector. + */ + public static TextualComponent selector(String selector) { + throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE + // OVERLOADS documentation accordingly + + return new ArbitraryTextTypeComponent("selector", selector); + } + @Override public String toString() { return getReadableString(); @@ -51,27 +152,7 @@ public abstract class TextualComponent implements Cloneable { * @param writer The object to which to write the JSON data. * @throws IOException If an error occurs while writing to the stream. */ - public abstract void writeJson(final JsonWriter writer) throws IOException; - - static TextualComponent deserialize(final Map map) { - if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) { - // Arbitrary text component - return ArbitraryTextTypeComponent.deserialize(map); - } else if ((map.size() >= 2) && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) { - // Complex JSON object - return ComplexTextTypeComponent.deserialize(map); - } - - return null; - } - - static boolean isTextKey(final String key) { - return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); - } - - static boolean isTranslatableText(final TextualComponent component) { - return (component instanceof ComplexTextTypeComponent) && component.getKey().equals("translate"); - } + public abstract void writeJson(JsonWriter writer) throws IOException; /** * Internal class used to represent all types of text components. @@ -79,33 +160,37 @@ public abstract class TextualComponent implements Cloneable { */ private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable { - public ArbitraryTextTypeComponent(final String key, final String value) { + private String _key; + private String _value; + + public ArbitraryTextTypeComponent(String key, String value) { setKey(key); setValue(value); } - @Override - public String getKey() { - return _key; + public static ArbitraryTextTypeComponent deserialize(Map map) { + return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString()); } - public void setKey(final String key) { + @Override + public String getKey() { + return this._key; + } + + public void setKey(String key) { Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified."); - _key = key; + this._key = key; } public String getValue() { - return _value; + return this._value; } - public void setValue(final String value) { + public void setValue(String value) { Preconditions.checkArgument(value != null, "The value must be specified."); - _value = value; + this._value = value; } - private String _key; - private String _value; - @Override public TextualComponent clone() throws CloneNotSupportedException { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone @@ -113,7 +198,7 @@ public abstract class TextualComponent implements Cloneable { } @Override - public void writeJson(final JsonWriter writer) throws IOException { + public void writeJson(JsonWriter writer) throws IOException { writer.name(getKey()).value(getValue()); } @@ -128,10 +213,6 @@ public abstract class TextualComponent implements Cloneable { }; } - public static ArbitraryTextTypeComponent deserialize(final Map map) { - return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString()); - } - @Override public String getReadableString() { return getValue(); @@ -144,33 +225,46 @@ public abstract class TextualComponent implements Cloneable { */ private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable { - public ComplexTextTypeComponent(final String key, final Map values) { + private String _key; + private Map _value; + + public ComplexTextTypeComponent(String key, Map values) { setKey(key); setValue(values); } - @Override - public String getKey() { - return _key; + public static ComplexTextTypeComponent deserialize(Map map) { + String key = null; + Map value = new HashMap(); + for (Map.Entry valEntry : map.entrySet()) { + if (valEntry.getKey().equals("key")) { + key = (String) valEntry.getValue(); + } else if (valEntry.getKey().startsWith("value.")) { + value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); + } + } + return new ComplexTextTypeComponent(key, value); } - public void setKey(final String key) { + @Override + public String getKey() { + return this._key; + } + + public void setKey(String key) { Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified."); - _key = key; + this._key = key; } public Map getValue() { - return _value; + return this._value; } - public void setValue(final Map value) { + public void setValue(Map value) { Preconditions.checkArgument(value != null, "The value must be specified."); - _value = value; + this._value = value; } - private String _key; - private Map _value; - @Override public TextualComponent clone() throws CloneNotSupportedException { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone @@ -178,10 +272,10 @@ public abstract class TextualComponent implements Cloneable { } @Override - public void writeJson(final JsonWriter writer) throws IOException { + public void writeJson(JsonWriter writer) throws IOException { writer.name(getKey()); writer.beginObject(); - for (final Map.Entry jsonPair : _value.entrySet()) { + for (Map.Entry jsonPair : this._value.entrySet()) { writer.name(jsonPair.getKey()).value(jsonPair.getValue()); } writer.endObject(); @@ -193,101 +287,16 @@ public abstract class TextualComponent implements Cloneable { return new java.util.HashMap() { { put("key", getKey()); - for (final Map.Entry valEntry : getValue().entrySet()) { + for (Map.Entry valEntry : getValue().entrySet()) { put("value." + valEntry.getKey(), valEntry.getValue()); } } }; } - public static ComplexTextTypeComponent deserialize(final Map map) { - String key = null; - final Map value = new HashMap(); - for (final Map.Entry valEntry : map.entrySet()) { - if (valEntry.getKey().equals("key")) { - key = (String) valEntry.getValue(); - } else if (valEntry.getKey().startsWith("value.")) { - value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); - } - } - return new ComplexTextTypeComponent(key, value); - } - @Override public String getReadableString() { return getKey(); } } - - /** - * Create a textual component representing a string literal. - * This is the default type of textual component when a single string literal is given to a method. - * @param textValue The text which will be represented. - * @return The text component representing the specified literal text. - */ - public static TextualComponent rawText(final String textValue) { - return new ArbitraryTextTypeComponent("text", textValue); - } - - /** - * Create a textual component representing a localized string. - * The client will see this text component as their localized version of the specified string key, which can be overridden by a resource pack. - *

- * If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client. - *

- * @param translateKey The string key which maps to localized text. - * @return The text component representing the specified localized text. - */ - public static TextualComponent localizedText(final String translateKey) { - return new ArbitraryTextTypeComponent("translate", translateKey); - } - - private static void throwUnsupportedSnapshot() { - throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); - } - - /** - * Create a textual component representing a scoreboard value. - * The client will see their own score for the specified objective as the text represented by this component. - *

- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. - *

- * @param scoreboardObjective The name of the objective for which to display the score. - * @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization. - */ - public static TextualComponent objectiveScore(final String scoreboardObjective) { - return objectiveScore("*", scoreboardObjective); - } - - /** - * Create a textual component representing a scoreboard value. - * The client will see the score of the specified player for the specified objective as the text represented by this component. - *

- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. - *

- * @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing player's score will be displayed. - * Standard minecraft selectors (@a, @p, etc) are not supported. - * @param scoreboardObjective The name of the objective for which to display the score. - * @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization. - */ - public static TextualComponent objectiveScore(final String playerName, final String scoreboardObjective) { - throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly - - return new ComplexTextTypeComponent("score", ImmutableMap. builder().put("name", playerName).put("objective", scoreboardObjective).build()); - } - - /** - * Create a textual component representing a player name, retrievable by using a standard minecraft selector. - * The client will see the players or entities captured by the specified selector as the text represented by this component. - *

- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. - *

- * @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component. - * @return The text component representing the name of the entities captured by the selector. - */ - public static TextualComponent selector(final String selector) { - throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly - - return new ArbitraryTextTypeComponent("selector", selector); - } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java index 33c335a4d..446a60aab 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java @@ -42,6 +42,7 @@ import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.io.FilenameFilter; import java.io.IOException; @@ -55,20 +56,20 @@ import java.util.Map.Entry; import java.util.UUID; @CommandDeclaration( -command = "uuidconvert", -permission = "plots.admin", -description = "Debug UUID conversion", -usage = "/plot uuidconvert ", -requiredType = RequiredType.CONSOLE, -category = CommandCategory.DEBUG) + command = "uuidconvert", + permission = "plots.admin", + description = "Debug UUID conversion", + usage = "/plot uuidconvert ", + requiredType = RequiredType.CONSOLE, + category = CommandCategory.DEBUG) public class DebugUUID extends SubCommand { public DebugUUID() { - requiredArguments = new Argument[] { Argument.String }; + this.requiredArguments = new Argument[]{Argument.String}; } @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { + public boolean onCommand(final PlotPlayer player, String[] args) { final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper(); final UUIDWrapper newWrapper; @@ -84,7 +85,7 @@ public class DebugUUID extends SubCommand { break; default: try { - final Class clazz = Class.forName(args[0]); + Class clazz = Class.forName(args[0]); newWrapper = (UUIDWrapper) clazz.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert "); @@ -121,38 +122,39 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Collecting playerdata"); - final HashSet worlds = new HashSet<>(); + HashSet worlds = new HashSet<>(); worlds.add(WorldUtil.IMP.getMainWorld()); worlds.add("world"); - final HashSet uuids = new HashSet<>(); - final HashSet names = new HashSet<>(); - for (final String worldname : worlds) { - final File playerdataFolder = new File(worldname + File.separator + "playerdata"); + HashSet uuids = new HashSet<>(); + HashSet names = new HashSet<>(); + for (String worldname : worlds) { + File playerdataFolder = new File(worldname + File.separator + "playerdata"); String[] dat = playerdataFolder.list(new FilenameFilter() { @Override - public boolean accept(final File f, final String s) { - return s.endsWith(".dat"); - } - }); - if (dat != null) - for (final String current : dat) { - final String s = current.replaceAll(".dat$", ""); - try { - final UUID uuid = UUID.fromString(s); - uuids.add(uuid); - } catch (final Exception e) { - MainUtil.sendMessage(player, C.PREFIX + "Invalid playerdata: " + current); - } - } - final File playersFolder = new File(worldname + File.separator + "players"); - dat = playersFolder.list(new FilenameFilter() { - @Override - public boolean accept(final File f, final String s) { + public boolean accept(File f, String s) { return s.endsWith(".dat"); } }); if (dat != null) { - for (final String current : dat) { + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); + try { + UUID uuid = UUID.fromString(s); + uuids.add(uuid); + } catch (Exception e) { + MainUtil.sendMessage(player, C.PREFIX + "Invalid playerdata: " + current); + } + } + } + File playersFolder = new File(worldname + File.separator + "players"); + dat = playersFolder.list(new FilenameFilter() { + @Override + public boolean accept(File f, String s) { + return s.endsWith(".dat"); + } + }); + if (dat != null) { + for (String current : dat) { names.add(current.replaceAll(".dat$", "")); } } @@ -160,22 +162,22 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Populating map"); UUID uuid2; - final UUIDWrapper wrapper = new DefaultUUIDWrapper(); + UUIDWrapper wrapper = new DefaultUUIDWrapper(); for (UUID uuid : uuids) { try { - final OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid); + OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid); uuid = currentUUIDWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op); if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) { uCMap.put(uuid, uuid2); uCReverse.put(uuid2, uuid); } - } catch (final Throwable e) { + } catch (Throwable e) { MainUtil.sendMessage(player, C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } - for (final String name : names) { - final UUID uuid = currentUUIDWrapper.getUUID(name); + for (String name : names) { + UUID uuid = currentUUIDWrapper.getUUID(name); uuid2 = newWrapper.getUUID(name); if (!uuid.equals(uuid2)) { uCMap.put(uuid, uuid2); @@ -184,11 +186,11 @@ public class DebugUUID extends SubCommand { } if (uCMap.isEmpty()) { MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate"); - for (final OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) { + for (OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) { if (op.getLastPlayed() != 0) { // String name = op.getName(); // StringWrapper wrap = new StringWrapper(name); - final UUID uuid = currentUUIDWrapper.getUUID(op); + UUID uuid = currentUUIDWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op); if (!uuid.equals(uuid2)) { uCMap.put(uuid, uuid2); @@ -208,8 +210,8 @@ public class DebugUUID extends SubCommand { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - for (final Entry entry : uCMap.entrySet()) { - final String name = UUIDHandler.getName(entry.getKey()); + for (Entry entry : uCMap.entrySet()) { + String name = UUIDHandler.getName(entry.getKey()); if (name != null) { UUIDHandler.add(new StringWrapper(name), entry.getValue()); } @@ -217,10 +219,10 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); - final File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); + File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); if (file.exists()) { try { - final List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); for (String line : lines) { try { line = line.trim(); @@ -228,24 +230,24 @@ public class DebugUUID extends SubCommand { continue; } line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - final String[] split = line.split("\\|"); - final String name = split[0]; + String[] split = line.split("\\|"); + String name = split[0]; if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) { continue; } - final UUID old = currentUUIDWrapper.getUUID(name); + UUID old = currentUUIDWrapper.getUUID(name); if (old == null) { continue; } - final UUID now = newWrapper.getUUID(name); + UUID now = newWrapper.getUUID(name); UUIDHandler.add(new StringWrapper(name), now); uCMap.put(old, now); uCReverse.put(now, old); - } catch (final Exception e2) { + } catch (Exception e2) { e2.printStackTrace(); } } - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -255,8 +257,8 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Updating plot objects"); - for (final Plot plot : PS.get().getPlots()) { - final UUID value = uCMap.get(plot.owner); + for (Plot plot : PS.get().getPlots()) { + UUID value = uCMap.get(plot.owner); if (value != null) { plot.owner = value; } @@ -267,7 +269,7 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Deleting database"); final AbstractDB database = DBFunc.dbManager; - final boolean result = database.deleteTables(); + boolean result = database.deleteTables(); MainUtil.sendMessage(player, "&7 - Creating tables"); @@ -275,8 +277,8 @@ public class DebugUUID extends SubCommand { database.createTables(); if (!result) { MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); - for (final Plot plot : PS.get().getPlots()) { - final UUID value = uCReverse.get(plot.owner); + for (Plot plot : PS.get().getPlots()) { + UUID value = uCReverse.get(plot.owner); if (value != null) { plot.owner = value; } @@ -289,7 +291,7 @@ public class DebugUUID extends SubCommand { }); return; } - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); return; } @@ -312,7 +314,7 @@ public class DebugUUID extends SubCommand { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final ArrayList plots = new ArrayList<>(PS.get().getPlots()); + ArrayList plots = new ArrayList<>(PS.get().getPlots()); database.createPlotsAndData(plots, new Runnable() { @Override public void run() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java index 8e8a559c2..e92d32fb0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java @@ -14,60 +14,61 @@ import java.util.Collections; import java.util.HashMap; public abstract class APlotMeConnector { - public abstract Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder); - - public abstract HashMap> getPlotMePlots(final Connection connection) throws SQLException; - - public abstract boolean accepts(final String version); - - public String getWorld(final String world) { - for (final World newworld : Bukkit.getWorlds()) { - if (newworld.getName().equalsIgnoreCase(world)) { - return newworld.getName(); + + public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder); + + public abstract HashMap> getPlotMePlots(Connection connection) throws SQLException; + + public abstract boolean accepts(String version); + + public String getWorld(String world) { + for (World newWorld : Bukkit.getWorlds()) { + if (newWorld.getName().equalsIgnoreCase(world)) { + return newWorld.getName(); } } return world; } - - public boolean isValidConnection(final Connection connection) { + + public boolean isValidConnection(Connection connection) { return connection != null; } - - public void copyConfig(final FileConfiguration plotConfig, final String world, final String actualWorldName) { - final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); // - PS.get().config.set("worlds." + actualWorldName + ".road.width", pathwidth); - final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); // - PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotsize); - final String wallblock = plotConfig.getString("worlds." + world + ".WallBlockId"); // - PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallblock); - final String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); // + + public void copyConfig(FileConfiguration plotConfig, String world, String actualWorldName) { + int pathWidth = plotConfig.getInt("worlds." + world + ".PathWidth"); // + PS.get().config.set("worlds." + actualWorldName + ".road.width", pathWidth); + int plotSize = plotConfig.getInt("worlds." + world + ".PlotSize"); // + PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotSize); + String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); // + PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallBlock); + String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); // PS.get().config.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor)); - final String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); // + String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); // PS.get().config.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling)); - final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId"); + String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId"); PS.get().config.set("worlds." + actualWorldName + ".road.block", road); - Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); // + int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); // PS.get().config.set("worlds." + actualWorldName + ".road.height", height); } - - public Location getPlotTopLocAbs(final int path, final int plot, final PlotId plotid) { - final int px = plotid.x; - final int pz = plotid.y; - final int x = (px * (path + plot)) - (int) Math.floor(path / 2) - 1; - final int z = (pz * (path + plot)) - (int) Math.floor(path / 2) - 1; + + public Location getPlotTopLocAbs(int path, int plot, PlotId plotid) { + int px = plotid.x; + int pz = plotid.y; + int x = (px * (path + plot)) - (int) Math.floor(path / 2) - 1; + int z = (pz * (path + plot)) - (int) Math.floor(path / 2) - 1; return new Location(null, x, 256, z); } - - public Location getPlotBottomLocAbs(final int path, final int plot, final PlotId plotid) { - final int px = plotid.x; - final int pz = plotid.y; - final int x = (px * (path + plot)) - plot - (int) Math.floor(path / 2) - 1; - final int z = (pz * (path + plot)) - plot - (int) Math.floor(path / 2) - 1; + + public Location getPlotBottomLocAbs(int path, int plot, PlotId plotid) { + int px = plotid.x; + int pz = plotid.y; + int x = (px * (path + plot)) - plot - (int) Math.floor(path / 2) - 1; + int z = (pz * (path + plot)) - plot - (int) Math.floor(path / 2) - 1; return new Location(null, x, 1, z); } - - public void setMerged(final HashMap> merges, final String world, final PlotId id, final int direction) { - final HashMap plots = merges.get(world); + + public void setMerged(HashMap> merges, String world, PlotId id, int direction) { + HashMap plots = merges.get(world); PlotId id2 = new PlotId(id.x, id.y); boolean[] merge1; if (plots.containsKey(id)) { 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 65a7d2cb2..414384309 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 @@ -25,70 +25,71 @@ import java.util.Map.Entry; import java.util.UUID; public class ClassicPlotMeConnector extends APlotMeConnector { - + private String plugin; private String prefix; - + @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(); - prefix = plotConfig.getString("mySQLprefix", plugin.toLowerCase()); + this.prefix = plotConfig.getString("mySQLprefix", 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); // return new MySQL(plotsquared, hostname, port, database, username, password) } else { return new SQLite(dataFolder + File.separator + "plots.db").openConnection(); } } catch (SQLException | ClassNotFoundException ignored) { + //ignored } return null; } - + @Override - public HashMap> getPlotMePlots(final Connection connection) throws SQLException { - final HashMap plotWidth = new HashMap<>(); - final HashMap roadWidth = new HashMap<>(); - final HashMap> plots = new HashMap<>(); - final HashMap> merges = new HashMap<>(); - PreparedStatement stmt = connection.prepareStatement("SELECT * FROM `" + prefix + "Plots`"); - ResultSet r = stmt.executeQuery(); + public HashMap> getPlotMePlots(Connection connection) throws SQLException { + HashMap plotWidth = new HashMap<>(); + HashMap roadWidth = new HashMap<>(); + HashMap> plots = new HashMap<>(); + HashMap> merges = new HashMap<>(); + PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`"); + ResultSet resultSet = statement.executeQuery(); String column = null; - final boolean checkUUID = DBFunc.hasColumn(r, "ownerid"); - final boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId"); + boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerid"); + boolean checkUUID2 = DBFunc.hasColumn(resultSet, "ownerId"); if (checkUUID) { column = "ownerid"; } else if (checkUUID2) { column = "ownerId"; } - final boolean merge = !"plotme".equalsIgnoreCase(plugin) && Settings.CONVERT_PLOTME; + boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.CONVERT_PLOTME; int missing = 0; - while (r.next()) { - final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ")); - final String name = r.getString("owner"); - final String world = LikePlotMeConverter.getWorld(r.getString("world")); + while (resultSet.next()) { + PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ")); + String name = resultSet.getString("owner"); + String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); if (!plots.containsKey(world)) { plots.put(world, new HashMap()); if (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); } @@ -109,14 +110,14 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } else { if (checkUUID || checkUUID2) { try { - final byte[] bytes = r.getBytes(column); + byte[] bytes = resultSet.getBytes(column); if (bytes != null) { try { - final ByteBuffer bb = ByteBuffer.wrap(bytes); - final long high = bb.getLong(); - final long low = bb.getLong(); + ByteBuffer bb = ByteBuffer.wrap(bytes); + long high = bb.getLong(); + long low = bb.getLong(); owner = new UUID(high, low); - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); owner = UUID.nameUUIDFromBytes(bytes); } @@ -138,55 +139,56 @@ public class ClassicPlotMeConnector 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.get(world).put(id, plot); } if (missing > 0) { PS.log("&cSome names could not be identified:"); PS.log("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database"); PS.log("&7 - Names you have never seen before could be from people mistyping commands"); - PS.log("&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will remain unknown until the player connects)"); + PS.log("&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will " + + "remain unknown until the player connects)"); } - - for (final Entry> entry : merges.entrySet()) { - final String world = entry.getKey(); - for (final Entry entry2 : entry.getValue().entrySet()) { - final HashMap newplots = plots.get(world); - final Plot plot = newplots.get(entry2.getKey()); + + for (Entry> entry : merges.entrySet()) { + String world = entry.getKey(); + for (Entry entry2 : entry.getValue().entrySet()) { + HashMap newplots = plots.get(world); + Plot plot = newplots.get(entry2.getKey()); if (plot != null) { plot.setMerged(entry2.getValue()); } } } - - r.close(); - stmt.close(); + + resultSet.close(); + statement.close(); try { - PS.log(" - " + prefix + "Denied"); - stmt = connection.prepareStatement("SELECT * FROM `" + prefix + "Denied`"); - r = stmt.executeQuery(); + PS.log(" - " + this.prefix + "Denied"); + statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Denied`"); + resultSet = statement.executeQuery(); - while (r.next()) { - final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ")); - final String name = r.getString("player"); - final String world = LikePlotMeConverter.getWorld(r.getString("world")); + while (resultSet.next()) { + PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ")); + String name = resultSet.getString("player"); + String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); UUID denied = UUIDHandler.getUUID(name, null); if (denied == null) { if ("*".equals(name)) { denied = DBFunc.everyone; } else { - if (DBFunc.hasColumn(r, "playerid")) { + if (DBFunc.hasColumn(resultSet, "playerid")) { try { - final byte[] bytes = r.getBytes("playerid"); + byte[] bytes = resultSet.getBytes("playerid"); if (bytes != null) { try { - final ByteBuffer bb = ByteBuffer.wrap(bytes); - final long high = bb.getLong(); - final long low = bb.getLong(); + ByteBuffer bb = ByteBuffer.wrap(bytes); + long high = bb.getLong(); + long low = bb.getLong(); denied = new UUID(high, low); - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); denied = UUID.nameUUIDFromBytes(bytes); } @@ -207,36 +209,34 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } } - stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Allowed`"); - r = stmt.executeQuery(); + statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "Allowed`"); + resultSet = statement.executeQuery(); - while (r.next()) { - final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ")); - final String name = r.getString("player"); - final String world = LikePlotMeConverter.getWorld(r.getString("world")); + while (resultSet.next()) { + PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ")); + String name = resultSet.getString("player"); + String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); UUID helper = UUIDHandler.getUUID(name, null); if (helper == null) { if ("*".equals(name)) { helper = DBFunc.everyone; - } else { - if (DBFunc.hasColumn(r, "playerid")) { - try { - final byte[] bytes = r.getBytes("playerid"); - if (bytes != null) { - try { - final ByteBuffer bb = ByteBuffer.wrap(bytes); - final long high = bb.getLong(); - final long low = bb.getLong(); - helper = new UUID(high, low); - } catch (final Exception e) { - e.printStackTrace(); - helper = UUID.nameUUIDFromBytes(bytes); - } - UUIDHandler.add(new StringWrapper(name), helper); + } 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(); + helper = new UUID(high, low); + } catch (Exception e) { + e.printStackTrace(); + helper = UUID.nameUUIDFromBytes(bytes); } - } catch (SQLException e) { - e.printStackTrace(); + UUIDHandler.add(new StringWrapper(name), helper); } + } catch (SQLException e) { + e.printStackTrace(); } } if (helper == null) { @@ -249,16 +249,17 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } } - r.close(); - stmt.close(); + resultSet.close(); + statement.close(); - } catch (SQLException e) { + } catch (SQLException ignored) { + //ignored } return plots; } - + @Override - public boolean accepts(final String version) { + public boolean accepts(String version) { return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java index c8cf638c9..053ddb6c7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java @@ -20,13 +20,12 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.PlotCluster; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.PlotCluster; - /** * Called when a flag is removed from a plot * @@ -34,56 +33,57 @@ import com.intellectualcrafters.plot.object.PlotCluster; */ public class ClusterFlagRemoveEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final PlotCluster cluster; private final Flag flag; private boolean cancelled; - + /** * PlotFlagRemoveEvent: Called when a flag is removed from a plot * * @param flag Flag that was removed * @param cluster PlotCluster from which the flag was removed */ - public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) { + public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) { this.cluster = cluster; this.flag = flag; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the cluster involved * * @return PlotCluster */ public PlotCluster getCluster() { - return cluster; + return this.cluster; } - + /** * Get the flag involved * * @return Flag */ public Flag getFlag() { - return flag; + return this.flag; } - + @Override public HandlerList getHandlers() { return handlers; } - + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public void setCancelled(final boolean b) { - cancelled = b; + public void setCancelled(boolean b) { + this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java index bb083009e..0e3d5be28 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java @@ -20,65 +20,67 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import com.intellectualcrafters.plot.object.Plot; +/** + -/** */ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Plot plot; private final boolean auto; private boolean cancelled; - + /** * PlayerClaimPlotEvent: Called when a plot is claimed * * @param player Player that claimed the plot * @param plot Plot that was claimed */ - public PlayerClaimPlotEvent(final Player player, final Plot plot, final boolean auto) { + public PlayerClaimPlotEvent(Player player, Plot plot, boolean auto) { super(player); this.plot = plot; this.auto = auto; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the plot involved * * @return Plot */ public Plot getPlot() { - return plot; + return this.plot; } - + /** * @return true if it was an automated claim, else false */ public boolean wasAuto() { - return auto; + return this.auto; } - + @Override public HandlerList getHandlers() { return handlers; } - + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public void setCancelled(final boolean b) { - cancelled = b; + public void setCancelled(boolean b) { + this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java index b144930a5..4c2844eda 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java @@ -20,42 +20,44 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import com.intellectualcrafters.plot.object.Plot; +/** + -/** */ public class PlayerEnterPlotEvent extends PlayerEvent { - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Plot plot; - + /** * PlayerEnterPlotEvent: Called when a player leaves a plot * * @param player Player that entered the plot * @param plot Plot that was entered */ - public PlayerEnterPlotEvent(final Player player, final Plot plot) { + public PlayerEnterPlotEvent(Player player, Plot plot) { super(player); this.plot = plot; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the plot involved * * @return Plot */ public Plot getPlot() { - return plot; + return this.plot; } - + @Override public HandlerList getHandlers() { return handlers; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java index 013be8a6f..063bb7490 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java @@ -20,43 +20,44 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import com.intellectualcrafters.plot.object.Plot; +/** + -/** */ public class PlayerLeavePlotEvent extends PlayerEvent { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Plot plot; - + /** * PlayerLeavePlotEvent: Called when a player leaves a plot * * @param player Player that left the plot * @param plot Plot that was left */ - public PlayerLeavePlotEvent(final Player player, final Plot plot) { + public PlayerLeavePlotEvent(Player player, Plot plot) { super(player); this.plot = plot; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the plot involved * * @return Plot */ public Plot getPlot() { - return plot; + return this.plot; } - + @Override public HandlerList getHandlers() { return handlers; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java index f353c16b1..9d421dd13 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java @@ -20,22 +20,23 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; -import java.util.UUID; - +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.object.Plot; +import java.util.UUID; + +/** + -/** */ public class PlayerPlotDeniedEvent extends PlotEvent { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Player initiator; private final boolean added; private final UUID player; - + /** * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot * @@ -44,44 +45,44 @@ public class PlayerPlotDeniedEvent extends PlotEvent { * @param player Player that was denied/un-denied * @param added true of add to deny list, false if removed */ - public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { + public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) { super(plot); this.initiator = initiator; this.added = added; this.player = player; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * If a user was added * * @return boolean */ public boolean wasAdded() { - return added; + return this.added; } - + /** * The player added/removed * * @return UUID */ public UUID getPlayer() { - return player; + return this.player; } - + /** * The player initiating the action * * @return Player */ public Player getInitiator() { - return initiator; + return this.initiator; } - + @Override public HandlerList getHandlers() { return handlers; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java index bdc013835..a4055f01b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java @@ -20,22 +20,23 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; -import java.util.UUID; - +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.object.Plot; +import java.util.UUID; + +/** + -/** */ public class PlayerPlotHelperEvent extends PlotEvent { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Player initiator; private final boolean added; private final UUID player; - + /** * PlayerPlotHelperEvent: Called when a plot helper is added/removed * @@ -44,44 +45,44 @@ public class PlayerPlotHelperEvent extends PlotEvent { * @param player Player that was added/removed from the helper list * @param added true of the player was added, false if the player was removed */ - public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { + public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) { super(plot); this.initiator = initiator; this.added = added; this.player = player; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * If a player was added * * @return boolean */ public boolean wasAdded() { - return added; + return this.added; } - + /** * The UUID added/removed * * @return UUID */ public UUID getPlayer() { - return player; + return this.player; } - + /** * The player initiating the action * * @return Player */ public Player getInitiator() { - return initiator; + return this.initiator; } - + @Override public HandlerList getHandlers() { return handlers; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java index 41bf08159..675e9fd94 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java @@ -20,22 +20,23 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; -import java.util.UUID; - +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.object.Plot; +import java.util.UUID; + +/** + -/** */ public class PlayerPlotTrustedEvent extends PlotEvent { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Player initiator; private final boolean added; private final UUID player; - + /** * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed * @@ -44,44 +45,44 @@ public class PlayerPlotTrustedEvent extends PlotEvent { * @param player Player that was added/removed from the trusted list * @param added true of the player was added, false if the player was removed */ - public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { + public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) { super(plot); this.initiator = initiator; this.added = added; this.player = player; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * If a player was added * * @return boolean */ public boolean wasAdded() { - return added; + return this.added; } - + /** * The UUID added/removed * * @return UUID */ public UUID getPlayer() { - return player; + return this.player; } - + /** * The player initiating the action * * @return Player */ public Player getInitiator() { - return initiator; + return this.initiator; } - + @Override public HandlerList getHandlers() { return handlers; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java index 5db20d45c..0251941ba 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java @@ -20,24 +20,26 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; - /** * Called when a player teleports to a plot - * + * + + */ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); private final Location from; private final Plot plot; private boolean cancelled; - + /** * PlayerTeleportToPlotEvent: Called when a player teleports to a plot * @@ -45,46 +47,46 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl * @param from Start location * @param plot Plot to which the player was teleported */ - public PlayerTeleportToPlotEvent(final Player player, final Location from, final Plot plot) { + public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { super(player); this.from = from; this.plot = plot; } - + public static HandlerList getHandlerList() { return handlers; } - + @Override public HandlerList getHandlers() { return handlers; } - + /** * Get the from location * * @return Location */ public Location getFrom() { - return from; + return this.from; } - + /** * Get the plot involved * * @return Plot */ public Plot getPlot() { - return plot; + return this.plot; } - + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public void setCancelled(final boolean cancelled) { + public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java index 46b12bc73..83d0cd86f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java @@ -20,28 +20,29 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotId; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; - /** * Called when a plot is cleared - * + * + + */ public class PlotClearEvent extends PlotEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; public PlotClearEvent(Plot plot) { super(plot); } - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; - public static HandlerList getHandlerList() { return handlers; } - + /** * Get the PlotId * @@ -50,7 +51,7 @@ public class PlotClearEvent extends PlotEvent implements Cancellable { public PlotId getPlotId() { return getPlot().getId(); } - + /** * Get the world name * @@ -59,19 +60,19 @@ public class PlotClearEvent extends PlotEvent implements Cancellable { public String getWorld() { return getPlot().getArea().worldname; } - + @Override public HandlerList getHandlers() { return handlers; } - + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public void setCancelled(final boolean b) { - cancelled = b; + public void setCancelled(boolean b) { + this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java index dc2c5e1d0..3b525ad24 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java @@ -20,26 +20,28 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; -import org.bukkit.event.HandlerList; - import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotId; +import org.bukkit.event.HandlerList; /** * Called when a plot is deleted - * + * + + */ public class PlotDeleteEvent extends PlotEvent { + + private static final HandlerList handlers = new HandlerList(); + public PlotDeleteEvent(Plot plot) { super(plot); } - private static HandlerList handlers = new HandlerList(); - public static HandlerList getHandlerList() { return handlers; } - + /** * Get the PlotId * @@ -48,7 +50,7 @@ public class PlotDeleteEvent extends PlotEvent { public PlotId getPlotId() { return getPlot().getId(); } - + /** * Get the world name * @@ -57,7 +59,7 @@ public class PlotDeleteEvent extends PlotEvent { public String getWorld() { return getPlot().getArea().worldname; } - + @Override public HandlerList getHandlers() { return handlers; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java index cc0671f21..94e2dc4cc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java @@ -1,19 +1,18 @@ package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.event.Event; -import com.intellectualcrafters.plot.object.Plot; - public abstract class PlotEvent extends Event { - + private final Plot plot; - - public PlotEvent(final Plot plot) { + + public PlotEvent(Plot plot) { this.plot = plot; } - + public final Plot getPlot() { - return plot; + return this.plot; } - + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java index 5ad2ee1dc..db188eec3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java @@ -20,58 +20,59 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; - /** * Called when a Flag is added to a plot - * + * + + */ public class PlotFlagAddEvent extends PlotEvent implements Cancellable { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Flag flag; private boolean cancelled; - + /** * PlotFlagAddEvent: Called when a Flag is added to a plot * * @param flag Flag that was added * @param plot Plot to which the flag was added */ - public PlotFlagAddEvent(final Flag flag, final Plot plot) { + public PlotFlagAddEvent(Flag flag, Plot plot) { super(plot); this.flag = flag; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the flag involved * * @return Flag */ public Flag getFlag() { - return flag; + return this.flag; } - + @Override public HandlerList getHandlers() { return handlers; } - + @Override public final boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public final void setCancelled(final boolean cancelled) { + public final void setCancelled(boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java index 973ba258c..b2fea0708 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java @@ -20,58 +20,59 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.Plot; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; - /** * Called when a flag is removed from a plot - * + * + + */ public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final Flag flag; private boolean cancelled; - + /** * PlotFlagRemoveEvent: Called when a flag is removed from a plot * * @param flag Flag that was removed * @param plot Plot from which the flag was removed */ - public PlotFlagRemoveEvent(final Flag flag, final Plot plot) { + public PlotFlagRemoveEvent(Flag flag, Plot plot) { super(plot); this.flag = flag; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the flag involved * * @return Flag */ public Flag getFlag() { - return flag; + return this.flag; } - + @Override public HandlerList getHandlers() { return handlers; } - + @Override public final boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public final void setCancelled(final boolean cancelled) { + public final void setCancelled(boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java index cc186fccc..b2c97fc80 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java @@ -20,25 +20,26 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; -import java.util.ArrayList; - +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotId; import org.bukkit.World; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; +import java.util.ArrayList; + +/** -/** */ public class PlotMergeEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final ArrayList plots; private boolean cancelled; private Plot plot; private World world; - + /** * PlotMergeEvent: Called when plots are merged * @@ -46,48 +47,48 @@ public class PlotMergeEvent extends Event implements Cancellable { * @param plot Plot that was merged * @param plots A list of plots involved in the event */ - public PlotMergeEvent(final World world, final Plot plot, final ArrayList plots) { + public PlotMergeEvent(World world, Plot plot, ArrayList plots) { this.plots = plots; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the plots being added; * * @return Plot */ public ArrayList getPlots() { - return plots; + return this.plots; } - + /** * Get the main plot * * @return Plot */ public Plot getPlot() { - return plot; + return this.plot; } - + public World getWorld() { - return world; + return this.world; } - + @Override public HandlerList getHandlers() { return handlers; } - + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public void setCancelled(final boolean b) { - cancelled = b; + public void setCancelled(boolean b) { + this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java index e93b93438..9e10db4ae 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java @@ -1,46 +1,46 @@ package com.plotsquared.bukkit.events; -import org.bukkit.event.HandlerList; - import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.Rating; +import org.bukkit.event.HandlerList; /** * Created 2015-07-13 for PlotSquaredGit - * + * + */ public class PlotRateEvent extends PlotEvent { - - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final PlotPlayer rater; private Rating rating; - - public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot) { + + public PlotRateEvent(PlotPlayer rater, Rating rating, Plot plot) { super(plot); this.rater = rater; this.rating = rating; } - + public static HandlerList getHandlerList() { return handlers; } - + public PlotPlayer getRater() { - return rater; + return this.rater; } - - public void setRating(final Rating rating) { + + public Rating getRating() { + return this.rating; + } + + public void setRating(Rating rating) { this.rating = rating; } - - public Rating getRating() { - return rating; - } - + @Override public HandlerList getHandlers() { return handlers; } - + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java index dabbcbebe..9ec66f70e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java @@ -20,70 +20,71 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; -import java.util.ArrayList; - +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotId; import org.bukkit.World; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; +import java.util.ArrayList; + +/** -/** */ public class PlotUnlinkEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); + + private static final HandlerList handlers = new HandlerList(); private final ArrayList plots; private final World world; - private boolean cancelled; private final PlotArea area; - + private boolean cancelled; + /** * Called when a mega-plot is unlinked. * * @param world World in which the event occurred * @param plots Plots that are involved in the event */ - public PlotUnlinkEvent(final World world, PlotArea area, final ArrayList plots) { + public PlotUnlinkEvent(World world, PlotArea area, ArrayList plots) { this.plots = plots; this.world = world; this.area = area; } - + public static HandlerList getHandlerList() { return handlers; } - + /** * Get the plots involved * * @return PlotId */ public ArrayList getPlots() { - return plots; + return this.plots; } - + public World getWorld() { - return world; + return this.world; } - + public PlotArea getArea() { - return area; + return this.area; } @Override public HandlerList getHandlers() { return handlers; } - + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - + @Override - public void setCancelled(final boolean b) { - cancelled = b; + public void setCancelled(boolean b) { + this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java index e80bec573..231d9c51c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java @@ -10,8 +10,6 @@ import java.util.Random; public class BukkitAugmentedGenerator extends BlockPopulator { private static BukkitAugmentedGenerator generator; - - private BukkitAugmentedGenerator() {} public static BukkitAugmentedGenerator get(World world) { for (BlockPopulator populator : world.getPopulators()) { @@ -27,7 +25,7 @@ public class BukkitAugmentedGenerator extends BlockPopulator { } @Override - public void populate(final World world, Random r, final Chunk chunk) { + public void populate(World world, Random r, Chunk chunk) { AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 6f1cb7c2b..bc81d3447 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -59,10 +59,10 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap public BukkitPlotGenerator(IndependentPlotGenerator generator) { this.plotGenerator = generator; this.platformGenerator = this; - populators.add(new BlockPopulator() { + this.populators.add(new BlockPopulator() { @Override public void populate(World world, Random r, Chunk c) { - GenChunk result = (GenChunk) chunkSetter; + GenChunk result = (GenChunk) BukkitPlotGenerator.this.chunkSetter; if (result.result_data != null) { for (int i = 0; i < result.result_data.length; i++) { byte[] section = result.result_data[i]; @@ -79,7 +79,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } } }); - chunkSetter = new GenChunk(null, null); + this.chunkSetter = new GenChunk(null, null); this.full = true; MainUtil.initCache(); } @@ -90,8 +90,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } this.full = false; PS.debug("BukkitPlotGenerator does not fully support: " + cg); - platformGenerator = cg; - plotGenerator = new IndependentPlotGenerator() { + this.platformGenerator = cg; + this.plotGenerator = new IndependentPlotGenerator() { @Override public void processSetup(SetupObject setup) {} @@ -114,7 +114,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } @Override - public void generateChunk(final PlotChunk result, final PlotArea settings, final PseudoRandom random) { + public void generateChunk(final PlotChunk result, PlotArea settings, PseudoRandom random) { World w = BukkitUtil.getWorld(world); Random r = new Random(result.getChunkWrapper().hashCode()); BiomeGrid grid = new BiomeGrid() { @@ -134,8 +134,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap if (data != null) { return; } + } catch (Throwable e) { + //ignored } - catch (Throwable e) {} // Populator spillage short[][] tmp = cg.generateExtBlockSections(w, r, result.getX(), result.getZ(), grid); if (tmp != null) { @@ -166,9 +167,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } } }; - chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0)); + this.chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0)); if (cg != null) { - populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world))); + this.populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world))); } MainUtil.initCache(); } @@ -180,24 +181,24 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap @Override public boolean isFull() { - return full; + return this.full; } @Override public IndependentPlotGenerator getPlotGenerator() { - return plotGenerator; + return this.plotGenerator; } @Override public ChunkGenerator getPlatformGenerator() { - return platformGenerator; + return this.platformGenerator; } @Override - public List getDefaultPopulators(final World world) { + public List getDefaultPopulators(World world) { try { - if (!loaded) { - final String name = world.getName(); + if (!this.loaded) { + String name = world.getName(); PS.get().loadWorld(name, this); Set areas = PS.get().getPlotAreas(name); if (!areas.isEmpty()) { @@ -218,17 +219,17 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap world.setWaterAnimalSpawnLimit(-1); } } - loaded = true; + this.loaded = true; } - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); } - return populators; + return this.populators; } @Override public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) { - GenChunk result = (GenChunk) chunkSetter; + GenChunk result = (GenChunk) this.chunkSetter; // Set the chunk location result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz)); // Set the result data @@ -239,8 +240,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap // Catch any exceptions (as exceptions usually thrown try { // Fill the result data if necessary - if (platformGenerator != this) { - return platformGenerator.generateChunkData(world, random, cx, cz, grid); + if (this.platformGenerator != this) { + return this.platformGenerator.generateChunkData(world, random, cx, cz, grid); } else { generate(world, cx, cz, result); } @@ -253,10 +254,10 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap public void generate(World world, int cx, int cz, GenChunk result) { // Load if improperly loaded - if (!loaded) { - final String name = world.getName(); + if (!this.loaded) { + String name = world.getName(); PS.get().loadWorld(name, this); - loaded = true; + this.loaded = true; } // Set random seed this.random.state = cx << 16 | cz & 0xFFFF; @@ -265,13 +266,13 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap return; } PlotArea area = PS.get().getPlotArea(world.getName(), null); - plotGenerator.generateChunk(chunkSetter, area, this.random); + this.plotGenerator.generateChunk(this.chunkSetter, area, this.random); ChunkManager.postProcessChunk(result); } @Override - public short[][] generateExtBlockSections(final World world, final Random r, final int cx, final int cz, final BiomeGrid grid) { - GenChunk result = (GenChunk) chunkSetter; + public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) { + GenChunk result = (GenChunk) this.chunkSetter; // Set the chunk location result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz)); // Set the result data @@ -282,8 +283,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap // Catch any exceptions (as exceptions usually thrown try { // Fill the result data - if (platformGenerator != this) { - return platformGenerator.generateExtBlockSections(world, r, cx, cz, grid); + if (this.platformGenerator != this) { + return this.platformGenerator.generateExtBlockSections(world, r, cx, cz, grid); } else { generate(world, cx, cz, result); } @@ -295,19 +296,27 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } /** - * Allow spawning everywhere + * Allow spawning everywhere. + * @param world Ignored + * @param x Ignored + * @param z Ignored + * @return always true */ @Override - public boolean canSpawn(final World world, final int x, final int z) { + public boolean canSpawn(World world, int x, int z) { return true; } @Override public String toString() { - if (platformGenerator == this) { - return "" + plotGenerator; + if (this.platformGenerator == this) { + return "" + this.plotGenerator; + } + if (this.platformGenerator == null) { + return "null"; + } else { + return this.platformGenerator.getClass().getName(); } - return platformGenerator == null ? "null" : platformGenerator.getClass().getName(); } @Override diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java index b7e62eef7..dc402eefe 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java @@ -1,5 +1,7 @@ package com.plotsquared.bukkit.listeners; +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.ChunkLoc; @@ -33,13 +35,9 @@ import java.util.ArrayDeque; import java.util.HashMap; import java.util.Map.Entry; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - public class ChunkListener implements Listener { private RefMethod methodGetHandleChunk; - private RefClass classChunk; - private RefClass classCraftChunk; private RefField mustSave; private Chunk lastChunk; @@ -47,8 +45,8 @@ public class ChunkListener implements Listener { public ChunkListener() { if (Settings.CHUNK_PROCESSOR_GC || Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) { try { - this.classChunk = getRefClass("{nms}.Chunk"); - this.classCraftChunk = getRefClass("{cb}.CraftChunk"); + RefClass classChunk = getRefClass("{nms}.Chunk"); + RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); this.mustSave = classChunk.getField("mustSave"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); } catch (Throwable e) { @@ -63,12 +61,12 @@ public class ChunkListener implements Listener { TaskManager.runTask(new Runnable() { @Override public void run() { - final int distance = Bukkit.getViewDistance() + 2; - final HashMap> players = new HashMap<>(); - for (final Entry entry : UUIDHandler.getPlayers().entrySet()) { - final PlotPlayer pp = entry.getValue(); - final Location loc = pp.getLocation(); - final String world = loc.getWorld(); + int distance = Bukkit.getViewDistance() + 2; + HashMap> players = new HashMap<>(); + for (Entry entry : UUIDHandler.getPlayers().entrySet()) { + PlotPlayer pp = entry.getValue(); + Location location = pp.getLocation(); + String world = location.getWorld(); if (!PS.get().hasPlotArea(world)) { continue; } @@ -77,7 +75,7 @@ public class ChunkListener implements Listener { map = new HashMap<>(); players.put(world, map); } - final ChunkLoc origin = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); + ChunkLoc origin = new ChunkLoc(location.getX() >> 4, location.getZ() >> 4); Integer val = map.get(origin); int check; if (val != null) { @@ -97,8 +95,8 @@ public class ChunkListener implements Listener { if (z >= check || -z >= check) { continue; } - final int weight = distance - Math.max(Math.abs(x), Math.abs(z)); - final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z); + int weight = distance - Math.max(Math.abs(x), Math.abs(z)); + ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z); val = map.get(chunk); if (val == null || val < weight) { map.put(chunk, weight); @@ -108,24 +106,24 @@ public class ChunkListener implements Listener { } } int time = 300; - for (final World world : Bukkit.getWorlds()) { - final String name = world.getName(); + for (World world : Bukkit.getWorlds()) { + String name = world.getName(); if (!PS.get().hasPlotArea(name)) { continue; } - final boolean autosave = world.isAutoSave(); + boolean autosave = world.isAutoSave(); if (autosave) { world.setAutoSave(false); } - final HashMap map = players.get(name); + HashMap map = players.get(name); if (map == null || map.isEmpty()) { continue; } Chunk[] chunks = world.getLoadedChunks(); ArrayDeque toUnload = new ArrayDeque<>(); - for (final Chunk chunk : chunks) { - final int x = chunk.getX(); - final int z = chunk.getZ(); + for (Chunk chunk : chunks) { + int x = chunk.getX(); + int z = chunk.getZ(); if (!map.containsKey(new ChunkLoc(x, z))) { toUnload.add(chunk); } @@ -152,14 +150,14 @@ public class ChunkListener implements Listener { } }); } - - public boolean unloadChunk(final String world, final Chunk chunk) { - final int X = chunk.getX(); - final int Z = chunk.getZ(); - final int x = X << 4; - final int z = Z << 4; - final int x2 = x + 15; - final int z2 = z + 15; + + public boolean unloadChunk(String world, Chunk chunk) { + int X = chunk.getX(); + int Z = chunk.getZ(); + int x = X << 4; + int z = Z << 4; + int x2 = x + 15; + int z2 = z + 15; Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs(); if (plot != null && plot.hasOwner()) { return false; @@ -180,8 +178,8 @@ public class ChunkListener implements Listener { if (plot != null && plot.hasOwner()) { return false; } - final Object c = methodGetHandleChunk.of(chunk).call(); - mustSave.of(c).set(false); + Object c = this.methodGetHandleChunk.of(chunk).call(); + this.mustSave.of(c).set(false); if (chunk.isLoaded()) { chunk.unload(false, false); } @@ -189,10 +187,10 @@ public class ChunkListener implements Listener { } @EventHandler - public void onChunkUnload(final ChunkUnloadEvent event) { + public void onChunkUnload(ChunkUnloadEvent event) { if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) { - final Chunk chunk = event.getChunk(); - final String world = chunk.getWorld().getName(); + Chunk chunk = event.getChunk(); + String world = chunk.getWorld().getName(); if (PS.get().hasPlotArea(world)) { if (unloadChunk(world, chunk)) { return; @@ -205,15 +203,15 @@ public class ChunkListener implements Listener { } @EventHandler - public void onChunkLoad(final ChunkLoadEvent event) { + public void onChunkLoad(ChunkLoadEvent event) { processChunk(event.getChunk(), false); } @EventHandler(priority = EventPriority.LOWEST) - public void onItemSpawn(final ItemSpawnEvent event) { - final Item entity = event.getEntity(); - final Chunk chunk = entity.getLocation().getChunk(); - if (chunk == lastChunk) { + public void onItemSpawn(ItemSpawnEvent event) { + Item entity = event.getEntity(); + Chunk chunk = entity.getLocation().getChunk(); + if (chunk == this.lastChunk) { event.getEntity().remove(); event.setCancelled(true); return; @@ -221,28 +219,28 @@ public class ChunkListener implements Listener { if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { return; } - final Entity[] entities = chunk.getEntities(); + Entity[] entities = chunk.getEntities(); if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) { event.getEntity().remove(); event.setCancelled(true); - lastChunk = chunk; + this.lastChunk = chunk; } else { - lastChunk = null; + this.lastChunk = null; } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPhysics(final BlockPhysicsEvent event) { + public void onBlockPhysics(BlockPhysicsEvent event) { if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST) - public void onEntitySpawn(final CreatureSpawnEvent event) { - final LivingEntity entity = event.getEntity(); - final Chunk chunk = entity.getLocation().getChunk(); - if (chunk == lastChunk) { + public void onEntitySpawn(CreatureSpawnEvent event) { + LivingEntity entity = event.getEntity(); + Chunk chunk = entity.getLocation().getChunk(); + if (chunk == this.lastChunk) { event.getEntity().remove(); event.setCancelled(true); return; @@ -250,20 +248,20 @@ public class ChunkListener implements Listener { if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { return; } - final Entity[] entities = chunk.getEntities(); + Entity[] entities = chunk.getEntities(); if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) { event.getEntity().remove(); event.setCancelled(true); - lastChunk = chunk; + this.lastChunk = chunk; } else { - lastChunk = null; + this.lastChunk = null; } } public void cleanChunk(final Chunk chunk) { TaskManager.index.incrementAndGet(); final Integer currentIndex = TaskManager.index.get(); - final Integer task = TaskManager.runTaskRepeat(new Runnable() { + Integer task = TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { if (!chunk.isLoaded()) { @@ -273,7 +271,7 @@ public class ChunkListener implements Listener { chunk.unload(true, true); return; } - final BlockState[] tiles = chunk.getTileEntities(); + BlockState[] tiles = chunk.getTileEntities(); if (tiles.length == 0) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); @@ -281,7 +279,7 @@ public class ChunkListener implements Listener { chunk.unload(true, true); return; } - final long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); int i = 0; while (System.currentTimeMillis() - start < 250) { if (i >= tiles.length) { @@ -298,15 +296,15 @@ public class ChunkListener implements Listener { }, 5); TaskManager.tasks.put(currentIndex, task); } - - public boolean processChunk(final Chunk chunk, final boolean unload) { + + public boolean processChunk(Chunk chunk, boolean unload) { if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { return false; } - final Entity[] entities = chunk.getEntities(); - final BlockState[] tiles = chunk.getTileEntities(); + Entity[] entities = chunk.getEntities(); + BlockState[] tiles = chunk.getTileEntities(); if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) { - for (final Entity ent : entities) { + for (Entity ent : entities) { if (!(ent instanceof Player)) { ent.remove(); } @@ -319,7 +317,7 @@ public class ChunkListener implements Listener { cleanChunk(chunk); return true; } - for (final BlockState tile : tiles) { + for (BlockState tile : tiles) { tile.getBlock().setType(Material.AIR, false); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java index 12f941c81..1d41a89b1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java @@ -37,14 +37,12 @@ import java.util.HashSet; import java.util.Set; import java.util.UUID; -/** - - */ public class ForceFieldListener implements Listener { - private Set getNearbyPlayers(final Player player, final Plot plot) { - final Set players = new HashSet<>(); - PlotPlayer pp; - for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { + + private Set getNearbyPlayers(Player player, Plot plot) { + Set players = new HashSet<>(); + for (Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { + PlotPlayer pp; if (!(entity instanceof Player) || ((pp = BukkitUtil.getPlayer((Player) entity)) == null) || !plot.equals(pp.getCurrentPlot())) { continue; } @@ -54,10 +52,10 @@ public class ForceFieldListener implements Listener { } return players; } - - private PlotPlayer hasNearbyPermitted(final Player player, final Plot plot) { - PlotPlayer pp; - for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { + + private PlotPlayer hasNearbyPermitted(Player player, Plot plot) { + for (Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { + PlotPlayer pp; if (!(entity instanceof Player) || ((pp = BukkitUtil.getPlayer((Player) entity)) == null) || !plot.equals(pp.getCurrentPlot())) { continue; } @@ -67,12 +65,16 @@ public class ForceFieldListener implements Listener { } return null; } - - public Vector calculateVelocity(final PlotPlayer pp, final PlotPlayer e) { + + public Vector calculateVelocity(PlotPlayer pp, PlotPlayer e) { Location playerLocation = pp.getLocationFull(); Location oPlayerLocation = e.getLocation(); - final double playerX = playerLocation.getX(), playerY = playerLocation.getY(), playerZ = playerLocation.getZ(), oPlayerX = oPlayerLocation.getX(), oPlayerY = oPlayerLocation.getY(), oPlayerZ = oPlayerLocation - .getZ(); + double playerX = playerLocation.getX(); + double playerY = playerLocation.getY(); + double playerZ = playerLocation.getZ(); + double oPlayerX = oPlayerLocation.getX(); + double oPlayerY = oPlayerLocation.getY(); + double oPlayerZ = oPlayerLocation.getZ(); double x = 0d; if (playerX < oPlayerX) { x = 1.0d; @@ -93,25 +95,25 @@ public class ForceFieldListener implements Listener { } return new Vector(x, y, z); } - + @EventHandler - public void onPlotEntry(final PlayerEnterPlotEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = event.getPlot(); + public void onPlotEntry(PlayerEnterPlotEvent event) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = event.getPlot(); if (plot == null) { return; } if ((FlagManager.getPlotFlagRaw(plot, "forcefield") != null) && FlagManager.getPlotFlagRaw(plot, "forcefield").getValue().equals("true")) { if (!FlagManager.isBooleanFlag(plot, "forcefield", false)) { - final UUID uuid = pp.getUUID(); + UUID uuid = pp.getUUID(); if (plot.isAdded(uuid)) { - final Set players = getNearbyPlayers(player, plot); - for (final PlotPlayer oPlayer : players) { + Set players = getNearbyPlayers(player, plot); + for (PlotPlayer oPlayer : players) { ((BukkitPlayer) oPlayer).player.setVelocity(calculateVelocity(pp, oPlayer)); } } else { - final PlotPlayer oPlayer = hasNearbyPermitted(player, plot); + PlotPlayer oPlayer = hasNearbyPermitted(player, plot); if (oPlayer == null) { return; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java index 5e4d81812..93109581a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java @@ -123,23 +123,23 @@ import java.util.regex.Pattern; * */ public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener { - + private boolean pistonBlocks = true; private float lastRadius; // To prevent recursion private boolean tmp_teleport = true; - + public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) { TaskManager.runTaskLater(new Runnable() { @Override public void run() { - final String world = bloc.getWorld().getName(); - final int x = bloc.getBlockX(); - final int z = bloc.getBlockZ(); - final int distance = Bukkit.getViewDistance() * 16; + String world = bloc.getWorld().getName(); + int x = bloc.getBlockX(); + int z = bloc.getBlockZ(); + int distance = Bukkit.getViewDistance() * 16; for (Entry entry : UUIDHandler.getPlayers().entrySet()) { PlotPlayer player = entry.getValue(); - final Location loc = player.getLocation(); + Location loc = player.getLocation(); if (loc.getWorld().equals(world)) { if (16 * Math.abs(loc.getX() - x) / 16 > distance || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { continue; @@ -150,10 +150,10 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } }, 3); } - + @EventHandler - public void onRedstoneEvent(final BlockRedstoneEvent event) { - final Block block = event.getBlock(); + public void onRedstoneEvent(BlockRedstoneEvent event) { + Block block = event.getBlock(); switch (block.getType()) { case REDSTONE_LAMP_OFF: case REDSTONE_WIRE: @@ -184,16 +184,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case POWERED_RAIL: return; default: - final Location loc = BukkitUtil.getLocation(block.getLocation()); + Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(loc); if (plot == null) { return; } - final Flag redstone = FlagManager.getPlotFlagRaw(plot, "redstone"); + Flag redstone = FlagManager.getPlotFlagRaw(plot, "redstone"); if (redstone != null) { if ((Boolean) redstone.getValue()) { return; @@ -205,7 +205,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (Settings.REDSTONE_DISABLER) { if (UUIDHandler.getPlayer(plot.owner) == null) { boolean disable = true; - for (final UUID trusted : plot.getTrusted()) { + for (UUID trusted : plot.getTrusted()) { if (UUIDHandler.getPlayer(trusted) != null) { disable = false; break; @@ -227,19 +227,19 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onPhysicsEvent(final BlockPhysicsEvent event) { + public void onPhysicsEvent(BlockPhysicsEvent event) { switch (event.getChangedType()) { case REDSTONE_COMPARATOR_OFF: case REDSTONE_COMPARATOR_ON: { - final Block block = event.getBlock(); - final Location loc = BukkitUtil.getLocation(block.getLocation()); + Block block = event.getBlock(); + Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(loc); if (plot == null) { return; } @@ -252,13 +252,13 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case ANVIL: case SAND: case GRAVEL: - final Block block = event.getBlock(); - final Location loc = BukkitUtil.getLocation(block.getLocation()); + Block block = event.getBlock(); + Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(loc); if (plot != null && FlagManager.isPlotFlagTrue(plot, "disable-physics")) { event.setCancelled(true); return; @@ -268,11 +268,11 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen break; } } - + @EventHandler - public void onProjectileHit(final ProjectileHitEvent event) { - final Projectile entity = event.getEntity(); - final Location loc = BukkitUtil.getLocation(entity); + public void onProjectileHit(ProjectileHitEvent event) { + Projectile entity = event.getEntity(); + Location loc = BukkitUtil.getLocation(entity); if (!PS.get().hasPlotArea(loc.getWorld())) { return; } @@ -282,9 +282,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } Plot plot = area.getPlotAbs(loc); // - final ProjectileSource shooter = entity.getShooter(); + ProjectileSource shooter = entity.getShooter(); if (shooter instanceof Player) { - final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); + PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { entity.remove(); @@ -300,29 +300,29 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen entity.remove(); return; } - final Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); if (!area.contains(sLoc.getX(), sLoc.getZ())) { entity.remove(); return; } - final Plot sPlot = area.getOwnedPlotAbs(sLoc); + Plot sPlot = area.getOwnedPlotAbs(sLoc); if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) { entity.remove(); } } } - + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void PlayerCommand(final PlayerCommandPreprocessEvent event) { + public void PlayerCommand(PlayerCommandPreprocessEvent event) { String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); if (msg.isEmpty()) { return; } - final String[] split = msg.split(" "); - final PluginCommand cmd = Bukkit.getServer().getPluginCommand(split[0]); + String[] split = msg.split(" "); + PluginCommand cmd = Bukkit.getServer().getPluginCommand(split[0]); if (cmd == null) { if (split[0].equals("plotme") || split[0].equals("ap")) { - final Player player = event.getPlayer(); + Player player = event.getPlayer(); if (Settings.USE_PLOTME_ALIAS) { player.performCommand("plots " + StringMan.join(Arrays.copyOfRange(split, 1, split.length), " ")); } else { @@ -332,8 +332,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } } - final Player player = event.getPlayer(); - final BukkitPlayer pp = (BukkitPlayer) BukkitUtil.getPlayer(player); + Player player = event.getPlayer(); + BukkitPlayer pp = (BukkitPlayer) BukkitUtil.getPlayer(player); Plot plot = pp.getCurrentPlot(); if (plot == null) { return; @@ -342,20 +342,20 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (flag == null || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { return; } - final List v = (List) flag.getValue(); - final String[] parts = msg.split(" "); + List v = (List) flag.getValue(); + String[] parts = msg.split(" "); String c = parts[0]; if (parts[0].contains(":")) { c = parts[0].split(":")[1]; msg = msg.replace(parts[0].split(":")[0] + ":", ""); } - final String l = c; - final List aliases = new ArrayList<>(); - for (final HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { + String l = c; + List aliases = new ArrayList<>(); + for (HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { if (c.equals(cmdLabel.getName())) { break; } - final String label = cmdLabel.getName().replaceFirst("/", ""); + String label = cmdLabel.getName().replaceFirst("/", ""); if (aliases.contains(label)) { continue; } @@ -377,7 +377,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (!l.equals(c)) { msg = msg.replace(l, c); } - for (final String s : v) { + for (String s : v) { Pattern pattern; if (!RegExUtil.compiledPatterns.containsKey(s)) { RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); @@ -399,16 +399,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onConnect(final PlayerJoinEvent event) { + public void onConnect(PlayerJoinEvent event) { final Player player = event.getPlayer(); BukkitUtil.getPlayer(event.getPlayer()).unregister(); final PlotPlayer pp = BukkitUtil.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(); @@ -432,15 +432,15 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } }, 20); } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void PlayerMove(final PlayerMoveEvent event) { - final org.bukkit.Location from = event.getFrom(); - final org.bukkit.Location to = event.getTo(); + public void PlayerMove(PlayerMoveEvent event) { + org.bukkit.Location from = event.getFrom(); + org.bukkit.Location to = event.getTo(); int x2; if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); // Cancel teleport TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location @@ -452,7 +452,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } Plot now = area.getPlot(loc); - final Plot lastPlot = pp.getMeta("lastplot"); + Plot lastPlot = pp.getMeta("lastplot"); if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); @@ -472,7 +472,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } - final Integer border = area.getBorder(); + Integer border = area.getBorder(); if (x2 > border) { to.setX(border - 4); player.teleport(event.getTo()); @@ -488,8 +488,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } int z2; if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); // Cancel teleport TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location @@ -501,7 +501,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } Plot now = area.getPlot(loc); - final Plot lastPlot = pp.getMeta("lastplot"); + Plot lastPlot = pp.getMeta("lastplot"); if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); @@ -521,7 +521,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } - final Integer border = area.getBorder(); + Integer border = area.getBorder(); if (z2 > border) { to.setZ(border - 4); player.teleport(event.getTo()); @@ -533,28 +533,28 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onChat(final AsyncPlayerChatEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer plr = BukkitUtil.getPlayer(player); + public void onChat(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + PlotPlayer plr = BukkitUtil.getPlayer(player); Location loc = plr.getLocation(); PlotArea area = loc.getPlotArea(); if (area == null || !area.PLOT_CHAT && !plr.getAttribute("chat")) { return; } - final Plot plot = area.getPlotAbs(loc); + Plot plot = area.getPlotAbs(loc); if (plot == null) { return; } - final String message = event.getMessage(); + String message = event.getMessage(); String format = C.PLOT_CHAT_FORMAT.s(); - final String sender = event.getPlayer().getDisplayName(); - final PlotId id = plot.getId(); - final Set recipients = event.getRecipients(); + String sender = event.getPlayer().getDisplayName(); + PlotId id = plot.getId(); + Set recipients = event.getRecipients(); recipients.clear(); - for (final Player p : Bukkit.getOnlinePlayers()) { - final PlotPlayer pp = BukkitUtil.getPlayer(p); + for (Player p : Bukkit.getOnlinePlayers()) { + PlotPlayer pp = BukkitUtil.getPlayer(p); if (pp.getAttribute("chatspy")) { String spy = event.getFormat(); spy = String.format(spy, sender, message); @@ -567,22 +567,22 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen format = ChatColor.translateAlternateColorCodes('&', format); event.setFormat(format); } - + @EventHandler(priority = EventPriority.LOWEST) - public void BlockDestroy(final BlockBreakEvent event) { - final Player player = event.getPlayer(); - final Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); + public void BlockDestroy(BlockBreakEvent event) { + Player player = event.getPlayer(); + Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getPlotAbs(loc); + Plot plot = area.getPlotAbs(loc); if (plot != null) { if (event.getBlock().getY() == 0) { event.setCancelled(true); return; } - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (!plot.hasOwner()) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; @@ -591,8 +591,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } else if (!plot.isAdded(pp.getUUID())) { - final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); - final Block block = event.getBlock(); + Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); + Block block = event.getBlock(); if (destroy != null && ((HashSet) destroy.getValue()) .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { return; @@ -611,7 +611,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } return; } - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } @@ -623,16 +623,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); event.setCancelled(true); } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(final EntityExplodeEvent event) { + public void onBigBoom(EntityExplodeEvent event) { Location loc = BukkitUtil.getLocation(event.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { if (!PS.get().hasPlotArea(loc.getWorld())) { return; } - final Iterator iter = event.blockList().iterator(); + Iterator iter = event.blockList().iterator(); while (iter.hasNext()) { iter.next(); if (loc.getPlotArea() != null) { @@ -651,20 +651,20 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } else { origin = (Plot) meta.get(0).value(); } - if (lastRadius != 0) { - final List nearby = event.getEntity().getNearbyEntities(lastRadius, lastRadius, lastRadius); - for (final Entity near : nearby) { + if (this.lastRadius != 0) { + List nearby = event.getEntity().getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); + for (Entity near : nearby) { if (near instanceof TNTPrimed || near.getType() == EntityType.MINECART_TNT) { if (!near.hasMetadata("plot")) { near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); } } } - lastRadius = 0; + this.lastRadius = 0; } - final Iterator iter = event.blockList().iterator(); + Iterator iter = event.blockList().iterator(); while (iter.hasNext()) { - final Block b = iter.next(); + Block b = iter.next(); loc = BukkitUtil.getLocation(b.getLocation()); if (!area.contains(loc.getX(), loc.getZ()) || !origin.equals(area.getOwnedPlot(loc))) { iter.remove(); @@ -675,11 +675,11 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } event.setCancelled(true); } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onWorldChanged(final PlayerChangedWorldEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + public void onWorldChanged(PlayerChangedWorldEvent event) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); // Delete last location @@ -700,22 +700,22 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen pp.deleteMeta("perm"); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPeskyMobsChangeTheWorldLikeWTFEvent(final EntityChangeBlockEvent event) { - final String world = event.getBlock().getWorld().getName(); + public void onPeskyMobsChangeTheWorldLikeWTFEvent(EntityChangeBlockEvent event) { + String world = event.getBlock().getWorld().getName(); if (!PS.get().hasPlotArea(world)) { return; } - final Entity e = event.getEntity(); + Entity e = event.getEntity(); if (!(e instanceof org.bukkit.entity.FallingBlock)) { event.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityBlockForm(final EntityBlockFormEvent e) { - final String world = e.getBlock().getWorld().getName(); + public void onEntityBlockForm(EntityBlockFormEvent e) { + String world = e.getBlock().getWorld().getName(); if (!PS.get().hasPlotArea(world)) { return; } @@ -723,28 +723,28 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBS(final BlockSpreadEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onBS(BlockSpreadEvent e) { + Block b = e.getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); if (loc.isPlotRoad()) { e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBF(final BlockFormEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onBF(BlockFormEvent e) { + Block b = e.getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); if (loc.isPlotRoad()) { e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBD(final BlockDamageEvent event) { - final Player player = event.getPlayer(); + public void onBD(BlockDamageEvent event) { + Player player = event.getPlayer(); Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); if (player == null) { if (loc.isPlotRoad()) { @@ -756,24 +756,24 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (area == null) { return; } - final Plot plot = area.getPlotAbs(loc); + Plot plot = area.getPlotAbs(loc); if (plot != null) { if (loc.getY() == 0) { event.setCancelled(true); return; } if (!plot.hasOwner()) { - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; } event.setCancelled(true); return; } - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (!plot.isAdded(pp.getUUID())) { - final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); - final Block block = event.getBlock(); + Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); + Block block = event.getBlock(); if (destroy != null && ((HashSet) destroy.getValue()) .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { return; @@ -786,16 +786,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } return; } - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } event.setCancelled(true); } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onFade(final BlockFadeEvent e) { - final Block b = e.getBlock(); + public void onFade(BlockFadeEvent e) { + Block b = e.getBlock(); Location loc = BukkitUtil.getLocation(b.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { @@ -805,9 +805,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onChange(final BlockFromToEvent e) { + public void onChange(BlockFromToEvent e) { Block from = e.getBlock(); Block to = e.getToBlock(); Location tloc = BukkitUtil.getLocation(to.getLocation()); @@ -817,32 +817,33 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } Plot plot = area.getOwnedPlot(tloc); Location floc = BukkitUtil.getLocation(from.getLocation()); - if (!area.contains(floc.getX(), floc.getZ()) || !Objects.equals(plot, area.getOwnedPlot(floc)) || (plot != null && FlagManager.isPlotFlagTrue(plot, "disable-physics"))) { + if (!area.contains(floc.getX(), floc.getZ()) || !Objects.equals(plot, area.getOwnedPlot(floc)) || (plot != null && FlagManager + .isPlotFlagTrue(plot, "disable-physics"))) { e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onGrow(final BlockGrowEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onGrow(BlockGrowEvent e) { + Block b = e.getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); if (loc.isUnownedPlotArea()) { e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonExtend(final BlockPistonExtendEvent event) { - final Block block = event.getBlock(); - final Location loc = BukkitUtil.getLocation(block.getLocation()); - final BlockFace face = event.getDirection(); - final Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + Block block = event.getBlock(); + Location loc = BukkitUtil.getLocation(block.getLocation()); + BlockFace face = event.getDirection(); + Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); PlotArea area = loc.getPlotArea(); if (area == null) { if (!PS.get().hasPlotArea(loc.getWorld())) { return; } - for (final Block b : event.getBlocks()) { + for (Block b : event.getBlocks()) { if (BukkitUtil.getLocation(b.getLocation().add(relative)).getPlotArea() != null) { event.setCancelled(true); return; @@ -850,14 +851,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } return; } - final Plot plot = area.getOwnedPlot(loc); + Plot plot = area.getOwnedPlot(loc); if (plot == null) { event.setCancelled(true); return; } - final List blocks = event.getBlocks(); - for (final Block b : blocks) { - final Location bloc = BukkitUtil.getLocation(b.getLocation().add(relative)); + List blocks = event.getBlocks(); + for (Block b : blocks) { + Location bloc = BukkitUtil.getLocation(b.getLocation().add(relative)); if (!area.contains(bloc.getX(), bloc.getZ())) { event.setCancelled(true); return; @@ -868,31 +869,31 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonRetract(final BlockPistonRetractEvent event) { - final Block block = event.getBlock(); + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + Block block = event.getBlock(); Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { if (!PS.get().hasPlotArea(loc.getWorld())) { return; } - if (pistonBlocks) { + if (this.pistonBlocks) { try { - for (final Block pulled : event.getBlocks()) { + for (Block pulled : event.getBlocks()) { loc = BukkitUtil.getLocation(pulled.getLocation()); if (loc.getPlotArea() != null) { event.setCancelled(true); return; } } - } catch (final Throwable e) { - pistonBlocks = false; + } catch (Throwable e) { + this.pistonBlocks = false; } } - if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { - final BlockFace dir = event.getDirection(); + if (!this.pistonBlocks && block.getType() != Material.PISTON_BASE) { + BlockFace dir = event.getDirection(); loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (loc.getPlotArea() != null) { event.setCancelled(true); @@ -902,9 +903,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } Plot plot = area.getOwnedPlot(loc); - if (pistonBlocks) { + if (this.pistonBlocks) { try { - for (final Block pulled : event.getBlocks()) { + for (Block pulled : event.getBlocks()) { loc = BukkitUtil.getLocation(pulled.getLocation()); if (!area.contains(loc.getX(), loc.getZ())) { event.setCancelled(true); @@ -916,12 +917,12 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } } - } catch (final Throwable e) { - pistonBlocks = false; + } catch (Throwable e) { + this.pistonBlocks = false; } } - if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { - final BlockFace dir = event.getDirection(); + if (!this.pistonBlocks && block.getType() != Material.PISTON_BASE) { + BlockFace dir = event.getDirection(); loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (!area.contains(loc)) { event.setCancelled(true); @@ -933,25 +934,25 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDispense(final BlockDispenseEvent e) { + public void onBlockDispense(BlockDispenseEvent e) { Material type = e.getItem().getType(); if (type != Material.WATER_BUCKET && type != Material.LAVA_BUCKET) { return; } - final Location loc = BukkitUtil.getLocation(e.getVelocity().toLocation(e.getBlock().getWorld())); + Location loc = BukkitUtil.getLocation(e.getVelocity().toLocation(e.getBlock().getWorld())); if (loc.isPlotRoad()) { e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onStructureGrow(final StructureGrowEvent e) { + public void onStructureGrow(StructureGrowEvent e) { if (!PS.get().hasPlotArea(e.getWorld().getName())) { return; } - final List blocks = e.getBlocks(); + List blocks = e.getBlocks(); if (blocks.isEmpty()) { return; } @@ -977,30 +978,30 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen blocks.remove(i); continue; } - final Plot plot = area.getOwnedPlot(loc); + Plot plot = area.getOwnedPlot(loc); if (!Objects.equals(plot, origin)) { e.getBlocks().remove(i); } } } - final Plot origin = area.getPlotAbs(loc); + Plot origin = area.getPlotAbs(loc); if (origin == null) { e.setCancelled(true); return; } for (int i = blocks.size() - 1; i >= 0; i--) { loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); - final Plot plot = area.getOwnedPlot(loc); + Plot plot = area.getOwnedPlot(loc); if (!Objects.equals(plot, origin)) { e.getBlocks().remove(i); } } } - + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onInteract(final PlayerInteractEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + public void onInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); PlotArea area = pp.getPlotAreaAbs(); if (area == null) { return; @@ -1008,7 +1009,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen PlayerBlockEventType eventType = null; BukkitLazyBlock lb; Location loc; - final Action action = event.getAction(); + Action action = event.getAction(); switch (action) { case PHYSICAL: { eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; @@ -1020,8 +1021,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case RIGHT_CLICK_BLOCK: { Block block = event.getClickedBlock(); loc = BukkitUtil.getLocation(block.getLocation()); - final Material blockType = block.getType(); - final int blockId = blockType.getId(); + Material blockType = block.getType(); + int blockId = blockType.getId(); switch (blockType) { case ANVIL: case ACACIA_DOOR: @@ -1083,7 +1084,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen break; } lb = new BukkitLazyBlock(blockId, block); - final ItemStack hand = player.getItemInHand(); + ItemStack hand = player.getItemInHand(); if (eventType != null) { break; } @@ -1179,19 +1180,19 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void MobSpawn(final CreatureSpawnEvent event) { - final Entity entity = event.getEntity(); + public void MobSpawn(CreatureSpawnEvent event) { + Entity entity = event.getEntity(); if (entity instanceof Player) { return; } - final Location loc = BukkitUtil.getLocation(entity.getLocation()); - final PlotArea area = loc.getPlotArea(); + Location loc = BukkitUtil.getLocation(entity.getLocation()); + PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); + CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); switch (reason) { case SPAWNER_EGG: case DISPENSE_EGG: @@ -1222,7 +1223,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } break; } - final Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(loc); if (plot == null) { if (!area.MOB_SPAWNING) { event.setCancelled(true); @@ -1233,24 +1234,24 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); } } - + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onEntityFall(final EntityChangeBlockEvent event) { + public void onEntityFall(EntityChangeBlockEvent event) { if (event.getEntityType() != EntityType.FALLING_BLOCK) { return; } - final Block block = event.getBlock(); - final World world = block.getWorld(); - final String worldname = world.getName(); + Block block = event.getBlock(); + World world = block.getWorld(); + String worldname = world.getName(); if (!PS.get().hasPlotArea(worldname)) { return; } - final Location loc = BukkitUtil.getLocation(block.getLocation()); + Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(loc); if (plot == null) { event.setCancelled(true); return; @@ -1270,15 +1271,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); entity.remove(); } - } - else if (event.getTo() == Material.AIR) { + } else if (event.getTo() == Material.AIR) { event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); } } - + @EventHandler - public void onPrime(final ExplosionPrimeEvent event) { - lastRadius = event.getRadius() + 1; + public void onPrime(ExplosionPrimeEvent event) { + this.lastRadius = event.getRadius() + 1; } public boolean checkEntity(Plot plot, String... flags) { @@ -1307,7 +1307,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen default: i = 0; } - final Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag); + Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag); if (plotFlag == null) { continue; } @@ -1321,7 +1321,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return false; } - public boolean checkEntity(final Entity entity, final Plot plot) { + public boolean checkEntity(Entity entity, Plot plot) { if (plot == null || plot.owner == null || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS.isEmpty()) { return false; } @@ -1429,155 +1429,137 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBurn(final BlockBurnEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onBlockBurn(BlockBurnEvent e) { + Block b = e.getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Plot plot = loc.getOwnedPlot(); + Plot plot = loc.getOwnedPlot(); if (plot == null || !FlagManager.isBooleanFlag(plot, "block-burn", false)) { e.setCancelled(true); return; } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockIgnite(final BlockIgniteEvent e) { - final Player player = e.getPlayer(); - final Entity ent = e.getIgnitingEntity(); - final Block b = e.getBlock(); - final BlockIgniteEvent.IgniteCause c = e.getCause(); - final Location loc; - if (b != null) { - loc = BukkitUtil.getLocation(b.getLocation()); + public void onBlockIgnite(BlockIgniteEvent event) { + Player player = event.getPlayer(); + Entity ignitingEntity = event.getIgnitingEntity(); + Block block = event.getBlock(); + BlockIgniteEvent.IgniteCause igniteCause = event.getCause(); + Location loc; + if (block != null) { + loc = BukkitUtil.getLocation(block.getLocation()); + } else if (ignitingEntity != null) { + loc = BukkitUtil.getLocation(ignitingEntity); + } else if (player != null) { + loc = BukkitUtil.getLocation(player); } else { - if (ent != null) { - loc = BukkitUtil.getLocation(ent); - } else if (player != null) { - loc = BukkitUtil.getLocation(player); - } else { - return; - } + return; } PlotArea area = loc.getPlotArea(); if (area == null) { return; } - if (c == BlockIgniteEvent.IgniteCause.LIGHTNING) { - e.setCancelled(true); + if (igniteCause == BlockIgniteEvent.IgniteCause.LIGHTNING) { + event.setCancelled(true); return; } - final Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(loc); if (player != null) { - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); - e.setCancelled(true); + event.setCancelled(true); } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - e.setCancelled(true); - } - } else { - if (!plot.isAdded(pp.getUUID())) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); - } - } else if (!FlagManager.isPlotFlagTrue(plot, "block-ignition")) { - e.setCancelled(true); - } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); } + } else if (!plot.isAdded(pp.getUUID())) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } + } else if (!FlagManager.isPlotFlagTrue(plot, "block-ignition")) { + event.setCancelled(true); } - } - else if (ent != null) { + } else if (ignitingEntity != null) { if (plot == null || !FlagManager.isPlotFlagTrue(plot, "block-ignition")) { - e.setCancelled(true); + event.setCancelled(true); return; } - if (c == BlockIgniteEvent.IgniteCause.FIREBALL) { - if (ent instanceof Fireball) { - final Projectile fireball = (Fireball) ent; + if (igniteCause == BlockIgniteEvent.IgniteCause.FIREBALL) { + if (ignitingEntity instanceof Fireball) { + Projectile fireball = (Projectile) ignitingEntity; + Location location = null; if (fireball.getShooter() instanceof Entity) { - final Entity shooter = (Entity) fireball.getShooter(); - if (BukkitUtil.getLocation(shooter.getLocation()).getPlot() == null) { - e.setCancelled(true); - return; - } - if (!BukkitUtil.getLocationFull(shooter).getPlot().equals(plot)) { - e.setCancelled(true); - return; - } + Entity shooter = (Entity) fireball.getShooter(); + location = BukkitUtil.getLocation(shooter.getLocation()); } else if (fireball.getShooter() instanceof BlockProjectileSource) { - final Block shooter = ((BlockProjectileSource) fireball.getShooter()).getBlock(); - if (BukkitUtil.getLocation(shooter.getLocation()).getPlot() == null) { - e.setCancelled(true); - return; - } - if (!BukkitUtil.getLocation(shooter.getLocation()).getPlot().equals(plot)) { - e.setCancelled(true); - return; - } + Block shooter = ((BlockProjectileSource) fireball.getShooter()).getBlock(); + location = BukkitUtil.getLocation(shooter.getLocation()); + } + if (location != null && (location.getPlot() == null || !location.getPlot().equals(plot))) { + event.setCancelled(true); } } } - } - else if (e.getIgnitingBlock() != null) { - final Block igniter = e.getIgnitingBlock(); - if (c == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) { + } else if (event.getIgnitingBlock() != null) { + Block igniter = event.getIgnitingBlock(); + if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) { if (plot == null || !FlagManager.isPlotFlagTrue(plot, "block-ignition")) { - e.setCancelled(true); + event.setCancelled(true); return; } if (BukkitUtil.getLocation(igniter.getLocation()).getPlot() == null) { - e.setCancelled(true); + event.setCancelled(true); return; } if (!BukkitUtil.getLocation(igniter.getLocation()).getPlot().equals(plot)) { - e.setCancelled(true); + event.setCancelled(true); return; } } - if (c == BlockIgniteEvent.IgniteCause.SPREAD || c == BlockIgniteEvent.IgniteCause.LAVA) { + if (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) { if (plot == null || !FlagManager.isPlotFlagTrue(plot, "fire-spread")) { - e.setCancelled(true); + event.setCancelled(true); return; } if (BukkitUtil.getLocation(igniter.getLocation()).getPlot() == null) { - e.setCancelled(true); + event.setCancelled(true); return; } if (!BukkitUtil.getLocation(igniter.getLocation()).getPlot().equals(plot)) { - e.setCancelled(true); + event.setCancelled(true); return; } } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onTeleport(final PlayerTeleportEvent event) { + public void onTeleport(PlayerTeleportEvent event) { if (event.getTo() == null || event.getFrom() == null) { BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location"); BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot"); return; } - final org.bukkit.Location from = event.getFrom(); - final org.bukkit.Location to = event.getTo(); + org.bukkit.Location from = event.getFrom(); + org.bukkit.Location to = event.getTo(); int x2; if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); Location loc = BukkitUtil.getLocation(to); pp.setMeta("location", loc); PlotArea area = loc.getPlotArea(); @@ -1585,20 +1567,20 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } Plot now = area.getPlotAbs(loc); - final Plot lastPlot = pp.getMeta("lastplot"); + Plot lastPlot = pp.getMeta("lastplot"); if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmp_teleport) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(from); - tmp_teleport = true; + this.tmp_teleport = true; } else { Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; + this.tmp_teleport = true; } } event.setCancelled(true); @@ -1606,37 +1588,37 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } else if (lastPlot != null && now.equals(lastPlot)) { return; - } else if (!plotEntry(pp, now) && tmp_teleport) { + } else if (!plotEntry(pp, now) && this.tmp_teleport) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); if (!now.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(from); - tmp_teleport = true; + this.tmp_teleport = true; } else { Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; + this.tmp_teleport = true; } } event.setCancelled(true); return; } - final Integer border = area.getBorder(); - if (tmp_teleport) { + Integer border = area.getBorder(); + if (this.tmp_teleport) { if (x2 > border) { to.setX(border - 4); - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(event.getTo()); - tmp_teleport = true; + this.tmp_teleport = true; MainUtil.sendMessage(pp, C.BORDER); return; } else if (x2 < -border) { to.setX(-border + 4); - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(event.getTo()); - tmp_teleport = true; + this.tmp_teleport = true; MainUtil.sendMessage(pp, C.BORDER); return; } @@ -1645,30 +1627,30 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } int z2; if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); // Set last location Location loc = BukkitUtil.getLocation(to); pp.setMeta("location", loc); - final PlotArea area = loc.getPlotArea(); + PlotArea area = loc.getPlotArea(); if (area == null) { return; } Plot now = area.getPlotAbs(loc); - final Plot lastPlot = pp.getMeta("lastplot"); + Plot lastPlot = pp.getMeta("lastplot"); if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmp_teleport) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(from); - tmp_teleport = true; + this.tmp_teleport = true; } else { Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; + this.tmp_teleport = true; } } event.setCancelled(true); @@ -1676,53 +1658,53 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } else if (lastPlot != null && now.equals(lastPlot)) { return; - } else if (!plotEntry(pp, now) && tmp_teleport) { + } else if (!plotEntry(pp, now) && this.tmp_teleport) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); if (!now.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(from); - tmp_teleport = true; + this.tmp_teleport = true; } else { Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; + this.tmp_teleport = true; } } event.setCancelled(true); return; } - final Integer border = area.getBorder(); - if (tmp_teleport) { + Integer border = area.getBorder(); + if (this.tmp_teleport) { if (z2 > border) { to.setZ(border - 4); - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(event.getTo()); - tmp_teleport = true; + this.tmp_teleport = true; MainUtil.sendMessage(pp, C.BORDER); } else if (z2 < -border) { to.setZ(-border + 4); - tmp_teleport = false; + this.tmp_teleport = false; player.teleport(event.getTo()); - tmp_teleport = true; + this.tmp_teleport = true; MainUtil.sendMessage(pp, C.BORDER); } } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketEmpty(final PlayerBucketEmptyEvent e) { - final BlockFace bf = e.getBlockFace(); - final Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onBucketEmpty(PlayerBucketEmptyEvent e) { + BlockFace bf = e.getBlockFace(); + Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); - final Plot plot = area.getPlotAbs(loc); + PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); + Plot plot = area.getPlotAbs(loc); if (plot == null) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { return; @@ -1736,7 +1718,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); e.setCancelled(true); } else if (!plot.isAdded(pp.getUUID())) { - final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); + Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) { return; } @@ -1747,16 +1729,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(final InventoryClickEvent event) { - final HumanEntity clicker = event.getWhoClicked(); + public void onInventoryClick(InventoryClickEvent event) { + HumanEntity clicker = event.getWhoClicked(); if (!(clicker instanceof Player)) { return; } - final Player player = (Player) clicker; - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final PlotInventory inv = pp.getMeta("inventory"); + Player player = (Player) clicker; + PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotInventory inv = pp.getMeta("inventory"); if (inv != null && event.getRawSlot() == event.getSlot()) { if (!inv.onClick(event.getSlot())) { event.setCancelled(true); @@ -1764,76 +1746,70 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClose(final InventoryCloseEvent event) { - final HumanEntity closer = event.getPlayer(); + public void onInventoryClose(InventoryCloseEvent event) { + HumanEntity closer = event.getPlayer(); if (!(closer instanceof Player)) { return; } - final Player player = (Player) closer; + Player player = (Player) closer; BukkitUtil.getPlayer(player).deleteMeta("inventory"); } - + @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(final PlayerQuitEvent event) { - final PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); + public void onLeave(PlayerQuitEvent event) { + PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); pp.unregister(); } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketFill(final PlayerBucketFillEvent e) { - final Block b = e.getBlockClicked(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onBucketFill(PlayerBucketFillEvent e) { + Block b = e.getBlockClicked(); + Location loc = BukkitUtil.getLocation(b.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(loc); + Player p = e.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlotAbs(loc); if (plot == null) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { return; } MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); e.setCancelled(true); - } else { - if (!plot.hasOwner()) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - e.setCancelled(true); - } else if (!plot.isAdded(pp.getUUID())) { - final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); - final Block block = e.getBlockClicked(); - if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { - return; - } - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); + } else if (!plot.hasOwner()) { + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + return; } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + e.setCancelled(true); + } else if (!plot.isAdded(pp.getUUID())) { + Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); + Block block = e.getBlockClicked(); + if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + return; + } + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleCreate(final VehicleCreateEvent event) { - final Vehicle entity = event.getVehicle(); - final Location loc = BukkitUtil.getLocation(entity); + public void onVehicleCreate(VehicleCreateEvent event) { + Vehicle entity = event.getVehicle(); + Location loc = BukkitUtil.getLocation(entity); PlotArea area = loc.getPlotArea(); if (area == null) { return; } Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - entity.remove(); - return; - } - if (checkEntity(entity, plot)) { + if (plot == null || checkEntity(entity, plot)) { entity.remove(); return; } @@ -1841,18 +1817,18 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingPlace(final HangingPlaceEvent e) { - final Block b = e.getBlock().getRelative(e.getBlockFace()); - final Location loc = BukkitUtil.getLocation(b.getLocation()); + public void onHangingPlace(HangingPlaceEvent e) { + Block b = e.getBlock().getRelative(e.getBlockFace()); + Location loc = BukkitUtil.getLocation(b.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(loc); + Player p = e.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlotAbs(loc); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); @@ -1880,51 +1856,49 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { - final Entity r = e.getRemover(); + public void onHangingBreakByEntity(HangingBreakByEntityEvent e) { + Entity r = e.getRemover(); if (r instanceof Player) { - final Player p = (Player) r; - final Location l = BukkitUtil.getLocation(e.getEntity()); + Player p = (Player) r; + Location l = BukkitUtil.getLocation(e.getEntity()); PlotArea area = l.getPlotArea(); if (area == null) { return; } - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(l); + PlotPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlotAbs(l); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); e.setCancelled(true); } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); - e.setCancelled(true); - } - } else if (!plot.isAdded(pp.getUUID())) { - if (FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_BREAK.s())) { - return; - } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); - e.setCancelled(true); - } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + e.setCancelled(true); + } + } else if (!plot.isAdded(pp.getUUID())) { + if (FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_BREAK.s())) { + return; + } + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + e.setCancelled(true); } } } else if (r instanceof Projectile) { - final Projectile p = (Projectile) r; + Projectile p = (Projectile) r; if (p.getShooter() instanceof Player) { - final Player shooter = (Player) p.getShooter(); + Player shooter = (Player) p.getShooter(); Location loc = BukkitUtil.getLocation(e.getEntity()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final PlotPlayer player = BukkitUtil.getPlayer(shooter); - final Plot plot = area.getPlotAbs(BukkitUtil.getLocation(e.getEntity())); + PlotPlayer player = BukkitUtil.getPlayer(shooter); + Plot plot = area.getPlotAbs(BukkitUtil.getLocation(e.getEntity())); if (plot != null) { if (!plot.hasOwner()) { if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { @@ -1945,65 +1919,63 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen e.setCancelled(true); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { - final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + public void onPlayerInteractEntity(PlayerInteractEntityEvent e) { + Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); PlotArea area = l.getPlotArea(); if (area == null) { return; } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(l); + Player p = e.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlotAbs(l); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_ROAD); e.setCancelled(true); } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); - e.setCancelled(true); - } - } else if (!plot.isAdded(pp.getUUID())) { - final Entity entity = e.getRightClicked(); - if (entity instanceof Monster && FlagManager.isPlotFlagTrue(plot, C.FLAG_HOSTILE_INTERACT.s())) { - return; - } - if (entity instanceof Animals && FlagManager.isPlotFlagTrue(plot, C.FLAG_ANIMAL_INTERACT.s())) { - return; - } - if (entity instanceof Tameable && ((Tameable) entity).isTamed() && FlagManager.isPlotFlagTrue(plot, C.FLAG_TAMED_INTERACT.s())) { - return; - } - if (entity instanceof Vehicle && FlagManager.isPlotFlagTrue(plot, C.FLAG_VEHICLE_USE.s())) { - return; - } - if (entity instanceof Player && FlagManager.isPlotFlagTrue(plot, C.FLAG_PLAYER_INTERACT.s())) { - return; - } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER); - e.setCancelled(true); - } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); + e.setCancelled(true); + } + } else if (!plot.isAdded(pp.getUUID())) { + Entity entity = e.getRightClicked(); + if (entity instanceof Monster && FlagManager.isPlotFlagTrue(plot, C.FLAG_HOSTILE_INTERACT.s())) { + return; + } + if (entity instanceof Animals && FlagManager.isPlotFlagTrue(plot, C.FLAG_ANIMAL_INTERACT.s())) { + return; + } + if (entity instanceof Tameable && ((Tameable) entity).isTamed() && FlagManager.isPlotFlagTrue(plot, C.FLAG_TAMED_INTERACT.s())) { + return; + } + if (entity instanceof Vehicle && FlagManager.isPlotFlagTrue(plot, C.FLAG_VEHICLE_USE.s())) { + return; + } + if (entity instanceof Player && FlagManager.isPlotFlagTrue(plot, C.FLAG_PLAYER_INTERACT.s())) { + return; + } + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER); + e.setCancelled(true); } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleDestroy(final VehicleDestroyEvent e) { - final Location l = BukkitUtil.getLocation(e.getVehicle()); + public void onVehicleDestroy(VehicleDestroyEvent e) { + Location l = BukkitUtil.getLocation(e.getVehicle()); PlotArea area = l.getPlotArea(); if (area == null) { return; } - final Entity d = e.getAttacker(); + Entity d = e.getAttacker(); if (d instanceof Player) { - final Player p = (Player) d; - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(l); + Player p = (Player) d; + PlotPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlotAbs(l); if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); @@ -2030,46 +2002,46 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(final PotionSplashEvent event) { - final ThrownPotion damager = event.getPotion(); - final Location l = BukkitUtil.getLocation(damager); + public void onPotionSplash(PotionSplashEvent event) { + ThrownPotion damager = event.getPotion(); + Location l = BukkitUtil.getLocation(damager); if (!PS.get().hasPlotArea(l.getWorld())) { return; } - for (final LivingEntity victim : event.getAffectedEntities()) { - if (!entityDamage(l, damager, victim)) { + for (LivingEntity victim : event.getAffectedEntities()) { + if (!entityDamage(damager, victim)) { event.setIntensity(victim, 0); } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { - final Entity damager = e.getDamager(); - final Location l = BukkitUtil.getLocation(damager); + public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent e) { + Entity damager = e.getDamager(); + Location l = BukkitUtil.getLocation(damager); if (!PS.get().hasPlotArea(l.getWorld())) { return; } - final Entity victim = e.getEntity(); - if (!entityDamage(l, damager, victim)) { + Entity victim = e.getEntity(); + if (!entityDamage(damager, victim)) { e.setCancelled(true); } } - - public boolean entityDamage(final Location l, final Entity damager, final Entity victim) { - final Location dloc = BukkitUtil.getLocation(damager); - final Location vloc = BukkitUtil.getLocation(victim); + + public boolean entityDamage(Entity damager, Entity victim) { + Location dloc = BukkitUtil.getLocation(damager); + Location vloc = BukkitUtil.getLocation(victim); PlotArea dArea = dloc.getPlotArea(); PlotArea vArea = dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); if (dArea == null && vArea == null) { return true; } - final Plot dplot = dArea != null ? dArea.getPlot(dloc) : null; - final Plot vplot = vArea != null ? vArea.getPlot(vloc) : null; - + Plot dplot = dArea != null ? dArea.getPlot(dloc) : null; + Plot vplot = vArea != null ? vArea.getPlot(vloc) : null; + Plot plot; String stub; if (dplot == null && vplot == null) { @@ -2080,17 +2052,40 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen stub = "road"; } else { // Priorize plots for close to seamless pvp zones - plot = vplot == null ? dplot : dplot == null || !(victim instanceof Player) ? vplot : - victim.getTicksLived() > damager.getTicksLived() ? dplot : vplot; - stub = plot.hasOwner() ? "other" : "unowned"; + if (victim.getTicksLived() > damager.getTicksLived()) { + if (dplot == null || !(victim instanceof Player)) { + if (vplot == null) { + plot = dplot; + } else { + plot = vplot; + } + } else { + plot = dplot; + } + } else if (dplot == null || !(victim instanceof Player)) { + if (vplot == null) { + plot = dplot; + } else { + plot = vplot; + } + } else if (vplot == null) { + plot = dplot; + } else { + plot = vplot; + } + if (plot.hasOwner()) { + stub = "other"; + } else { + stub = "unowned"; + } } - + Player player; if (damager instanceof Player) { // attacker is player player = (Player) damager; } else if (damager instanceof Projectile) { - final Projectile projectile = (Projectile) damager; - final ProjectileSource shooter = projectile.getShooter(); + Projectile projectile = (Projectile) damager; + ProjectileSource shooter = projectile.getShooter(); if (shooter instanceof Player) { // shooter is player player = (Player) shooter; } else { // shooter is not player @@ -2100,7 +2095,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen player = null; } if (player != null) { - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotPlayer pp = BukkitUtil.getPlayer(player); if (victim instanceof Hanging) { // hanging if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hanging-break") || plot.isAdded(pp.getUUID()))) { return true; @@ -2137,16 +2132,12 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } else if (victim instanceof Player) { if (plot != null) { - final Flag pvp = FlagManager.getPlotFlagRaw(plot, C.FLAG_PVP.s()); - if (pvp == null) { + Flag pvp = FlagManager.getPlotFlagRaw(plot, C.FLAG_PVP.s()); + if (pvp == null || (Boolean) pvp.getValue()) { return true; - } else { - if ((Boolean) pvp.getValue()) { - return true; - } else if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); - return false; - } + } else if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + return false; } } if (!Permissions.hasPermission(pp, "plots.admin.pvp." + stub)) { @@ -2178,47 +2169,45 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen // player is null return !(damager instanceof Arrow && !(victim instanceof Creature)); } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerEggThrow(final PlayerEggThrowEvent e) { - final Location l = BukkitUtil.getLocation(e.getEgg().getLocation()); + public void onPlayerEggThrow(PlayerEggThrowEvent e) { + Location l = BukkitUtil.getLocation(e.getEgg().getLocation()); PlotArea area = l.getPlotArea(); if (area == null) { return; } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlot(l); + Player p = e.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlot(l); if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.projectile.road")) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); e.setHatching(false); } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.projectile.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); - e.setHatching(false); - } - } else if (!plot.isAdded(pp.getUUID())) { - if (!Permissions.hasPermission(pp, "plots.admin.projectile.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); - e.setHatching(false); - } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.projectile.unowned")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); + e.setHatching(false); + } + } else if (!plot.isAdded(pp.getUUID())) { + if (!Permissions.hasPermission(pp, "plots.admin.projectile.other")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); + e.setHatching(false); } } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void BlockCreate(final BlockPlaceEvent event) { - final Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); + public void blockCreate(BlockPlaceEvent event) { + Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { return; } - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = area.getPlotAbs(loc); + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = area.getPlotAbs(loc); if (plot != null) { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { @@ -2227,10 +2216,10 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } } else if (!plot.isAdded(pp.getUUID())) { - final Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s()); - final Block block = event.getBlock(); + Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s()); + Block block = event.getBlock(); if ((place == null || !((HashSet) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) - && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; @@ -2243,7 +2232,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } if (FlagManager.isPlotFlagTrue(plot, C.FLAG_DISABLE_PHYSICS.s())) { - final Block block = event.getBlockPlaced(); + Block block = event.getBlockPlaced(); if (block.getType().hasGravity()) { sendBlockChange(block.getLocation(), block.getType(), block.getData()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents183.java similarity index 79% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents183.java index 23fa3e7a9..7739678aa 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents183.java @@ -14,18 +14,18 @@ import org.bukkit.event.block.BlockExplodeEvent; import java.util.Iterator; -public class PlayerEvents_1_8_3 implements Listener { +public class PlayerEvents183 implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(final BlockExplodeEvent event) { - final Block block = event.getBlock(); + public void onBigBoom(BlockExplodeEvent event) { + Block block = event.getBlock(); Location loc = BukkitUtil.getLocation(block.getLocation()); - final String world = loc.getWorld(); + String world = loc.getWorld(); if (!PS.get().hasPlotArea(world)) { return; } PlotArea area = loc.getPlotArea(); if (area == null) { - final Iterator iter = event.blockList().iterator(); + Iterator iter = event.blockList().iterator(); while (iter.hasNext()) { loc = BukkitUtil.getLocation(iter.next().getLocation()); if (loc.getPlotArea() != null) { @@ -38,9 +38,9 @@ public class PlayerEvents_1_8_3 implements Listener { if (plot == null || !FlagManager.isPlotFlagTrue(plot, "explosion")) { event.setCancelled(true); } - final Iterator iter = event.blockList().iterator(); + Iterator iter = event.blockList().iterator(); while (iter.hasNext()) { - final Block b = iter.next(); + Block b = iter.next(); if (!plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(b.getLocation())))) { iter.remove(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java index bd18e1a24..02719dd32 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java @@ -1,9 +1,15 @@ package com.plotsquared.bukkit.listeners; -import java.util.HashSet; -import java.util.List; -import java.util.UUID; - +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.listener.PlotListener; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.ArmorStand; @@ -20,48 +26,41 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.listener.PlotListener; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; public class PlayerEvents_1_8 extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onInventoryClick(final InventoryClickEvent event) { + public void onInventoryClick(InventoryClickEvent event) { if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) { return; } - final HumanEntity entity = event.getWhoClicked(); + HumanEntity entity = event.getWhoClicked(); if (!(entity instanceof Player) || !PS.get().hasPlotArea(entity.getWorld().getName())) { return; } - final Player player = (Player) entity; - final PlayerInventory inv = player.getInventory(); - final int slot = inv.getHeldItemSlot(); + Player player = (Player) entity; + PlayerInventory inv = player.getInventory(); + int slot = inv.getHeldItemSlot(); if ((slot != event.getSlot()) || (slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { return; } - final ItemStack current = inv.getItemInHand(); - final ItemStack newItem = event.getCursor(); - final ItemMeta newMeta = newItem.getItemMeta(); - final ItemMeta oldMeta = newItem.getItemMeta(); + ItemStack current = inv.getItemInHand(); + ItemStack newItem = event.getCursor(); + ItemMeta newMeta = newItem.getItemMeta(); + ItemMeta oldMeta = newItem.getItemMeta(); String newLore = ""; if (newMeta != null) { - final List lore = newMeta.getLore(); + List lore = newMeta.getLore(); if (lore != null) { newLore = lore.toString(); } } String oldLore = ""; if (oldMeta != null) { - final List lore = oldMeta.getLore(); + List lore = oldMeta.getLore(); if (lore != null) { oldLore = lore.toString(); } @@ -69,86 +68,82 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener { if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) { return; } - final HashSet blocks = null; - final Block block = player.getTargetBlock(blocks, 7); - final BlockState state = block.getState(); + HashSet blocks = null; + Block block = player.getTargetBlock(blocks, 7); + BlockState state = block.getState(); if (state == null) { return; } if (state.getType() != newItem.getType()) { return; } - final Location l = BukkitUtil.getLocation(state.getLocation()); + Location l = BukkitUtil.getLocation(state.getLocation()); PlotArea area = l.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getPlotAbs(l); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = area.getPlotAbs(l); + PlotPlayer pp = BukkitUtil.getPlayer(player); boolean cancelled = false; if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road"); cancelled = true; } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + cancelled = true; + } } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid)) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other"); cancelled = true; } - } else { - final UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid)) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other"); - cancelled = true; - } - } } } if (cancelled) { - if ((current.getTypeId() == newItem.getTypeId()) && (current.getDurability() == newItem.getDurability())) { - event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability())); + if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem.getDurability())) { + event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); event.setCancelled(true); return; } - event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability())); + event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onInteract(final PlayerInteractAtEntityEvent e) { - final Entity entity = e.getRightClicked(); + public void onInteract(PlayerInteractAtEntityEvent e) { + Entity entity = e.getRightClicked(); if (!(entity instanceof ArmorStand)) { return; } - final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); - final PlotArea area = l.getPlotArea(); + Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + PlotArea area = l.getPlotArea(); if (area == null) { return; } - final Plot plot = area.getPlotAbs(l); - final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); + Plot plot = area.getPlotAbs(l); + PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road"); e.setCancelled(true); } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + e.setCancelled(true); + } } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid)) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other"); e.setCancelled(true); } - } else { - final UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid)) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other"); - e.setCancelled(true); - } - } } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java index 07ae581ca..8a87bb6a8 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -45,40 +45,33 @@ import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; -import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map.Entry; import java.util.UUID; -/** - * Created 2014-10-30 for PlotSquared - * - - */ -@SuppressWarnings("deprecation") public class PlotPlusListener extends PlotListener implements Listener { - private final static HashMap feedRunnable = new HashMap<>(); - private final static HashMap healRunnable = new HashMap<>(); - - public static void startRunnable(final JavaPlugin plugin) { + + private static final HashMap feedRunnable = new HashMap<>(); + private static final HashMap healRunnable = new HashMap<>(); + + public static void startRunnable(JavaPlugin plugin) { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { @Override public void run() { if (!healRunnable.isEmpty()) { - for (final Iterator> iter = healRunnable.entrySet().iterator(); iter.hasNext();) { - final Entry entry = iter.next(); - final Interval value = entry.getValue(); + for (Iterator> iter = healRunnable.entrySet().iterator(); iter.hasNext(); ) { + Entry entry = iter.next(); + Interval value = entry.getValue(); ++value.count; if (value.count == value.interval) { value.count = 0; - final Player player = Bukkit.getPlayer(entry.getKey()); + Player player = Bukkit.getPlayer(entry.getKey()); if (player == null) { iter.remove(); continue; } - final double level = player.getHealth(); + double level = player.getHealth(); if (level != value.max) { player.setHealth(Math.min(level + value.amount, value.max)); } @@ -86,18 +79,18 @@ public class PlotPlusListener extends PlotListener implements Listener { } } if (!feedRunnable.isEmpty()) { - for (final Iterator> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) { - final Entry entry = iter.next(); - final Interval value = entry.getValue(); + for (Iterator> iter = feedRunnable.entrySet().iterator(); iter.hasNext(); ) { + Entry entry = iter.next(); + Interval value = entry.getValue(); ++value.count; if (value.count == value.interval) { value.count = 0; - final Player player = Bukkit.getPlayer(entry.getKey()); + Player player = Bukkit.getPlayer(entry.getKey()); if (player == null) { iter.remove(); continue; } - final int level = player.getFoodLevel(); + int level = player.getFoodLevel(); if (level != value.max) { player.setFoodLevel(Math.min(level + value.amount, value.max)); } @@ -105,17 +98,17 @@ public class PlotPlusListener extends PlotListener implements Listener { } } } - }, 0l, 20l); + }, 0L, 20L); } @EventHandler(priority = EventPriority.HIGH) - public void onMelt(final BlockFadeEvent event) { - final BlockState state = event.getNewState(); + public void onMelt(BlockFadeEvent event) { + BlockState state = event.getNewState(); if (state.getType() != Material.WATER && state.getType() != Material.STATIONARY_WATER) { return; } - final Plot plot = BukkitUtil.getLocation(state.getLocation()).getOwnedPlot(); + Plot plot = BukkitUtil.getLocation(state.getLocation()).getOwnedPlot(); if (plot == null) { return; } @@ -128,12 +121,12 @@ public class PlotPlusListener extends PlotListener implements Listener { } @EventHandler(priority = EventPriority.HIGH) - public void onInteract(final BlockDamageEvent event) { - final Player player = event.getPlayer(); + public void onInteract(BlockDamageEvent event) { + Player player = event.getPlayer(); if (player.getGameMode() != GameMode.SURVIVAL) { return; } - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); if (plot == null) { return; } @@ -143,12 +136,12 @@ public class PlotPlusListener extends PlotListener implements Listener { } @EventHandler(priority = EventPriority.HIGH) - public void onDamage(final EntityDamageEvent event) { + public void onDamage(EntityDamageEvent event) { if (event.getEntityType() != EntityType.PLAYER) { return; } - final Player player = (Player) event.getEntity(); - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + Player player = (Player) event.getEntity(); + Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); if (plot == null) { return; } @@ -158,115 +151,82 @@ public class PlotPlusListener extends PlotListener implements Listener { } @EventHandler - public void onItemPickup(final PlayerPickupItemEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + public void onItemPickup(PlayerPickupItemEvent event) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); if (plot == null) { return; } - final UUID uuid = pp.getUUID(); + UUID uuid = pp.getUUID(); if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) { event.setCancelled(true); } } @EventHandler - public void onItemDrop(final PlayerDropItemEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + public void onItemDrop(PlayerDropItemEvent event) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); if (plot == null) { return; } - final UUID uuid = pp.getUUID(); + UUID uuid = pp.getUUID(); if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) { event.setCancelled(true); } } @EventHandler - public void onPlotEnter(final PlayerEnterPlotEvent event) { - final Player player = event.getPlayer(); - final Plot plot = event.getPlot(); - final Flag feed = FlagManager.getPlotFlagRaw(plot, "feed"); + public void onPlotEnter(PlayerEnterPlotEvent event) { + Player player = event.getPlayer(); + Plot plot = event.getPlot(); + Flag feed = FlagManager.getPlotFlagRaw(plot, "feed"); if (feed != null) { - final Integer[] value = (Integer[]) feed.getValue(); + Integer[] value = (Integer[]) feed.getValue(); feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); } - final Flag heal = FlagManager.getPlotFlagRaw(plot, "heal"); + Flag heal = FlagManager.getPlotFlagRaw(plot, "heal"); if (heal != null) { - final Integer[] value = (Integer[]) heal.getValue(); + Integer[] value = (Integer[]) heal.getValue(); healRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); } } @EventHandler - public void onPlayerQuit(final PlayerQuitEvent event) { - final Player player = event.getPlayer(); - final String name = player.getName(); + public void onPlayerQuit(PlayerQuitEvent event) { + Player player = event.getPlayer(); + String name = player.getName(); feedRunnable.remove(name); healRunnable.remove(name); } @EventHandler - public void onPlotLeave(final PlayerLeavePlotEvent event) { - final Player leaver = event.getPlayer(); - final Plot plot = event.getPlot(); + public void onPlotLeave(PlayerLeavePlotEvent event) { + Player leaver = event.getPlayer(); + Plot plot = event.getPlot(); if (!plot.hasOwner()) { return; } BukkitUtil.getPlayer(leaver); - final String name = leaver.getName(); + String name = leaver.getName(); feedRunnable.remove(name); healRunnable.remove(name); } - - public static class Interval { - public final int interval; - public final int amount; - public final int max; + + private static class Interval { + + final int interval; + final int amount; + final int max; public int count = 0; - - public Interval(final int interval, final int amount, final int max) { + + Interval(int interval, int amount, int max) { this.interval = interval; this.amount = amount; this.max = max; } } - - /** - * Record Meta Class - * - */ - public static class RecordMeta { - public final static List metaList = new ArrayList<>(); - static { - for (int x = 3; x < 12; x++) { - metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x))); - } - } - private final String name; - private final Material material; - - public RecordMeta(final String name, final Material material) { - this.name = name; - this.material = material; - } - - @Override - public String toString() { - return name; - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - public Material getMaterial() { - return material; - } - } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java index 5c5305ff0..49ce15eb9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java @@ -1,5 +1,8 @@ package com.plotsquared.bukkit.listeners; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.generator.GeneratorWrapper; +import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import org.bukkit.World; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -7,17 +10,13 @@ import org.bukkit.event.Listener; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.generator.ChunkGenerator; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.plotsquared.bukkit.generator.BukkitPlotGenerator; - public class WorldEvents implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onWorldInit(final WorldInitEvent event) { - final World world = event.getWorld(); - final String name = world.getName(); - final ChunkGenerator gen = world.getGenerator(); + public void onWorldInit(WorldInitEvent event) { + World world = event.getWorld(); + String name = world.getName(); + ChunkGenerator gen = world.getGenerator(); if (gen instanceof GeneratorWrapper) { PS.get().loadWorld(name, (GeneratorWrapper) gen); } else { 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 664519869..0e1797ff2 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 @@ -1,19 +1,5 @@ package com.plotsquared.bukkit.listeners.worldedit; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -29,6 +15,18 @@ import com.plotsquared.listener.WEManager; import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.selections.Selection; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; public class WEListener implements Listener { @@ -43,21 +41,10 @@ public class WEListener implements Listener { 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 unregioned = new HashSet<>(Arrays.asList("paste", "redo", "undo", "rotate", "flip", "generate", "schematic", "schem")); - public final HashSet unsafe1 = new HashSet<>(Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks")); public final HashSet restricted = new HashSet<>(Collections.singletonList("up")); public final HashSet other = new HashSet<>(Arrays.asList("undo", "redo")); - - public boolean checkCommand(final List list, final String cmd) { - for (final String identifier : list) { - if (("/" + identifier).equals(cmd) || ("//" + identifier).equals(cmd) || ("/worldedit:/" + identifier).equals(cmd) || ("/worldedit:" + identifier).equals(cmd)) { - return true; - } - } - return false; - } - - public String reduceCmd(final String cmd, final boolean single) { + + public String reduceCmd(String cmd, boolean single) { if (cmd.startsWith("/worldedit:/")) { return cmd.substring(12); } @@ -72,24 +59,24 @@ public class WEListener implements Listener { } return cmd; } - - public int getInt(final String s) { + + public int getInt(String s) { try { int max = 0; - final String[] split = s.split(","); - for (final String rad : split) { - final int val = Integer.parseInt(rad); + String[] split = s.split(","); + for (String rad : split) { + int val = Integer.parseInt(rad); if (val > max) { max = val; } } return max; - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { return 0; } } - - public boolean checkVolume(final PlotPlayer player, final long volume, final long max, final Cancellable e) { + + public boolean checkVolume(PlotPlayer player, long volume, long max, Cancellable e) { if (volume > max) { MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", volume + "").replaceAll("%max%", max + "")); e.setCancelled(true); @@ -99,16 +86,16 @@ public class WEListener implements Listener { } return true; } - - public boolean checkSelection(final Player p, final PlotPlayer pp, final int modifier, final long max, final Cancellable e) { - final Selection selection = BukkitMain.worldEdit.getSelection(p); + + public boolean checkSelection(Player p, PlotPlayer pp, int modifier, long max, Cancellable e) { + Selection selection = BukkitMain.worldEdit.getSelection(p); if (selection == null) { return true; } - final BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector(); - final BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector(); - final HashSet mask = WEManager.getMask(pp); - final RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ()); + BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector(); + BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector(); + HashSet mask = WEManager.getMask(pp); + RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ()); if (Settings.REQUIRE_SELECTION) { String arg = null; if (!WEManager.regionContains(region, mask)) { @@ -135,15 +122,16 @@ public class WEListener implements Listener { return true; } } - final long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ())) * modifier; + long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ())) + * modifier; return checkVolume(pp, volume, max, e); } - public boolean delay(final Player player, final String command, final boolean delayed) { + public boolean delay(final Player player, final String command, boolean delayed) { if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) { return false; } - final boolean free = SetQueue.IMP.addTask(null); + boolean free = SetQueue.IMP.addTask(null); if (free) { if (delayed) { MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command); @@ -166,80 +154,80 @@ public class WEListener implements Listener { } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public boolean onPlayerCommand(final PlayerCommandPreprocessEvent e) { - final WorldEditPlugin worldedit = BukkitMain.worldEdit; + public boolean onPlayerCommand(PlayerCommandPreprocessEvent e) { + WorldEditPlugin worldedit = BukkitMain.worldEdit; if (worldedit == null) { HandlerList.unregisterAll(this); return true; } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); + Player p = e.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(p); if (!PS.get().hasPlotArea(p.getWorld().getName())) { return true; } - final String message = e.getMessage(); - final String cmd = message.toLowerCase(); - final boolean single = true; - final String[] split = cmd.split(" "); - - final long maxVolume = Settings.WE_MAX_VOLUME; - final long maxIterations = Settings.WE_MAX_ITERATIONS; + String message = e.getMessage(); + String cmd = message.toLowerCase(); + String[] split = cmd.split(" "); + + long maxVolume = Settings.WE_MAX_VOLUME; + long maxIterations = Settings.WE_MAX_ITERATIONS; if (pp.getAttribute("worldedit")) { return true; } + boolean single = true; if (split.length >= 2) { - final String reduced = reduceCmd(split[0], single); - final String reduced2 = reduceCmd(split[0] + " " + split[1], single); - if (rad1.contains(reduced)) { + String reduced = reduceCmd(split[0], single); + String reduced2 = reduceCmd(split[0] + " " + split[1], single); + if (this.rad1.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; } - final long volume = getInt(split[1]) * 256; + long volume = getInt(split[1]) * 256; return checkVolume(pp, volume, maxVolume, e); } - if (rad2.contains(reduced)) { + if (this.rad2.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; } if (split.length >= 3) { - final long volume = getInt(split[2]) * 256; + long volume = getInt(split[2]) * 256; return checkVolume(pp, volume, maxVolume, e); } return true; } - if (rad2_1.contains(reduced)) { + if (this.rad2_1.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; } if (split.length >= 4) { - final long volume = getInt(split[2]) * getInt(split[3]); + long volume = getInt(split[2]) * getInt(split[3]); return checkVolume(pp, volume, maxVolume, e); } return true; } - if (rad2_2.contains(reduced)) { + if (this.rad2_2.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; } if (split.length >= 3) { - final long radius = getInt(split[2]); - final long volume = radius * radius; + long radius = getInt(split[2]); + long volume = radius * radius; return checkVolume(pp, volume, maxVolume, e); } return true; } - if (rad2_3.contains(reduced2)) { + if (this.rad2_3.contains(reduced2)) { if (delay(p, message, false)) { e.setCancelled(true); return true; } if (split.length >= 3) { if (split.length == 4) { - final int iterations = getInt(split[3]); + int iterations = getInt(split[3]); if (iterations > maxIterations) { MainUtil.sendMessage(pp, C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + "")); e.setCancelled(true); @@ -249,13 +237,13 @@ public class WEListener implements Listener { return true; } } - final long radius = getInt(split[2]); - final long volume = radius * radius; + long radius = getInt(split[2]); + long volume = radius * radius; return checkVolume(pp, volume, maxVolume, e); } return true; } - if (rad3_1.contains(reduced2)) { + if (this.rad3_1.contains(reduced2)) { if (delay(p, message, false)) { e.setCancelled(true); return true; @@ -265,13 +253,13 @@ public class WEListener implements Listener { if (split[i].equalsIgnoreCase("-h")) { i = 3; } - final long radius = getInt(split[i]); - final long volume = radius * radius; + long radius = getInt(split[i]); + long volume = radius * radius; return checkVolume(pp, volume, maxVolume, e); } return true; } - if (rad3_2.contains(reduced2)) { + if (this.rad3_2.contains(reduced2)) { if (delay(p, message, false)) { e.setCancelled(true); return true; @@ -281,13 +269,13 @@ public class WEListener implements Listener { if (split[i].equalsIgnoreCase("-h")) { i = 4; } - final long radius = getInt(split[i]); - final long volume = radius * radius; + long radius = getInt(split[i]); + long volume = radius * radius; return checkVolume(pp, volume, maxVolume, e); } return true; } - if (regionExtend.contains(reduced)) { + if (this.regionExtend.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; @@ -295,7 +283,7 @@ public class WEListener implements Listener { return checkSelection(p, pp, getInt(split[1]), maxVolume, e); } } - final String reduced = reduceCmd(split[0], single); + String reduced = reduceCmd(split[0], single); if (Settings.WE_BLACKLIST.contains(reduced)) { MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE); e.setCancelled(true); @@ -303,8 +291,8 @@ public class WEListener implements Listener { MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS); } } - if (restricted.contains(reduced)) { - final Plot plot = pp.getCurrentPlot(); + if (this.restricted.contains(reduced)) { + Plot plot = pp.getCurrentPlot(); if ((plot != null) && plot.isAdded(pp.getUUID())) { if (delay(p, message, false)) { e.setCancelled(true); @@ -319,14 +307,14 @@ public class WEListener implements Listener { } return true; } - if (region.contains(reduced)) { + if (this.region.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; } return checkSelection(p, pp, 1, maxVolume, e); } - if (other.contains(reduced)) { + if (this.other.contains(reduced)) { if (delay(p, message, false)) { e.setCancelled(true); return true; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java index 99b226c78..6f4fa0cfc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java @@ -1,40 +1,39 @@ package com.plotsquared.bukkit.object; -import org.bukkit.block.Block; - import com.intellectualcrafters.plot.object.LazyBlock; import com.intellectualcrafters.plot.object.PlotBlock; +import org.bukkit.block.Block; public class BukkitLazyBlock extends LazyBlock { - + private int id; private Block block; private PlotBlock pb; - - public BukkitLazyBlock(final int id, final Block block) { + + public BukkitLazyBlock(int id, Block block) { this.id = id; this.block = block; } - - public BukkitLazyBlock(final PlotBlock pb) { - id = pb.id; + + public BukkitLazyBlock(PlotBlock pb) { + this.id = pb.id; this.pb = pb; } - - public BukkitLazyBlock(final Block block) { + + public BukkitLazyBlock(Block block) { this.block = block; } - + @Override public PlotBlock getPlotBlock() { - if (pb != null) { - return pb; + if (this.pb != null) { + return this.pb; } - if (id == 0) { - id = block.getTypeId(); + if (this.id == 0) { + this.id = this.block.getTypeId(); } byte data; - switch (id) { + switch (this.id) { case 0: case 2: case 4: @@ -120,20 +119,20 @@ public class BukkitLazyBlock extends LazyBlock { data = 0; break; default: - data = block.getData(); + data = this.block.getData(); break; } - pb = new PlotBlock((short) id, data); - return pb; - + this.pb = new PlotBlock((short) this.id, data); + return this.pb; + } - + @Override public int getId() { - if (id == 0) { - id = block.getTypeId(); + if (this.id == 0) { + this.id = this.block.getTypeId(); } - return id; + return this.id; } - + } 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 56f5e2ca4..3d3ad540d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java @@ -1,10 +1,9 @@ package com.plotsquared.bukkit.object; -import java.util.UUID; - +import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; +import java.util.UUID; public class BukkitOfflinePlayer implements OfflinePlotPlayer { @@ -14,27 +13,27 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects. * @param player */ - public BukkitOfflinePlayer(final OfflinePlayer player) { + public BukkitOfflinePlayer(OfflinePlayer player) { this.player = player; } @Override public UUID getUUID() { - return player.getUniqueId(); + return this.player.getUniqueId(); } @Override public long getLastPlayed() { - return player.getLastPlayed(); + return this.player.getLastPlayed(); } @Override public boolean isOnline() { - return player.isOnline(); + return this.player.isOnline(); } @Override public String getName() { - return player.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 b30d5a74c..d9ddf5761 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java @@ -4,7 +4,7 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.PlotGamemode; +import com.intellectualcrafters.plot.util.PlotGameMode; import com.intellectualcrafters.plot.util.PlotWeather; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.bukkit.util.BukkitUtil; @@ -31,12 +31,12 @@ public class BukkitPlayer extends PlotPlayer { * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects. * @param player */ - public BukkitPlayer(final Player player) { + public BukkitPlayer(Player player) { this.player = player; super.populatePersistentMetaMap(); } - - public BukkitPlayer(final Player player, final boolean offline) { + + public BukkitPlayer(Player player, boolean offline) { this.player = player; this.offline = offline; super.populatePersistentMetaMap(); @@ -44,45 +44,45 @@ public class BukkitPlayer extends PlotPlayer { @Override public long getPreviousLogin() { - if (last == 0) { - last = player.getLastPlayed(); + if (this.last == 0) { + this.last = this.player.getLastPlayed(); } - return last; + return this.last; } @Override public Location getLocation() { - final Location loc = super.getLocation(); - return loc == null ? BukkitUtil.getLocation(player) : loc; + Location location = super.getLocation(); + return location == null ? BukkitUtil.getLocation(this.player) : location; } @Override public UUID getUUID() { - if (uuid == null) { - uuid = UUIDHandler.getUUID(this); + if (this.uuid == null) { + this.uuid = UUIDHandler.getUUID(this); } - return uuid; + return this.uuid; } @Override - public boolean hasPermission(final String node) { - if (offline && EconHandler.manager != null) { - return EconHandler.manager.hasPermission(getName(), node); + public boolean hasPermission(String permission) { + if (this.offline && EconHandler.manager != null) { + return EconHandler.manager.hasPermission(getName(), permission); } - return player.hasPermission(node); + return this.player.hasPermission(permission); } - - public Permission getPermission(final String node) { - final PluginManager manager = Bukkit.getPluginManager(); + + public Permission getPermission(String node) { + PluginManager manager = Bukkit.getPluginManager(); Permission perm = manager.getPermission(node); if (perm == null) { - final String[] nodes = node.split("\\."); + String[] nodes = node.split("\\."); perm = new Permission(node); - final StringBuilder n = new StringBuilder(); + StringBuilder n = new StringBuilder(); for (int i = 0; i < nodes.length - 1; i++) { n.append(nodes[i]).append("."); if (!node.equals(n + C.PERMISSION_STAR.s())) { - final Permission parent = getPermission(n + C.PERMISSION_STAR.s()); + Permission parent = getPermission(n + C.PERMISSION_STAR.s()); if (parent != null) { perm.addParent(parent, true); } @@ -96,134 +96,125 @@ public class BukkitPlayer extends PlotPlayer { } @Override - public void sendMessage(final String message) { - player.sendMessage(message); + public void sendMessage(String message) { + this.player.sendMessage(message); } @Override - public void teleport(final Location loc) { - if (Math.abs(loc.getX()) >= 30000000 || Math.abs(loc.getZ()) >= 30000000) { + public void teleport(Location location) { + if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) { return; } - player.teleport(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX() + 0.5, loc.getY(), loc.getZ() + 0.5, loc.getYaw(), loc.getPitch()), TeleportCause.COMMAND); + this.player.teleport( + new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, location.getY(), location.getZ() + 0.5, + location.getYaw(), location.getPitch()), TeleportCause.COMMAND); } @Override public String getName() { - if (name == null) { - name = player.getName(); + if (this.name == null) { + this.name = this.player.getName(); } - return name; + return this.name; } @Override public boolean isOnline() { - return !offline && player.isOnline(); + return !this.offline && this.player.isOnline(); } @Override - public void setCompassTarget(final Location loc) { - player.setCompassTarget(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ())); + public void setCompassTarget(Location location) { + this.player.setCompassTarget( + new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ())); } @Override public Location getLocationFull() { - return BukkitUtil.getLocationFull(player); + return BukkitUtil.getLocationFull(this.player); } - + @Override - public void loadData() { - if (!player.isOnline()) { - player.loadData(); - } - } - - @Override - public void saveData() { - player.saveData(); - } - - @Override - public void setWeather(final PlotWeather weather) { + public void setWeather(PlotWeather weather) { switch (weather) { case CLEAR: - player.setPlayerWeather(WeatherType.CLEAR); + this.player.setPlayerWeather(WeatherType.CLEAR); return; case RAIN: - player.setPlayerWeather(WeatherType.DOWNFALL); + this.player.setPlayerWeather(WeatherType.DOWNFALL); return; case RESET: - player.resetPlayerWeather(); + this.player.resetPlayerWeather(); return; } } @Override - public PlotGamemode getGamemode() { - switch (player.getGameMode()) { + public PlotGameMode getGameMode() { + switch (this.player.getGameMode()) { case ADVENTURE: - return PlotGamemode.ADVENTURE; + return PlotGameMode.ADVENTURE; case CREATIVE: - return PlotGamemode.CREATIVE; + return PlotGameMode.CREATIVE; case SPECTATOR: - return PlotGamemode.SPECTATOR; + return PlotGameMode.SPECTATOR; case SURVIVAL: - return PlotGamemode.SURVIVAL; + return PlotGameMode.SURVIVAL; } return null; } @Override - public void setGamemode(final PlotGamemode gamemode) { - switch (gamemode) { + public void setGameMode(PlotGameMode gameMode) { + switch (gameMode) { case ADVENTURE: - player.setGameMode(GameMode.ADVENTURE); + this.player.setGameMode(GameMode.ADVENTURE); return; case CREATIVE: - player.setGameMode(GameMode.CREATIVE); + this.player.setGameMode(GameMode.CREATIVE); return; case SPECTATOR: - player.setGameMode(GameMode.SPECTATOR); + this.player.setGameMode(GameMode.SPECTATOR); return; case SURVIVAL: - player.setGameMode(GameMode.SURVIVAL); + this.player.setGameMode(GameMode.SURVIVAL); return; } } @Override - public void setTime(final long time) { + public void setTime(long time) { if (time != Long.MAX_VALUE) { - player.setPlayerTime(time, false); + this.player.setPlayerTime(time, false); } else { - player.resetPlayerTime(); + this.player.resetPlayerTime(); } } @Override - public void setFlight(final boolean fly) { - player.setAllowFlight(fly); + public void setFlight(boolean fly) { + this.player.setAllowFlight(fly); } @Override - public void playMusic(final Location loc, final int id) { - player.playEffect(BukkitUtil.getLocation(loc), Effect.RECORD_PLAY, id); + public void playMusic(Location location, int id) { + this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id); } @Override - public void kick(final String message) { - player.kickPlayer(message); + public void kick(String message) { + this.player.kickPlayer(message); } @Override public void stopSpectating() { - if (getGamemode() == PlotGamemode.SPECTATOR) { - player.setSpectatorTarget(null); + if (getGameMode() == PlotGameMode.SPECTATOR) { + this.player.setSpectatorTarget(null); } } @Override public boolean isBanned() { - return player.isBanned(); + return this.player.isBanned(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java index a06e4adc9..fcc878d6a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java @@ -56,31 +56,31 @@ public class EntityWrapper { private ArmorStandStats stand; @SuppressWarnings("deprecation") - public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) { - hash = entity.getEntityId(); + public EntityWrapper(org.bukkit.entity.Entity entity, short depth) { + this.hash = entity.getEntityId(); this.depth = depth; - final Location loc = entity.getLocation(); - yaw = loc.getYaw(); - pitch = loc.getPitch(); - x = loc.getX(); - y = loc.getY(); - z = loc.getZ(); - type = entity.getType(); + Location loc = entity.getLocation(); + this.yaw = loc.getYaw(); + this.pitch = loc.getPitch(); + this.x = loc.getX(); + this.y = loc.getY(); + this.z = loc.getZ(); + this.type = entity.getType(); if (depth == 0) { return; } - base = new EntityBaseStats(); - final Entity p = entity.getPassenger(); + this.base = new EntityBaseStats(); + Entity p = entity.getPassenger(); if (p != null) { - base.passenger = new EntityWrapper(p, depth); + this.base.passenger = new EntityWrapper(p, depth); } - base.fall = entity.getFallDistance(); - base.fire = (short) entity.getFireTicks(); - base.age = entity.getTicksLived(); - final Vector velocity = entity.getVelocity(); - base.v_x = velocity.getX(); - base.v_y = velocity.getY(); - base.v_z = velocity.getZ(); + this.base.fall = entity.getFallDistance(); + this.base.fire = (short) entity.getFireTicks(); + this.base.age = entity.getTicksLived(); + Vector velocity = entity.getVelocity(); + this.base.v_x = velocity.getX(); + this.base.v_y = velocity.getY(); + this.base.v_z = velocity.getZ(); if (depth == 1) { return; } @@ -123,31 +123,31 @@ public class EntityWrapper { } // MISC // case DROPPED_ITEM: { - final Item item = (Item) entity; - stack = item.getItemStack(); + Item item = (Item) entity; + this.stack = item.getItemStack(); return; } case ITEM_FRAME: { - final ItemFrame itemframe = (ItemFrame) entity; - x = Math.floor(x); - y = Math.floor(y); - z = Math.floor(z); - dataByte = getOrdinal(Rotation.values(), itemframe.getRotation()); - stack = itemframe.getItem().clone(); + ItemFrame itemframe = (ItemFrame) entity; + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.dataByte = getOrdinal(Rotation.values(), itemframe.getRotation()); + this.stack = itemframe.getItem().clone(); return; } case PAINTING: { - final Painting painting = (Painting) entity; - x = Math.floor(x); - y = Math.floor(y); - z = Math.floor(z); - final Art a = painting.getArt(); - dataByte = getOrdinal(BlockFace.values(), painting.getFacing()); - final int h = a.getBlockHeight(); + Painting painting = (Painting) entity; + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + Art a = painting.getArt(); + this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing()); + int h = a.getBlockHeight(); if ((h % 2) == 0) { - y -= 1; + this.y -= 1; } - dataString = a.name(); + this.dataString = a.name(); return; } // END MISC // @@ -161,7 +161,7 @@ public class EntityWrapper { // START AGEABLE // // START TAMEABLE // case HORSE: { - final Horse horse = (Horse) entity; + Horse horse = (Horse) entity; this.horse = new HorseStats(); this.horse.jump = horse.getJumpStrength(); this.horse.chest = horse.isCarryingChest(); @@ -184,9 +184,9 @@ public class EntityWrapper { } // END AMEABLE // case SHEEP: { - final Sheep sheep = (Sheep) entity; - dataByte = (byte) ((sheep).isSheared() ? 1 : 0); - dataByte2 = sheep.getColor().getDyeData(); + Sheep sheep = (Sheep) entity; + this.dataByte = (byte) (sheep.isSheared() ? 1 : 0); + this.dataByte2 = sheep.getColor().getDyeData(); storeAgeable((Ageable) entity); storeLiving((LivingEntity) entity); return; @@ -202,54 +202,55 @@ public class EntityWrapper { } // END AGEABLE // case RABBIT: { // NEW - dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType()); + this.dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType()); storeAgeable((Ageable) entity); storeLiving((LivingEntity) entity); return; } case GUARDIAN: { // NEW - dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0); + this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0); storeLiving((LivingEntity) entity); return; } case SKELETON: { // NEW - dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId(); + this.dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId(); storeLiving((LivingEntity) entity); return; } case ARMOR_STAND: { // NEW // CHECK positions - final ArmorStand stand = (ArmorStand) entity; - inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() }; + ArmorStand stand = (ArmorStand) entity; + this.inventory = new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), + stand.getLeggings().clone(), stand.getBoots().clone()}; storeLiving((LivingEntity) entity); this.stand = new ArmorStandStats(); - final EulerAngle head = stand.getHeadPose(); + EulerAngle head = stand.getHeadPose(); this.stand.head[0] = (float) head.getX(); this.stand.head[1] = (float) head.getY(); this.stand.head[2] = (float) head.getZ(); - final EulerAngle body = stand.getBodyPose(); + EulerAngle body = stand.getBodyPose(); this.stand.body[0] = (float) body.getX(); this.stand.body[1] = (float) body.getY(); this.stand.body[2] = (float) body.getZ(); - final EulerAngle leftLeg = stand.getLeftLegPose(); + EulerAngle leftLeg = stand.getLeftLegPose(); this.stand.leftLeg[0] = (float) leftLeg.getX(); this.stand.leftLeg[1] = (float) leftLeg.getY(); this.stand.leftLeg[2] = (float) leftLeg.getZ(); - final EulerAngle rightLeg = stand.getRightLegPose(); + EulerAngle rightLeg = stand.getRightLegPose(); this.stand.rightLeg[0] = (float) rightLeg.getX(); this.stand.rightLeg[1] = (float) rightLeg.getY(); this.stand.rightLeg[2] = (float) rightLeg.getZ(); - final EulerAngle leftArm = stand.getLeftArmPose(); + EulerAngle leftArm = stand.getLeftArmPose(); this.stand.leftArm[0] = (float) leftArm.getX(); this.stand.leftArm[1] = (float) leftArm.getY(); this.stand.leftArm[2] = (float) leftArm.getZ(); - final EulerAngle rightArm = stand.getRightArmPose(); + EulerAngle rightArm = stand.getRightArmPose(); this.stand.rightArm[0] = (float) rightArm.getX(); this.stand.rightArm[1] = (float) rightArm.getY(); this.stand.rightArm[2] = (float) rightArm.getZ(); @@ -298,39 +299,39 @@ public class EntityWrapper { } @Override - public boolean equals(final Object obj) { - return hash == obj.hashCode(); + public boolean equals(Object obj) { + return this.hash == obj.hashCode(); } @Override public int hashCode() { - return hash; + return this.hash; } - public void storeInventory(final InventoryHolder held) { - inventory = held.getInventory().getContents().clone(); + public void storeInventory(InventoryHolder held) { + this.inventory = held.getInventory().getContents().clone(); } - private void restoreLiving(final LivingEntity entity) { - entity.setCanPickupItems(lived.loot); - if (lived.name != null) { - entity.setCustomName(lived.name); - entity.setCustomNameVisible(lived.visible); + private void restoreLiving(LivingEntity entity) { + entity.setCanPickupItems(this.lived.loot); + if (this.lived.name != null) { + entity.setCustomName(this.lived.name); + entity.setCustomNameVisible(this.lived.visible); } - if ((lived.potions != null) && (!lived.potions.isEmpty())) { - entity.addPotionEffects(lived.potions); + if ((this.lived.potions != null) && !this.lived.potions.isEmpty()) { + entity.addPotionEffects(this.lived.potions); } - entity.setRemainingAir(lived.air); - entity.setRemoveWhenFarAway(lived.persistent); - if (lived.equipped) { - final EntityEquipment equipment = entity.getEquipment(); - equipment.setItemInHand(lived.hands); - equipment.setHelmet(lived.helmet); - equipment.setChestplate(lived.chestplate); - equipment.setLeggings(lived.leggings); - equipment.setBoots(lived.boots); + entity.setRemainingAir(this.lived.air); + entity.setRemoveWhenFarAway(this.lived.persistent); + if (this.lived.equipped) { + EntityEquipment equipment = entity.getEquipment(); + equipment.setItemInHand(this.lived.hands); + equipment.setHelmet(this.lived.helmet); + equipment.setChestplate(this.lived.chestplate); + equipment.setLeggings(this.lived.leggings); + equipment.setBoots(this.lived.boots); } - if (lived.leashed) { + if (this.lived.leashed) { // TODO leashes // World world = entity.getWorld(); // Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math @@ -339,11 +340,11 @@ public class EntityWrapper { } } - private void restoreInventory(final InventoryHolder entity) { - entity.getInventory().setContents(inventory); + private void restoreInventory(InventoryHolder entity) { + entity.getInventory().setContents(this.inventory); } - public void storeLiving(final LivingEntity lived) { + public void storeLiving(LivingEntity lived) { this.lived = new LivingEntityStats(); this.lived.potions = lived.getActivePotionEffects(); this.lived.loot = lived.getCanPickupItems(); @@ -354,12 +355,12 @@ public class EntityWrapper { this.lived.persistent = lived.getRemoveWhenFarAway(); this.lived.leashed = lived.isLeashed(); if (this.lived.leashed) { - final Location loc = lived.getLeashHolder().getLocation(); - this.lived.leash_x = (short) (x - loc.getBlockX()); - this.lived.leash_y = (short) (y - loc.getBlockY()); - this.lived.leash_z = (short) (z - loc.getBlockZ()); + Location loc = lived.getLeashHolder().getLocation(); + this.lived.leash_x = (short) (this.x - loc.getBlockX()); + this.lived.leash_y = (short) (this.y - loc.getBlockY()); + this.lived.leash_z = (short) (this.z - loc.getBlockZ()); } - final EntityEquipment equipment = lived.getEquipment(); + EntityEquipment equipment = lived.getEquipment(); this.lived.equipped = equipment != null; if (this.lived.equipped) { this.lived.hands = equipment.getItemInHand().clone(); @@ -370,50 +371,50 @@ public class EntityWrapper { } } - private void restoreTameable(final Tameable entity) { - if (tamed.tamed) { - if (tamed.owner != null) { + private void restoreTameable(Tameable entity) { + if (this.tamed.tamed) { + if (this.tamed.owner != null) { entity.setTamed(true); - entity.setOwner(tamed.owner); + entity.setOwner(this.tamed.owner); } } } - private void restoreAgeable(final Ageable entity) { - if (!aged.adult) { + private void restoreAgeable(Ageable entity) { + if (!this.aged.adult) { entity.setBaby(); } - entity.setAgeLock(aged.locked); - if (aged.age > 0) { - entity.setAge(aged.age); + entity.setAgeLock(this.aged.locked); + if (this.aged.age > 0) { + entity.setAge(this.aged.age); } } - public void storeAgeable(final Ageable aged) { + public void storeAgeable(Ageable aged) { this.aged = new AgeableStats(); this.aged.age = aged.getAge(); this.aged.locked = aged.getAgeLock(); this.aged.adult = aged.isAdult(); } - public void storeTameable(final Tameable tamed) { + public void storeTameable(Tameable tamed) { this.tamed = new TameableStats(); this.tamed.owner = tamed.getOwner(); this.tamed.tamed = tamed.isTamed(); } @SuppressWarnings("deprecation") - public Entity spawn(final World world, final int x_offset, final int z_offset) { - final Location loc = new Location(world, x + x_offset, y, z + z_offset); - loc.setYaw(yaw); - loc.setPitch(pitch); - if (type.isSpawnable()) { + public Entity spawn(World world, int x_offset, int z_offset) { + Location loc = new Location(world, this.x + x_offset, this.y, this.z + z_offset); + loc.setYaw(this.yaw); + loc.setPitch(this.pitch); + if (this.type.isSpawnable()) { return null; } Entity entity; - switch (type) { + switch (this.type) { case DROPPED_ITEM: { - return world.dropItem(loc, stack); + return world.dropItem(loc, this.stack); } case PLAYER: case LEASH_HITCH: { @@ -428,28 +429,29 @@ public class EntityWrapper { break; } default: - entity = world.spawnEntity(loc, type); + entity = world.spawnEntity(loc, this.type); break; } - if (depth == 0) { + if (this.depth == 0) { return entity; } - if (base.passenger != null) { + if (this.base.passenger != null) { try { - entity.setPassenger(base.passenger.spawn(world, x_offset, z_offset)); - } catch (final Exception e) {} + entity.setPassenger(this.base.passenger.spawn(world, x_offset, z_offset)); + } catch (Exception e) { + } } - if (base.fall != 0) { - entity.setFallDistance(base.fall); + if (this.base.fall != 0) { + entity.setFallDistance(this.base.fall); } - if (base.fire != 0) { - entity.setFireTicks(base.fire); + if (this.base.fire != 0) { + entity.setFireTicks(this.base.fire); } - if (base.age != 0) { - entity.setTicksLived(base.age); + if (this.base.age != 0) { + entity.setTicksLived(this.base.age); } - entity.setVelocity(new Vector(base.v_x, base.v_y, base.v_z)); - if (depth == 1) { + entity.setVelocity(new Vector(this.base.v_x, this.base.v_y, this.base.v_z)); + if (this.depth == 1) { return entity; } switch (entity.getType()) { @@ -491,15 +493,15 @@ public class EntityWrapper { } // MISC // case ITEM_FRAME: { - final ItemFrame itemframe = (ItemFrame) entity; - itemframe.setRotation(Rotation.values()[dataByte]); - itemframe.setItem(stack); + ItemFrame itemframe = (ItemFrame) entity; + itemframe.setRotation(Rotation.values()[this.dataByte]); + itemframe.setItem(this.stack); return entity; } case PAINTING: { - final Painting painting = (Painting) entity; - painting.setFacingDirection(BlockFace.values()[dataByte], true); - painting.setArt(Art.getByName(dataString), true); + Painting painting = (Painting) entity; + painting.setFacingDirection(BlockFace.values()[this.dataByte], true); + painting.setArt(Art.getByName(this.dataString), true); return entity; } // END MISC // @@ -513,7 +515,7 @@ public class EntityWrapper { // START AGEABLE // // START TAMEABLE // case HORSE: { - final Horse horse = (Horse) entity; + Horse horse = (Horse) entity; horse.setJumpStrength(this.horse.jump); horse.setCarryingChest(this.horse.chest); horse.setVariant(Variant.values()[this.horse.variant]); @@ -535,12 +537,12 @@ public class EntityWrapper { } // END AGEABLE // case SHEEP: { - final Sheep sheep = (Sheep) entity; - if (dataByte == 1) { + Sheep sheep = (Sheep) entity; + if (this.dataByte == 1) { sheep.setSheared(true); } - if (dataByte2 != 0) { - sheep.setColor(DyeColor.getByDyeData(dataByte2)); + if (this.dataByte2 != 0) { + sheep.setColor(DyeColor.getByDyeData(this.dataByte2)); } restoreAgeable((Ageable) entity); restoreLiving((LivingEntity) entity); @@ -557,67 +559,67 @@ public class EntityWrapper { } // END AGEABLE // case RABBIT: { // NEW - if (dataByte != 0) { - ((Rabbit) entity).setRabbitType(Type.values()[dataByte]); + if (this.dataByte != 0) { + ((Rabbit) entity).setRabbitType(Type.values()[this.dataByte]); } restoreAgeable((Ageable) entity); restoreLiving((LivingEntity) entity); return entity; } case GUARDIAN: { // NEW - if (dataByte != 0) { + if (this.dataByte != 0) { ((Guardian) entity).setElder(true); } restoreLiving((LivingEntity) entity); return entity; } case SKELETON: { // NEW - if (dataByte != 0) { - ((Skeleton) entity).setSkeletonType(SkeletonType.values()[dataByte]); + if (this.dataByte != 0) { + ((Skeleton) entity).setSkeletonType(SkeletonType.values()[this.dataByte]); } storeLiving((LivingEntity) entity); return entity; } case ARMOR_STAND: { // NEW // CHECK positions - final ArmorStand stand = (ArmorStand) entity; - if (inventory[0] != null) { - stand.setItemInHand(inventory[0]); + ArmorStand stand = (ArmorStand) entity; + if (this.inventory[0] != null) { + stand.setItemInHand(this.inventory[0]); } - if (inventory[1] != null) { - stand.setHelmet(inventory[1]); + if (this.inventory[1] != null) { + stand.setHelmet(this.inventory[1]); } - if (inventory[2] != null) { - stand.setChestplate(inventory[2]); + if (this.inventory[2] != null) { + stand.setChestplate(this.inventory[2]); } - if (inventory[3] != null) { - stand.setLeggings(inventory[3]); + if (this.inventory[3] != null) { + stand.setLeggings(this.inventory[3]); } - if (inventory[4] != null) { - stand.setBoots(inventory[4]); + if (this.inventory[4] != null) { + stand.setBoots(this.inventory[4]); } if ((this.stand.head[0] != 0) || (this.stand.head[1] != 0) || (this.stand.head[2] != 0)) { - final EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); + EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); stand.setHeadPose(pose); } if ((this.stand.body[0] != 0) || (this.stand.body[1] != 0) || (this.stand.body[2] != 0)) { - final EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); + EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); stand.setBodyPose(pose); } if ((this.stand.leftLeg[0] != 0) || (this.stand.leftLeg[1] != 0) || (this.stand.leftLeg[2] != 0)) { - final EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]); + EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]); stand.setLeftLegPose(pose); } if ((this.stand.rightLeg[0] != 0) || (this.stand.rightLeg[1] != 0) || (this.stand.rightLeg[2] != 0)) { - final EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]); + EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]); stand.setRightLegPose(pose); } if ((this.stand.leftArm[0] != 0) || (this.stand.leftArm[1] != 0) || (this.stand.leftArm[2] != 0)) { - final EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]); + EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]); stand.setLeftArmPose(pose); } if ((this.stand.rightArm[0] != 0) || (this.stand.rightArm[1] != 0) || (this.stand.rightArm[2] != 0)) { - final EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]); + EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]); stand.setRightArmPose(pose); } if (this.stand.invisible) { @@ -663,8 +665,8 @@ public class EntityWrapper { // END LIVING // } } - - private byte getOrdinal(final Object[] list, final Object value) { + + private byte getOrdinal(Object[] list, Object value) { for (byte i = 0; i < list.length; i++) { if (list[i].equals(value)) { return i; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java index 02173497a..34d42a497 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java @@ -11,12 +11,14 @@ import java.util.HashMap; import java.util.Map; /** - * Minecraft 1.8 Title + * Minecraft 1.8 Title. * * @version 1.0.4 * @author Maxim Van de Wynckel */ public class HackTitleManager { + + private static final Map, Class> CORRESPONDING_TYPES = new HashMap<>(); /* Title packet */ private Class packetTitle; /* Title packet actions ENUM */ @@ -29,76 +31,66 @@ public class HackTitleManager { /* Subtitle text and color */ private String subtitle = ""; private ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ + /* Title timings. */ private int fadeInTime = -1; 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 + * Create a new 1.8 title. * - * @param title - * Title - * @throws ClassNotFoundException + * @param title Title + * @throws ClassNotFoundException NMS Error. */ - public HackTitleManager(final String title) throws ClassNotFoundException { + public HackTitleManager(String title) throws ClassNotFoundException { this.title = title; loadClasses(); } - + /** - * Create a new 1.8 title + * Create a new 1.8 title. * - * @param title - * Title text - * @param subtitle - * Subtitle text - * @throws ClassNotFoundException + * @param title Title text + * @param subtitle Subtitle text + * @throws ClassNotFoundException NMS Error */ - public HackTitleManager(final String title, final String subtitle) throws ClassNotFoundException { + public HackTitleManager(String title, String subtitle) throws ClassNotFoundException { this.title = title; this.subtitle = subtitle; loadClasses(); } - + /** - * Copy 1.8 title + * Copy 1.8 title. * - * @param title - * Title - * @throws ClassNotFoundException + * @param title Title + * @throws ClassNotFoundException NMS Error */ - public HackTitleManager(final HackTitleManager title) throws ClassNotFoundException { + public HackTitleManager(HackTitleManager 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 - * @throws ClassNotFoundException + * @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 NMS error */ - public HackTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException { + public HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) throws ClassNotFoundException { this.title = title; this.subtitle = subtitle; this.fadeInTime = fadeInTime; @@ -106,265 +98,8 @@ public class HackTitleManager { this.fadeOutTime = fadeOutTime; loadClasses(); } - - /** - * Load spigot and NMS classes - * @throws ClassNotFoundException - */ - private void loadClasses() throws ClassNotFoundException { - packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); - packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); - nmsChatSerializer = getNMSClass("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; - } - - /** - * Set subtitle text - * - * @param subtitle - * Subtitle text - */ - public void setSubtitle(final String subtitle) { - this.subtitle = subtitle; - } - - /** - * Get subtitle text - * - * @return Subtitle text - */ - public String getSubtitle() { - return subtitle; - } - - /** - * Set the title color - * - * @param color - * Chat color - */ - public void setTitleColor(final ChatColor color) { - titleColor = color; - } - - /** - * Set the subtitle color - * - * @param color - * Chat color - */ - public void setSubtitleColor(final ChatColor color) { - subtitleColor = color; - } - - /** - * Set title fade in time - * - * @param time - * Time - */ - public void setFadeInTime(final int time) { - fadeInTime = time; - } - - /** - * Set title fade out time - * - * @param time - * Time - */ - public void setFadeOutTime(final int time) { - fadeOutTime = time; - } - - /** - * Set title stay time - * - * @param time - * Time - */ - public void setStayTime(final int time) { - stayTime = time; - } - - /** - * Set timings to ticks - */ - public void setTimingsToTicks() { - ticks = true; - } - - /** - * Set timings to seconds - */ - public void setTimingsToSeconds() { - ticks = false; - } - - /** - * Send the title to a player - * - * @param player - * Player - */ - public void send(final Player player) throws Exception { - if ((getProtocolVersion(player) >= 47) && isSpigot() && (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, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], fadeInTime * (ticks ? 1 : 20), stayTime * (ticks ? 1 : 20), - fadeOutTime * (ticks ? 1 : 20)); - // Send if set - if ((fadeInTime != -1) && (fadeOutTime != -1) && (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, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); - sendPacket.invoke(connection, packet); - if (!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, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); - sendPacket.invoke(connection, packet); - } - } - } - - /** - * Broadcast the title to all players - */ - public void broadcast() throws Exception { - for (final Player p : Bukkit.getOnlinePlayers()) { - send(p); - } - } - - /** - * Clear the title - * - * @param player - * Player - * @throws Exception - */ - public void clearTitle(final Player player) throws Exception { - if ((getProtocolVersion(player) >= 47) && isSpigot()) { - // 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).newInstance(actions[3]); - sendPacket.invoke(connection, packet); - } - } - - /** - * Reset the title settings - * - * @param player - * Player - * @throws Exception - */ - public void resetTitle(final Player player) throws Exception { - if ((getProtocolVersion(player) >= 47) && isSpigot()) { - // 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).newInstance(actions[4]); - sendPacket.invoke(connection, packet); - } - } - - /** - * Get the protocol version of the player - * - * @param player - * Player - * @return Protocol version - * @throws Exception - */ - private int getProtocolVersion(final Player player) throws Exception { - final Object handle = getHandle(player); - final Object connection = getField(handle.getClass(), "playerConnection").get(handle); - final Object networkManager = getValue("networkManager", connection); - return (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); - } - - /** - * Check if running spigot - * - * @return Spigot - */ - private boolean isSpigot() { - return Bukkit.getVersion().contains("Spigot"); - } - - /** - * Get class by url - * - * @param namespace - * Namespace url - * @return Class - */ - private Class getClass(final String namespace) { - try { - return Class.forName(namespace); - } catch (ClassNotFoundException e) { - } - return null; - } - - private Field getField(final String name, final Class clazz) throws Exception { - return clazz.getDeclaredField(name); - } - - private Object getValue(final String name, final Object obj) throws Exception { - final Field f = getField(name, obj.getClass()); - f.setAccessible(true); - return f.get(obj); - } - - private Class getPrimitiveType(final 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]; - for (int i = 0; i < a; i++) { - types[i] = getPrimitiveType(classes[i]); - } - return types; - } - - 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; } @@ -375,8 +110,258 @@ public class HackTitleManager { } return true; } - - private Object getHandle(final Object obj) { + + /** + * Load spigot and NMS classes. + * @throws ClassNotFoundException Spigot Error. + */ + private void loadClasses() throws ClassNotFoundException { + this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); + this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); + this.nmsChatSerializer = getNMSClass("ChatSerializer"); + } + + /** + * Get title text. + * + * @return Title text + */ + public String getTitle() { + return this.title; + } + + /** + * Set title text. + * + * @param title Title + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * Get subtitle text. + * + * @return Subtitle text + */ + public String getSubtitle() { + 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(ChatColor color) { + this.titleColor = color; + } + + /** + * Set the subtitle color. + * + * @param color Chat color + */ + public void setSubtitleColor(ChatColor color) { + this.subtitleColor = color; + } + + /** + * Set title fade in time. + * + * @param time Time + */ + public void setFadeInTime(int time) { + this.fadeInTime = time; + } + + /** + * Set title fade out time. + * + * @param time Time + */ + public void setFadeOutTime(int time) { + this.fadeOutTime = time; + } + + /** + * Set title stay time. + * + * @param time Time + */ + public void setStayTime(int time) { + this.stayTime = time; + } + + /** + * Set timings to ticks. + */ + public void setTimingsToTicks() { + this.ticks = true; + } + + /** + * Set timings to seconds. + */ + public void setTimingsToSeconds() { + this.ticks = false; + } + + /** + * Send the title to a player. + * + * @param player Player + * @throws Exception on NMS error + */ + public void send(Player player) throws Exception { + if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { + // First reset previous settings + resetTitle(player); + // Send timings first + 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, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], + this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); + // Send if set + if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { + sendPacket.invoke(connection, packet); + } + // Send title + 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, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); + sendPacket.invoke(connection, packet); + if (!this.subtitle.isEmpty()) { + // Send subtitle if present + 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, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); + sendPacket.invoke(connection, packet); + } + } + } + + /** + * Broadcast the title to all players. + * @throws Exception on NMS Error + */ + public void broadcast() throws Exception { + for (Player p : Bukkit.getOnlinePlayers()) { + send(p); + } + } + + /** + * Clear the title. + * + * @param player Player + * @throws Exception on NMS Error + */ + public void clearTitle(Player player) throws Exception { + if ((getProtocolVersion(player) >= 47) && isSpigot()) { + // Send timings first + 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).newInstance(actions[3]); + sendPacket.invoke(connection, packet); + } + } + + /** + * Reset the title settings. + * + * @param player Player + * @throws Exception on NMS error. + */ + public void resetTitle(Player player) throws Exception { + if ((getProtocolVersion(player) >= 47) && isSpigot()) { + // Send timings first + 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).newInstance(actions[4]); + sendPacket.invoke(connection, packet); + } + } + + /** + * Get the protocol version of the player. + * + * @param player Player + * @return Protocol version + * @throws Exception on NMS Error + */ + private int getProtocolVersion(Player player) throws Exception { + Object handle = getHandle(player); + Object connection = getField(handle.getClass(), "playerConnection").get(handle); + Object networkManager = getValue("networkManager", connection); + return (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); + } + + /** + * Check if running spigot. + * + * @return Spigot + */ + private boolean isSpigot() { + return Bukkit.getVersion().contains("Spigot"); + } + + /** + * Get class by url. + * + * @param namespace Namespace url + * @return Class + */ + private Class getClass(String namespace) { + try { + return Class.forName(namespace); + } catch (ClassNotFoundException ignored) { + } + return null; + } + + private Field getField(String name, Class clazz) throws Exception { + return clazz.getDeclaredField(name); + } + + private Object getValue(String name, Object obj) throws Exception { + Field f = getField(name, obj.getClass()); + f.setAccessible(true); + return f.get(obj); + } + + private Class getPrimitiveType(Class clazz) { + return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; + } + + 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(Object obj) { try { return getMethod("getHandle", obj.getClass()).invoke(obj); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { @@ -384,31 +369,31 @@ public class HackTitleManager { 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(); + 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 (SecurityException | NoSuchFieldException e) { @@ -416,18 +401,18 @@ public class HackTitleManager { return null; } } - - private Method getMethod(final Class clazz, final String name, final Class... args) { - for (final Method m : clazz.getMethods()) { - if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) { + + 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; } } 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/BukkitChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java index 1c1bd2dee..626c100b7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java @@ -20,31 +20,31 @@ public class BukkitChatManager extends ChatManager { } @Override - public void color(final PlotMessage m, final String color) { + public void color(PlotMessage m, String color) { m.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); } @Override - public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { - final List lines = new ArrayList<>(); - for (final PlotMessage tooltip : tooltips) { + public void tooltip(PlotMessage m, PlotMessage... tooltips) { + List lines = new ArrayList<>(); + for (PlotMessage tooltip : tooltips) { lines.add(tooltip.$(this)); } m.$(this).formattedTooltip(lines); } @Override - public void command(final PlotMessage m, final String command) { + public void command(PlotMessage m, String command) { m.$(this).command(command); } @Override - public void text(final PlotMessage m, final String text) { + public void text(PlotMessage m, String text) { m.$(this).then(ChatColor.stripColor(text)); } @Override - public void send(final PlotMessage m, final PlotPlayer player) { + public void send(PlotMessage m, PlotPlayer player) { if (ConsolePlayer.isConsole(player)) { player.sendMessage(m.$(this).toOldMessageFormat()); } else { @@ -53,7 +53,7 @@ public class BukkitChatManager extends ChatManager { } @Override - public void suggest(final PlotMessage m, final String command) { + public void suggest(PlotMessage m, String command) { m.$(this).suggest(command); } 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 6fcb63c60..357068f11 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -72,7 +72,7 @@ public class BukkitChunkManager extends ChunkManager { private static HashMap hopperContents; private static HashMap furnaceTime; private static HashMap skullData; - private static HashMap jukeDisc; + private static HashMap jukeboxDisc; private static HashMap brewTime; private static HashMap spawnerData; private static HashMap cmdData; @@ -81,7 +81,7 @@ public class BukkitChunkManager extends ChunkManager { private static HashMap> bannerPatterns; private static HashMap bannerBase; private static HashSet entities; - private static HashMap allblocks; + private static HashMap allBlocks; public static void initMaps() { chestContents = new HashMap<>(); @@ -94,7 +94,7 @@ public class BukkitChunkManager extends ChunkManager { furnaceTime = new HashMap<>(); skullData = new HashMap<>(); brewTime = new HashMap<>(); - jukeDisc = new HashMap<>(); + jukeboxDisc = new HashMap<>(); spawnerData = new HashMap<>(); noteBlockContents = new HashMap<>(); signContents = new HashMap<>(); @@ -102,47 +102,47 @@ public class BukkitChunkManager extends ChunkManager { bannerBase = new HashMap<>(); bannerPatterns = new HashMap<>(); entities = new HashSet<>(); - allblocks = new HashMap<>(); + allBlocks = new HashMap<>(); } - public static boolean isIn(final RegionWrapper region, final int x, final int z) { + public static boolean isIn(RegionWrapper region, int x, int z) { return x >= region.minX && x <= region.maxX && z >= region.minZ && z <= region.maxZ; } - public static void saveEntitiesOut(final Chunk chunk, final RegionWrapper region) { - for (final Entity entity : chunk.getEntities()) { - final Location loc = BukkitUtil.getLocation(entity); - final int x = loc.getX(); - final int z = loc.getZ(); + public static void saveEntitiesOut(Chunk chunk, RegionWrapper region) { + for (Entity entity : chunk.getEntities()) { + Location loc = BukkitUtil.getLocation(entity); + int x = loc.getX(); + int z = loc.getZ(); if (isIn(region, x, z)) { continue; } if (entity.getVehicle() != null) { continue; } - final EntityWrapper wrap = new EntityWrapper(entity, (short) 2); + EntityWrapper wrap = new EntityWrapper(entity, (short) 2); entities.add(wrap); } } - public static void saveEntitiesIn(final Chunk chunk, final RegionWrapper region) { + public static void saveEntitiesIn(Chunk chunk, RegionWrapper region) { saveEntitiesIn(chunk, region, 0, 0, false); } - public static void saveEntitiesIn(final Chunk chunk, final RegionWrapper region, final int offset_x, final int offset_z, final boolean delete) { - for (final Entity entity : chunk.getEntities()) { - final Location loc = BukkitUtil.getLocation(entity); - final int x = loc.getX(); - final int z = loc.getZ(); + public static void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, boolean delete) { + for (Entity entity : chunk.getEntities()) { + Location loc = BukkitUtil.getLocation(entity); + int x = loc.getX(); + int z = loc.getZ(); if (!isIn(region, x, z)) { continue; } if (entity.getVehicle() != null) { continue; } - final EntityWrapper wrap = new EntityWrapper(entity, (short) 2); - wrap.x += offset_x; - wrap.z += offset_z; + EntityWrapper wrap = new EntityWrapper(entity, (short) 2); + wrap.x += offsetX; + wrap.z += offsetZ; entities.add(wrap); if (delete) { if (!(entity instanceof Player)) { @@ -152,11 +152,11 @@ public class BukkitChunkManager extends ChunkManager { } } - public static void restoreEntities(final World world, final int x_offset, final int z_offset) { - for (final EntityWrapper entity : entities) { + public static void restoreEntities(World world, int xOffset, int zOffset) { + for (EntityWrapper entity : entities) { try { - entity.spawn(world, x_offset, z_offset); - } catch (final Exception e) { + entity.spawn(world, xOffset, zOffset); + } catch (Exception e) { PS.debug("Failed to restore entity (e): " + entity.x + "," + entity.y + "," + entity.z + " : " + entity.type); e.printStackTrace(); } @@ -164,130 +164,130 @@ public class BukkitChunkManager extends ChunkManager { entities.clear(); } - public static void restoreBlocks(final World world, final int x_offset, final int z_offset) { - for (final Entry blockLocEntry : chestContents.entrySet()) { + public static void restoreBlocks(World world, int xOffset, int zOffset) { + for (Entry blockLocEntry : chestContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Chest) { - final InventoryHolder chest = (InventoryHolder) state; + InventoryHolder chest = (InventoryHolder) state; chest.getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : signContents.entrySet()) { + for (Entry blockLocEntry : signContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Sign) { - final Sign sign = (Sign) state; + Sign sign = (Sign) state; int i = 0; - for (final String line : blockLocEntry.getValue()) { + for (String line : blockLocEntry.getValue()) { sign.setLine(i, line); i++; } state.update(true); } else { PS.debug( - "&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry.getKey().y + "&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry.getKey().y + "," + ( - blockLocEntry.getKey().z + z_offset)); + blockLocEntry.getKey().z + zOffset)); } } catch (IndexOutOfBoundsException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry.getKey().y + PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry.getKey().y + "," + ( - blockLocEntry.getKey().z + z_offset)); + blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : dispenserContents.entrySet()) { + for (Entry blockLocEntry : dispenserContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Dispenser) { ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : dropperContents.entrySet()) { + for (Entry blockLocEntry : dropperContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Dropper) { ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : beaconContents.entrySet()) { + for (Entry blockLocEntry : beaconContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Beacon) { ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocMaterialEntry : jukeDisc.entrySet()) { + for (Entry blockLocMaterialEntry : jukeboxDisc.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocMaterialEntry.getKey().x + x_offset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry - .getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry + .getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Jukebox) { ((Jukebox) state).setPlaying(blockLocMaterialEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + x_offset) + "," + PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + xOffset) + "," + blockLocMaterialEntry .getKey().y + "," + ( - blockLocMaterialEntry.getKey().z + z_offset)); + blockLocMaterialEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + x_offset) + "," + } catch (Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + xOffset) + "," + blockLocMaterialEntry .getKey().y + "," + ( - blockLocMaterialEntry.getKey().z + z_offset)); + blockLocMaterialEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : skullData.entrySet()) { + for (Entry blockLocEntry : skullData.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Skull) { - final Object[] data = blockLocEntry.getValue(); + Object[] data = blockLocEntry.getValue(); if (data[0] != null) { ((Skull) state).setOwner((String) data[0]); } @@ -299,215 +299,218 @@ public class BukkitChunkManager extends ChunkManager { } state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry.getKey().y + PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry.getKey().y + "," + ( - blockLocEntry.getKey().z + z_offset)); + blockLocEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } catch (Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : hopperContents.entrySet()) { + for (Entry blockLocEntry : hopperContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Hopper) { ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocNoteEntry : noteBlockContents.entrySet()) { + for (Entry blockLocNoteEntry : noteBlockContents.entrySet()) { try { - final Block block = world.getBlockAt( - blockLocNoteEntry.getKey().x + x_offset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = world.getBlockAt( + blockLocNoteEntry.getKey().x + xOffset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof NoteBlock) { ((NoteBlock) state).setNote(blockLocNoteEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + x_offset) + "," + PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + xOffset) + "," + blockLocNoteEntry .getKey().y + "," + ( - blockLocNoteEntry.getKey().z + z_offset)); + blockLocNoteEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + x_offset) + "," + } catch (Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + xOffset) + "," + blockLocNoteEntry .getKey().y + "," + ( - blockLocNoteEntry.getKey().z + z_offset)); + blockLocNoteEntry.getKey().z + zOffset)); } } - for (final Entry blockLocShortEntry : brewTime.entrySet()) { + for (Entry blockLocShortEntry : brewTime.entrySet()) { try { - final Block block = world.getBlockAt( - blockLocShortEntry.getKey().x + x_offset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = world.getBlockAt( + blockLocShortEntry.getKey().x + xOffset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof BrewingStand) { ((BrewingStand) state).setBrewingTime(blockLocShortEntry.getValue()); } else { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + x_offset) + "," + PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + xOffset) + "," + blockLocShortEntry .getKey().y + "," + ( - blockLocShortEntry.getKey().z + z_offset)); + blockLocShortEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + x_offset) + "," + + } 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 + z_offset)); + blockLocShortEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntityTypeEntry : spawnerData.entrySet()) { + for (Entry blockLocEntityTypeEntry : spawnerData.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntityTypeEntry.getKey().x + x_offset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry - .getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry + .getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof CreatureSpawner) { ((CreatureSpawner) state).setSpawnedType(blockLocEntityTypeEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + x_offset) + "," + PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + xOffset) + "," + blockLocEntityTypeEntry .getKey().y + "," + ( - blockLocEntityTypeEntry.getKey().z + z_offset)); + blockLocEntityTypeEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + x_offset) + "," + - blockLocEntityTypeEntry - .getKey().y + "," + ( - blockLocEntityTypeEntry.getKey().z + z_offset)); + } 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)); } } - for (final Entry blockLocStringEntry : cmdData.entrySet()) { + for (Entry blockLocStringEntry : cmdData.entrySet()) { try { - final Block block = world.getBlockAt( - blockLocStringEntry.getKey().x + x_offset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = world.getBlockAt( + blockLocStringEntry.getKey().x + xOffset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof CommandBlock) { ((CommandBlock) state).setCommand(blockLocStringEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + x_offset) + "," + PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + xOffset) + "," + blockLocStringEntry .getKey().y + "," + ( - blockLocStringEntry.getKey().z + z_offset)); + blockLocStringEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + x_offset) + "," + } catch (Exception e) { + PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + xOffset) + "," + blockLocStringEntry .getKey().y + "," + ( - blockLocStringEntry.getKey().z + z_offset)); + blockLocStringEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : brewingStandContents.entrySet()) { + for (Entry blockLocEntry : brewingStandContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof BrewingStand) { ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry .getKey().y + "," + ( blockLocEntry.getKey().z - + z_offset)); + + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry .getKey().y + "," + ( blockLocEntry.getKey().z - + z_offset)); + + zOffset)); } } - for (final Entry blockLocEntry : furnaceTime.entrySet()) { + for (Entry blockLocEntry : furnaceTime.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Furnace) { - final Short[] time = blockLocEntry.getValue(); + Short[] time = blockLocEntry.getValue(); ((Furnace) state).setBurnTime(time[0]); ((Furnace) state).setCookTime(time[1]); } else { - PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry .getKey().y + "," + ( - blockLocEntry.getKey().z + z_offset)); + blockLocEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + } catch (Exception e) { + PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry .getKey().y + "," + ( - blockLocEntry.getKey().z + z_offset)); + blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocEntry : furnaceContents.entrySet()) { + for (Entry blockLocEntry : furnaceContents.entrySet()) { try { - final Block block = - world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = + world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Furnace) { ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry - .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + xOffset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + zOffset)); } } - for (final Entry blockLocByteEntry : bannerBase.entrySet()) { + for (Entry blockLocByteEntry : bannerBase.entrySet()) { try { - final Block block = world.getBlockAt( - blockLocByteEntry.getKey().x + x_offset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + z_offset); - final BlockState state = block.getState(); + Block block = world.getBlockAt( + blockLocByteEntry.getKey().x + xOffset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset); + BlockState state = block.getState(); if (state instanceof Banner) { - final Banner banner = (Banner) state; - final DyeColor base = blockLocByteEntry.getValue(); - final List patterns = bannerPatterns.get(blockLocByteEntry.getKey()); + Banner banner = (Banner) state; + DyeColor base = blockLocByteEntry.getValue(); + List patterns = bannerPatterns.get(blockLocByteEntry.getKey()); banner.setBaseColor(base); banner.setPatterns(patterns); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + x_offset) + "," + blockLocByteEntry + PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + xOffset) + "," + blockLocByteEntry .getKey().y + "," + ( - blockLocByteEntry.getKey().z + z_offset)); + blockLocByteEntry.getKey().z + zOffset)); } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + x_offset) + "," + blockLocByteEntry + } catch (Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + xOffset) + "," + blockLocByteEntry .getKey().y + "," + ( - blockLocByteEntry.getKey().z + z_offset)); + blockLocByteEntry.getKey().z + zOffset)); } } } - public static void saveBlocks(final World world, int maxY, final int x, final int z, final int offset_x, final int offset_z, + 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 = storeNormal ? new PlotBlock[maxY + 1] : null; + PlotBlock[] ids; + if (storeNormal) { + ids = new PlotBlock[maxY + 1]; + } else { + ids = null; + } for (short y = 0; y <= maxY; y++) { - final Block block = world.getBlockAt(x, y, z); - final Material id = block.getType(); + Block block = world.getBlockAt(x, y, z); + Material id = block.getType(); if (!id.equals(Material.AIR)) { if (storeNormal) { ids[y] = new PlotBlock((short) id.getId(), block.getData()); } try { - BlockLoc bl = new BlockLoc(x + offset_x, y, z + offset_z); + BlockLoc bl = new BlockLoc(x + offsetX, y, z + offsetZ); if (block.getState() instanceof InventoryHolder) { - final InventoryHolder inventoryHolder = (InventoryHolder) block.getState(); - final ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone(); + InventoryHolder inventoryHolder = (InventoryHolder) block.getState(); + ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone(); if (id == Material.CHEST) { chestContents.put(bl, inventory); } else if (id == Material.DISPENSER) { @@ -519,71 +522,71 @@ public class BukkitChunkManager extends ChunkManager { } else if (id == Material.HOPPER) { hopperContents.put(bl, inventory); } else if (id == Material.BREWING_STAND) { - final BrewingStand brewingStand = (BrewingStand) inventoryHolder; - final short time = (short) brewingStand.getBrewingTime(); + BrewingStand brewingStand = (BrewingStand) inventoryHolder; + short time = (short) brewingStand.getBrewingTime(); if (time > 0) { brewTime.put(bl, time); } - final ItemStack[] invBre = brewingStand.getInventory().getContents().clone(); + ItemStack[] invBre = brewingStand.getInventory().getContents().clone(); brewingStandContents.put(bl, invBre); } else if (id == Material.FURNACE || id == Material.BURNING_FURNACE) { - final Furnace furnace = (Furnace) inventoryHolder; - final short burn = furnace.getBurnTime(); - final short cook = furnace.getCookTime(); - final ItemStack[] invFur = furnace.getInventory().getContents().clone(); + Furnace furnace = (Furnace) inventoryHolder; + short burn = furnace.getBurnTime(); + short cook = furnace.getCookTime(); + ItemStack[] invFur = furnace.getInventory().getContents().clone(); furnaceContents.put(bl, invFur); if (cook != 0) { furnaceTime.put(bl, new Short[]{burn, cook}); } } } else if (block.getState() instanceof CreatureSpawner) { - final CreatureSpawner spawner = (CreatureSpawner) block.getState(); - final EntityType type = spawner.getSpawnedType(); + CreatureSpawner spawner = (CreatureSpawner) block.getState(); + EntityType type = spawner.getSpawnedType(); if (type != null) { spawnerData.put(bl, type); } } else if (block.getState() instanceof CommandBlock) { - final CommandBlock cmd = (CommandBlock) block.getState(); - final String string = cmd.getCommand(); + CommandBlock cmd = (CommandBlock) block.getState(); + String string = cmd.getCommand(); if (string != null && !string.isEmpty()) { cmdData.put(bl, string); } } else if (block.getState() instanceof NoteBlock) { - final NoteBlock noteBlock = (NoteBlock) block.getState(); - final Note note = noteBlock.getNote(); + NoteBlock noteBlock = (NoteBlock) block.getState(); + Note note = noteBlock.getNote(); noteBlockContents.put(bl, note); } else if (block.getState() instanceof Jukebox) { - final Jukebox jukebox = (Jukebox) block.getState(); - final Material playing = jukebox.getPlaying(); + Jukebox jukebox = (Jukebox) block.getState(); + Material playing = jukebox.getPlaying(); if (playing != null) { - jukeDisc.put(bl, playing); + jukeboxDisc.put(bl, playing); } } else if (block.getState() instanceof Skull) { - final Skull skull = (Skull) block.getState(); - final String o = skull.getOwner(); - final byte skulltype = getOrdinal(SkullType.values(), skull.getSkullType()); + Skull skull = (Skull) block.getState(); + String o = skull.getOwner(); + byte skullType = getOrdinal(SkullType.values(), skull.getSkullType()); skull.getRotation(); - final short rot = getOrdinal(BlockFace.values(), skull.getRotation()); - skullData.put(bl, new Object[]{o, rot, skulltype}); + short rot = getOrdinal(BlockFace.values(), skull.getRotation()); + skullData.put(bl, new Object[]{o, rot, skullType}); } else if (block.getState() instanceof Banner) { - final Banner banner = (Banner) block.getState(); - final DyeColor base = banner.getBaseColor(); + Banner banner = (Banner) block.getState(); + DyeColor base = banner.getBaseColor(); bannerBase.put(bl, base); bannerPatterns.put(bl, banner.getPatterns()); } - } catch (final Exception e) { + } catch (Exception e) { PS.debug("------------ FAILED TO DO SOMETHING --------"); e.printStackTrace(); PS.debug("------------ but we caught it ^ --------"); } } } - final PlotLoc loc = new PlotLoc(x + offset_x, z + offset_z); - allblocks.put(loc, ids); + PlotLoc loc = new PlotLoc(x + offsetX, z + offsetZ); + allBlocks.put(loc, ids); } - private static byte getOrdinal(final Object[] list, final Object value) { + private static byte getOrdinal(Object[] list, Object value) { for (byte i = 0; i < list.length; i++) { if (list[i].equals(value)) { return i; @@ -592,49 +595,49 @@ public class BukkitChunkManager extends ChunkManager { return 0; } - public static void swapChunk(final World world1, final World world2, final Chunk pos1, final Chunk pos2, final RegionWrapper r1, - final RegionWrapper r2) { + public static void swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, RegionWrapper r1, + RegionWrapper r2) { initMaps(); - final int relX = r2.minX - r1.minX; - final int relZ = r2.minZ - r1.minZ; + int relX = r2.minX - r1.minX; + int relZ = r2.minZ - r1.minZ; saveEntitiesIn(pos1, r1, relX, relZ, true); saveEntitiesIn(pos2, r2, -relX, -relZ, true); - final int sx = pos1.getX() << 4; - final int sz = pos1.getZ() << 4; + int sx = pos1.getX() << 4; + int sz = pos1.getZ() << 4; - String worldname1 = world1.getName(); - String worldname2 = world2.getName(); + String worldName1 = world1.getName(); + String worldName2 = world2.getName(); for (int x = Math.max(r1.minX, sx); x <= Math.min(r1.maxX, sx + 15); x++) { for (int z = Math.max(r1.minZ, sz); z <= Math.min(r1.maxZ, sz + 15); z++) { saveBlocks(world1, 256, sx, sz, relX, relZ, false); for (int y = 0; y < 256; y++) { - final Block block1 = world1.getBlockAt(x, y, z); - final int id1 = block1.getTypeId(); - final byte data1 = block1.getData(); - final int xx = x + relX; - final int zz = z + relZ; - final Block block2 = world2.getBlockAt(xx, y, zz); - final int id2 = block2.getTypeId(); - final byte data2 = block2.getData(); + Block block1 = world1.getBlockAt(x, y, z); + int id1 = block1.getTypeId(); + byte data1 = block1.getData(); + int xx = x + relX; + int zz = z + relZ; + Block block2 = world2.getBlockAt(xx, y, zz); + int id2 = block2.getTypeId(); + byte data2 = block2.getData(); if (id1 == 0) { if (id2 != 0) { - SetQueue.IMP.setBlock(worldname1, x, y, z, (short) id2, data2); - SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) 0, (byte) 0); + SetQueue.IMP.setBlock(worldName1, x, y, z, (short) id2, data2); + SetQueue.IMP.setBlock(worldName2, xx, y, zz, (short) 0, (byte) 0); } } else if (id2 == 0) { - SetQueue.IMP.setBlock(worldname1, x, y, z, (short) 0, (byte) 0); - SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) id1, data1); + SetQueue.IMP.setBlock(worldName1, x, y, z, (short) 0, (byte) 0); + SetQueue.IMP.setBlock(worldName2, xx, y, zz, (short) id1, data1); } else if (id1 == id2) { if (data1 != data2) { block1.setData(data2); block2.setData(data1); } } else { - SetQueue.IMP.setBlock(worldname1, x, y, z, (short) id2, data2); - SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) id1, data1); + SetQueue.IMP.setBlock(worldName1, x, y, z, (short) id2, data2); + SetQueue.IMP.setBlock(worldName2, xx, y, zz, (short) id1, data1); } } } @@ -646,10 +649,10 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public Set getChunkChunks(final String world) { + public Set getChunkChunks(String world) { Set chunks = super.getChunkChunks(world); - for (final Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { - final ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); + for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { + ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); if (!chunks.contains(loc)) { chunks.add(loc); } @@ -658,8 +661,8 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public void regenerateChunk(final String world, final ChunkLoc loc) { - final World worldObj = Bukkit.getWorld(world); + public void regenerateChunk(String world, ChunkLoc loc) { + World worldObj = Bukkit.getWorld(world); worldObj.regenerateChunk(loc.x, loc.z); SetQueue.IMP.queue.sendChunk(world, Collections.singletonList(loc)); for (Entry entry : UUIDHandler.getPlayers().entrySet()) { @@ -674,28 +677,28 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone) { + public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - final Location pos4 = new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ); + Location pos4 = new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ); final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); final World oldWorld = Bukkit.getWorld(pos1.getWorld()); final World newWorld = Bukkit.getWorld(newPos.getWorld()); - final String newWorldname = newWorld.getName(); - final List chunks = new ArrayList<>(); + final String newWorldName = newWorld.getName(); + List chunks = new ArrayList<>(); initMaps(); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { - final int bx = value[2]; - final int bz = value[3]; - final int tx = value[4]; - final int tz = value[5]; - final ChunkLoc loc = new ChunkLoc(value[0], value[1]); - final int cxx = loc.x << 4; - final int czz = loc.z << 4; - final Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z); + int bx = value[2]; + int bz = value[3]; + int tx = value[4]; + int tz = value[5]; + ChunkLoc loc = new ChunkLoc(value[0], value[1]); + int cxx = loc.x << 4; + int czz = loc.z << 4; + Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z); saveEntitiesIn(chunk, region); for (int x = bx & 15; x <= (tx & 15); x++) { for (int z = bz & 15; z <= (tz & 15); z++) { @@ -706,17 +709,18 @@ public class BukkitChunkManager extends ChunkManager { }, new Runnable() { @Override public void run() { - for (Entry entry : allblocks.entrySet()) { + for (Entry entry : allBlocks.entrySet()) { PlotLoc loc = entry.getKey(); PlotBlock[] blocks = entry.getValue(); for (int y = 0; y < blocks.length; y++) { PlotBlock block = blocks[y]; if (block != null) { - SetQueue.IMP.setBlock(newWorldname, loc.x, y, loc.z, block); + SetQueue.IMP.setBlock(newWorldName, loc.x, y, loc.z, block); } } } - while (SetQueue.IMP.forceChunkSet()); + while (SetQueue.IMP.forceChunkSet()) { + } restoreBlocks(newWorld, 0, 0); restoreEntities(newWorld, relX, relZ); TaskManager.runTask(whenDone); @@ -725,14 +729,14 @@ public class BukkitChunkManager extends ChunkManager { return true; } - public void saveRegion(final World world, int x1, int x2, int z1, int z2) { + public void saveRegion(World world, int x1, int x2, int z1, int z2) { if (z1 > z2) { - final int tmp = z1; + int tmp = z1; z1 = z2; z2 = tmp; } if (x1 > x2) { - final int tmp = x1; + int tmp = x1; x1 = x2; x2 = tmp; } @@ -767,16 +771,16 @@ public class BukkitChunkManager extends ChunkManager { TaskManager.runTask(new Runnable() { @Override public void run() { - final long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { final ChunkLoc chunk = chunks.remove(0); - final int x = chunk.x; - final int z = chunk.z; - final int xxb = x << 4; - final int zzb = z << 4; - final int xxt = xxb + 15; - final int zzt = zzb + 15; - final Chunk chunkObj = worldObj.getChunkAt(x, z); + int x = chunk.x; + int z = chunk.z; + int xxb = x << 4; + int zzb = z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + Chunk chunkObj = worldObj.getChunkAt(x, z); if (!chunkObj.load(false)) { continue; } @@ -863,7 +867,7 @@ public class BukkitChunkManager extends ChunkManager { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { PlotLoc loc = new PlotLoc(bx + x, bz + z); - PlotBlock[] ids = allblocks.get(loc); + PlotBlock[] ids = allBlocks.get(loc); if (ids != null) { for (int y = 0; y < Math.min(128, ids.length); y++) { PlotBlock id = ids[y]; @@ -900,16 +904,16 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public void clearAllEntities(final Location pos1, final Location pos2) { - final String world = pos1.getWorld(); - final List entities = BukkitUtil.getEntities(world); - final int bx = pos1.getX(); - final int bz = pos1.getZ(); - final int tx = pos2.getX(); - final int tz = pos2.getZ(); - for (final Entity entity : entities) { + public void clearAllEntities(Location pos1, Location pos2) { + String world = pos1.getWorld(); + List entities = BukkitUtil.getEntities(world); + int bx = pos1.getX(); + int bz = pos1.getZ(); + int tx = pos2.getX(); + int tz = pos2.getZ(); + for (Entity entity : entities) { if (!(entity instanceof Player)) { - final org.bukkit.Location loc = entity.getLocation(); + org.bukkit.Location loc = entity.getLocation(); if (loc.getX() >= bx && loc.getX() <= tx && loc.getZ() >= bz && loc.getZ() <= tz) { entity.remove(); } @@ -918,7 +922,7 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public boolean loadChunk(final String world, final ChunkLoc loc, final boolean force) { + public boolean loadChunk(String world, ChunkLoc loc, boolean force) { return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force); } @@ -937,19 +941,19 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public void swap(final Location bot1, final Location top1, final Location bot2, final Location top2, final Runnable whenDone) { - final RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); - final RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); - final World world1 = Bukkit.getWorld(bot1.getWorld()); - final World world2 = Bukkit.getWorld(bot2.getWorld()); + public void swap(Location bot1, Location top1, Location bot2, Location top2, Runnable whenDone) { + RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); + RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); + World world1 = Bukkit.getWorld(bot1.getWorld()); + World world2 = Bukkit.getWorld(bot2.getWorld()); - final int relX = bot2.getX() - bot1.getX(); - final int relZ = bot2.getZ() - bot1.getZ(); + int relX = bot2.getX() - bot1.getX(); + int relZ = bot2.getZ() - bot1.getZ(); for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) { for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) { - final Chunk chunk1 = world1.getChunkAt(x, z); - final Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4)); + Chunk chunk1 = world1.getChunkAt(x, z); + Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4)); swapChunk(world1, world2, chunk1, chunk2, region1, region2); } } @@ -957,21 +961,21 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public int[] countEntities(final Plot plot) { + public int[] countEntities(Plot plot) { PlotArea area = plot.getArea(); - final World world = BukkitUtil.getWorld(area.worldname); + World world = BukkitUtil.getWorld(area.worldname); - final Location bot = plot.getBottomAbs(); - final Location top = plot.getTopAbs(); - final int bx = bot.getX() >> 4; - final int bz = bot.getZ() >> 4; + Location bot = plot.getBottomAbs(); + Location top = plot.getTopAbs(); + int bx = bot.getX() >> 4; + int bz = bot.getZ() >> 4; - final int tx = top.getX() >> 4; - final int tz = top.getZ() >> 4; + int tx = top.getX() >> 4; + int tz = top.getZ() >> 4; - final int size = tx - bx << 4; + int size = tx - bx << 4; - final Set chunks = new HashSet<>(); + Set chunks = new HashSet<>(); for (int X = bx; X <= tx; X++) { for (int Z = bz; Z <= tz; Z++) { if (world.isChunkLoaded(X, Z)) { @@ -989,14 +993,14 @@ public class BukkitChunkManager extends ChunkManager { } } - final int[] count = new int[6]; + int[] count = new int[6]; if (doWhole) { - for (final Entity entity : entities) { - final org.bukkit.Location loc = entity.getLocation(); - final Chunk chunk = loc.getChunk(); + for (Entity entity : entities) { + org.bukkit.Location loc = entity.getLocation(); + Chunk chunk = loc.getChunk(); if (chunks.contains(chunk)) { - final int X = chunk.getX(); - final int Z = chunk.getX(); + int X = chunk.getX(); + int Z = chunk.getZ(); if (X > bx && X < tx && Z > bz && Z < tz) { count(count, entity); } else { @@ -1008,11 +1012,11 @@ public class BukkitChunkManager extends ChunkManager { } } } else { - for (final Chunk chunk : chunks) { - final int X = chunk.getX(); - final int Z = chunk.getX(); - final Entity[] ents = chunk.getEntities(); - for (final Entity entity : ents) { + for (Chunk chunk : chunks) { + int X = chunk.getX(); + int Z = chunk.getZ(); + Entity[] entities1 = chunk.getEntities(); + for (Entity entity : entities1) { if (X == bx || X == tx || Z == bz || Z == tz) { Plot other = area.getPlot(BukkitUtil.getLocation(entity)); if (plot.equals(other)) { @@ -1027,7 +1031,7 @@ public class BukkitChunkManager extends ChunkManager { return count; } - private void count(final int[] count, final Entity entity) { + private void count(int[] count, Entity entity) { switch (entity.getType()) { case PLAYER: // not valid @@ -1041,6 +1045,10 @@ public class BukkitChunkManager extends ChunkManager { case SNOWBALL: case ENDER_PEARL: case ARROW: + case TIPPED_ARROW: + case SHULKER_BULLET: + case SPECTRAL_ARROW: + case DRAGON_FIREBALL: // projectile case PRIMED_TNT: case FALLING_BLOCK: @@ -1056,6 +1064,8 @@ public class BukkitChunkManager extends ChunkManager { case LIGHTNING: case WITHER_SKULL: case UNKNOWN: + case AREA_EFFECT_CLOUD: + case LINGERING_POTION: // non moving / unremovable break; case ITEM_FRAME: @@ -1109,6 +1119,7 @@ public class BukkitChunkManager extends ChunkManager { case WITCH: case WITHER: case ZOMBIE: + case SHULKER: // monster count[3]++; count[2]++; 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 b52c88566..999bdff4a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java @@ -31,8 +31,8 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } @Override - public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, - final String[] args) { + public boolean onCommand(final CommandSender commandSender, org.bukkit.command.Command command, final String commandLabel, + String[] args) { if (commandSender instanceof Player) { return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args); } @@ -47,7 +47,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } @Override - public boolean hasPermission(String perm) { + public boolean hasPermission(String permission) { return commandSender.hasPermission(commandLabel); } @@ -66,12 +66,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } @Override - public List onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, - final String[] strings) { + public List onTabComplete(CommandSender commandSender, org.bukkit.command.Command command, String s, + String[] strings) { if (!(commandSender instanceof Player)) { return null; } - final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender); + PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender); if (strings.length < 1) { if (strings.length == 0 || "plots".startsWith(s)) { return Collections.singletonList("plots"); @@ -80,11 +80,11 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { if (strings.length > 1) { return null; } - final Set tabOptions = new HashSet<>(); - final String arg = strings[0].toLowerCase(); + Set tabOptions = new HashSet<>(); + String arg = strings[0].toLowerCase(); ArrayList labels = new ArrayList<>(); - for (final Command cmd : MainCommand.getInstance().getCommands()) { - final String label = cmd.getCommand(); + for (Command cmd : MainCommand.getInstance().getCommands()) { + String label = cmd.getCommand(); HashSet aliases = new HashSet<>(cmd.getAliases()); aliases.add(label); for (String alias : aliases) { 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 51b005887..d0262d184 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -1,16 +1,14 @@ package com.plotsquared.bukkit.util; -import net.milkbowl.vault.economy.Economy; -import net.milkbowl.vault.permission.Permission; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; - import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.EconHandler; import com.plotsquared.bukkit.object.BukkitOfflinePlayer; import com.plotsquared.bukkit.object.BukkitPlayer; +import net.milkbowl.vault.economy.Economy; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.plugin.RegisteredServiceProvider; public class BukkitEconHandler extends EconHandler { @@ -19,80 +17,80 @@ public class BukkitEconHandler extends EconHandler { public Economy getEconomy() { init(); - return econ; + return this.econ; } public Permission getPermissions() { init(); - return perms; + return this.perms; } public boolean init() { - if (econ == null || perms == null) { + if (this.econ == null || this.perms == null) { setupPermissions(); setupEconomy(); } - return econ != null && perms != null; + return this.econ != null && this.perms != null; } private boolean setupPermissions() { - final RegisteredServiceProvider permissionProvider = + RegisteredServiceProvider permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { - perms = permissionProvider.getProvider(); + this.perms = permissionProvider.getProvider(); } - return perms != null; + return this.perms != null; } private boolean setupEconomy() { - final RegisteredServiceProvider economyProvider = + RegisteredServiceProvider economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { - econ = economyProvider.getProvider(); + this.econ = economyProvider.getProvider(); } - return econ != null; + return this.econ != null; } @Override - public double getMoney(final PlotPlayer player) { - final double bal = super.getMoney(player); + public double getMoney(PlotPlayer player) { + double bal = super.getMoney(player); if (Double.isNaN(bal)) { - return econ.getBalance(((BukkitPlayer) player).player); + return this.econ.getBalance(((BukkitPlayer) player).player); } return bal; } @Override - public void withdrawMoney(final PlotPlayer player, final double amount) { - econ.withdrawPlayer(((BukkitPlayer) player).player, amount); + public void withdrawMoney(PlotPlayer player, double amount) { + this.econ.withdrawPlayer(((BukkitPlayer) player).player, amount); } @Override - public void depositMoney(final PlotPlayer player, final double amount) { - econ.depositPlayer(((BukkitPlayer) player).player, amount); + public void depositMoney(PlotPlayer player, double amount) { + this.econ.depositPlayer(((BukkitPlayer) player).player, amount); } @Override - public void depositMoney(final OfflinePlotPlayer player, final double amount) { - econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); + public void depositMoney(OfflinePlotPlayer player, double amount) { + this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); } @Override - public void setPermission(final String world, final String player, final String perm, final boolean value) { + public void setPermission(String world, String player, String perm, boolean value) { if (value) { - perms.playerAdd(world, player, perm); + this.perms.playerAdd(world, player, perm); } else { - perms.playerRemove(world, player, perm); + this.perms.playerRemove(world, player, perm); } } @Override - public boolean hasPermission(final String world, final String player, final String perm) { - return perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); + public boolean hasPermission(String world, String player, String perm) { + return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); } @Override public double getBalance(PlotPlayer player) { - return econ.getBalance(player.getName()); + return this.econ.getBalance(player.getName()); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java index 5ba42b7b9..bfcd5c9af 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java @@ -35,91 +35,91 @@ import java.util.UUID; public class BukkitEventUtil extends EventUtil { - public Player getPlayer(final PlotPlayer player) { + public Player getPlayer(PlotPlayer player) { if (player instanceof BukkitPlayer) { return ((BukkitPlayer) player).player; } return null; } - public boolean callEvent(final Event event) { + public boolean callEvent(Event event) { Bukkit.getServer().getPluginManager().callEvent(event); return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); } @Override - public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto) { + public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); } @Override - public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot) { + public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); } @Override - public boolean callClear(final Plot plot) { + public boolean callClear(Plot plot) { return callEvent(new PlotClearEvent(plot)); } @Override - public void callDelete(final Plot plot) { + public void callDelete(Plot plot) { callEvent(new PlotDeleteEvent(plot)); } @Override - public boolean callFlagAdd(final Flag flag, final Plot plot) { + public boolean callFlagAdd(Flag flag, Plot plot) { return callEvent(new PlotFlagAddEvent(flag, plot)); } @Override - public boolean callFlagRemove(final Flag flag, final Plot plot) { + public boolean callFlagRemove(Flag flag, Plot plot) { return callEvent(new PlotFlagRemoveEvent(flag, plot)); } @Override - public boolean callMerge(final Plot plot, final ArrayList plots) { + public boolean callMerge(Plot plot, ArrayList plots) { return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getArea().worldname), plot, plots)); } @Override - public boolean callUnlink(final PlotArea area, final ArrayList plots) { + public boolean callUnlink(PlotArea area, ArrayList plots) { return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); } @Override - public void callEntry(final PlotPlayer player, final Plot plot) { + public void callEntry(PlotPlayer player, Plot plot) { callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); } @Override - public void callLeave(final PlotPlayer player, final Plot plot) { + public void callLeave(PlotPlayer player, Plot plot) { callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); } @Override - public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { + public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); } @Override - public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { + public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); } @Override - public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { + public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); } @Override - public boolean callFlagRemove(final Flag flag, final PlotCluster cluster) { + public boolean callFlagRemove(Flag flag, PlotCluster cluster) { return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); } @Override - public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating) { - final PlotRateEvent event = new PlotRateEvent(player, rating, plot); + public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { + PlotRateEvent event = new PlotRateEvent(player, rating, plot); Bukkit.getServer().getPluginManager().callEvent(event); return event.getRating(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java index 0bc8cf713..32b243224 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -49,11 +49,11 @@ public class BukkitHybridUtils extends HybridUtils { } final BiomeGrid nullBiomeGrid = new BiomeGrid() { @Override - public void setBiome(final int a, final int b, final Biome c) { + public void setBiome(int a, int b, Biome c) { } @Override - public Biome getBiome(final int a, final int b) { + public Biome getBiome(int a, int b) { return null; } }; @@ -76,8 +76,8 @@ public class BukkitHybridUtils extends HybridUtils { System.gc(); System.gc(); - final short[][][] oldblocks = new short[256][width][length]; - final short[][][] newblocks = new short[256][width][length]; + final short[][][] oldBlocks = new short[256][width][length]; + final short[][][] newBlocks = new short[256][width][length]; final Runnable run = new Runnable() { @Override @@ -86,38 +86,38 @@ public class BukkitHybridUtils extends HybridUtils { @Override public void run(int[] value) { // [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] - final int X = value[0]; - final int Z = value[1]; - final short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); - final int xb = (X << 4) - bx; - final int zb = (Z << 4) - bz; + int X = value[0]; + int Z = value[1]; + short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); + int xb = (X << 4) - bx; + int zb = (Z << 4) - bz; for (int i = 0; i < result.length; i++) { if (result[i] == null) { for (int j = 0; j < 4096; j++) { - final int x = MainUtil.x_loc[i][j] + xb; + int x = MainUtil.x_loc[i][j] + xb; if (x < 0 || x >= width) { continue; } - final int z = MainUtil.z_loc[i][j] + zb; + int z = MainUtil.z_loc[i][j] + zb; if (z < 0 || z >= length) { continue; } - final int y = MainUtil.y_loc[i][j]; - oldblocks[y][x][z] = 0; + int y = MainUtil.y_loc[i][j]; + oldBlocks[y][x][z] = 0; } continue; } for (int j = 0; j < result[i].length; j++) { - final int x = MainUtil.x_loc[i][j] + xb; + int x = MainUtil.x_loc[i][j] + xb; if (x < 0 || x >= width) { continue; } - final int z = MainUtil.z_loc[i][j] + zb; + int z = MainUtil.z_loc[i][j] + zb; if (z < 0 || z >= length) { continue; } - final int y = MainUtil.y_loc[i][j]; - oldblocks[y][x][z] = result[i][j]; + int y = MainUtil.y_loc[i][j]; + oldBlocks[y][x][z] = result[i][j]; } } @@ -128,19 +128,19 @@ public class BukkitHybridUtils extends HybridUtils { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final int size = width * length; - final int[] changes = new int[size]; - final int[] faces = new int[size]; - final int[] data = new int[size]; - final int[] air = new int[size]; - final int[] variety = new int[size]; + int size = width * length; + int[] changes = new int[size]; + int[] faces = new int[size]; + int[] data = new int[size]; + int[] air = new int[size]; + int[] variety = new int[size]; int i = 0; for (int x = 0; x < width; x++) { for (int z = 0; z < length; z++) { - final HashSet types = new HashSet<>(); + HashSet types = new HashSet<>(); for (int y = 0; y < 256; y++) { - final short old = oldblocks[y][x][z]; - final short now = newblocks[y][x][z]; + short old = oldBlocks[y][x][z]; + short now = newBlocks[y][x][z]; if (old != now) { changes[i]++; } @@ -150,28 +150,28 @@ public class BukkitHybridUtils extends HybridUtils { // check vertices // modifications_adjacent if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) { - if (newblocks[y - 1][x][z] == 0) { + if (newBlocks[y - 1][x][z] == 0) { faces[i]++; } - if (newblocks[y][x - 1][z] == 0) { + if (newBlocks[y][x - 1][z] == 0) { faces[i]++; } - if (newblocks[y][x][z - 1] == 0) { + if (newBlocks[y][x][z - 1] == 0) { faces[i]++; } - if (newblocks[y + 1][x][z] == 0) { + if (newBlocks[y + 1][x][z] == 0) { faces[i]++; } - if (newblocks[y][x + 1][z] == 0) { + if (newBlocks[y][x + 1][z] == 0) { faces[i]++; } - if (newblocks[y][x][z + 1] == 0) { + if (newBlocks[y][x][z + 1] == 0) { faces[i]++; } } - final Material material = Material.getMaterial(now); - final Class md = material.getData(); + Material material = Material.getMaterial(now); + Class md = material.getData(); if (md.equals(Directional.class)) { data[i] += 8; } else if (!md.equals(MaterialData.class)) { @@ -188,7 +188,7 @@ public class BukkitHybridUtils extends HybridUtils { // put in analysis obj // run whenDone - final PlotAnalysis analysis = new PlotAnalysis(); + PlotAnalysis analysis = new PlotAnalysis(); analysis.changes = (int) (MathMan.getMean(changes) * 100); analysis.faces = (int) (MathMan.getMean(faces) * 100); analysis.data = (int) (MathMan.getMean(data) * 100); @@ -217,8 +217,8 @@ public class BukkitHybridUtils extends HybridUtils { @Override public void run(int[] value) { - final int X = value[0]; - final int Z = value[1]; + int X = value[0]; + int Z = value[1]; worldObj.loadChunk(X, Z); int minX; if (X == cbx) { @@ -245,20 +245,20 @@ public class BukkitHybridUtils extends HybridUtils { maxZ = 16; } - final int cbx = X << 4; - final int cbz = Z << 4; + int cbx = X << 4; + int cbz = Z << 4; - final int xb = cbx - bx; - final int zb = cbz - bz; + int xb = cbx - bx; + int zb = cbz - bz; for (int x = minX; x <= maxX; x++) { - final int xx = cbx + x; + int xx = cbx + x; for (int z = minZ; z <= maxZ; z++) { - final int zz = cbz + z; + int zz = cbz + z; for (int y = 0; y < 256; y++) { - final Block block = worldObj.getBlockAt(xx, y, zz); - final int xr = xb + x; - final int zr = zb + z; - newblocks[y][xr][zr] = (short) block.getTypeId(); + Block block = worldObj.getBlockAt(xx, y, zz); + int xr = xb + x; + int zr = zb + z; + newBlocks[y][xr][zr] = (short) block.getTypeId(); } } } @@ -275,17 +275,17 @@ public class BukkitHybridUtils extends HybridUtils { } @Override - public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, - final PlotBlock[] blocks) { - final World world = BukkitUtil.getWorld(worldname); + public int checkModified(String worldname, int x1, int x2, int y1, int y2, int z1, int z2, + PlotBlock[] blocks) { + World world = BukkitUtil.getWorld(worldname); int count = 0; for (int y = y1; y <= y2; y++) { for (int x = x1; x <= x2; x++) { for (int z = z1; z <= z2; z++) { - final Block block = world.getBlockAt(x, y, z); - final int id = block.getTypeId(); + Block block = world.getBlockAt(x, y, z); + int id = block.getTypeId(); boolean same = false; - for (final PlotBlock p : blocks) { + for (PlotBlock p : blocks) { if (id == p.id) { same = true; break; @@ -301,15 +301,15 @@ public class BukkitHybridUtils extends HybridUtils { } @Override - public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) { - final World world = BukkitUtil.getWorld(worldname); - final int maxY = world.getMaxHeight(); + public int get_ey(String worldname, int sx, int ex, int sz, int ez, int sy) { + World world = BukkitUtil.getWorld(worldname); + int maxY = world.getMaxHeight(); int ey = sy; for (int x = sx; x <= ex; x++) { for (int z = sz; z <= ez; z++) { for (int y = sy; y < maxY; y++) { if (y > ey) { - final Block block = world.getBlockAt(x, y, z); + Block block = world.getBlockAt(x, y, z); if (!block.getType().equals(Material.AIR)) { ey = y; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java index 7f5a4e9b6..cd2c12d51 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -19,11 +19,11 @@ import java.util.List; public class BukkitInventoryUtil extends InventoryUtil { - public static ItemStack getItem(final PlotItemStack item) { + public static ItemStack getItem(PlotItemStack item) { if (item == null) { return null; } - final ItemStack stack = new ItemStack(item.id, item.amount, item.data); + ItemStack stack = new ItemStack(item.id, item.amount, item.data); ItemMeta meta = null; if (item.name != null) { meta = stack.getItemMeta(); @@ -33,8 +33,8 @@ public class BukkitInventoryUtil extends InventoryUtil { if (meta == null) { meta = stack.getItemMeta(); } - final List lore = new ArrayList<>(); - for (final String entry : item.lore) { + List lore = new ArrayList<>(); + for (String entry : item.lore) { lore.add(ChatColor.translateAlternateColorCodes('&', entry)); } meta.setLore(lore); @@ -46,12 +46,12 @@ public class BukkitInventoryUtil extends InventoryUtil { } @Override - public void open(final PlotInventory inv) { - final BukkitPlayer bp = (BukkitPlayer) inv.player; - final Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); - final PlotItemStack[] items = inv.getItems(); + public void open(PlotInventory inv) { + BukkitPlayer bp = (BukkitPlayer) inv.player; + Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); + PlotItemStack[] items = inv.getItems(); for (int i = 0; i < inv.size * 9; i++) { - final PlotItemStack item = items[i]; + PlotItemStack item = items[i]; if (item != null) { inventory.setItem(i, getItem(item)); } @@ -61,19 +61,19 @@ public class BukkitInventoryUtil extends InventoryUtil { } @Override - public void close(final PlotInventory inv) { + public void close(PlotInventory inv) { if (!inv.isOpen()) { return; } inv.player.deleteMeta("inventory"); - final BukkitPlayer bp = (BukkitPlayer) inv.player; + BukkitPlayer bp = (BukkitPlayer) inv.player; bp.player.closeInventory(); } @Override - public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) { - final BukkitPlayer bp = (BukkitPlayer) inv.player; - final InventoryView opened = bp.player.getOpenInventory(); + public void setItem(PlotInventory inv, int index, PlotItemStack item) { + BukkitPlayer bp = (BukkitPlayer) inv.player; + InventoryView opened = bp.player.getOpenInventory(); if (!inv.isOpen()) { return; } @@ -81,22 +81,22 @@ public class BukkitInventoryUtil extends InventoryUtil { bp.player.updateInventory(); } - public PlotItemStack getItem(final ItemStack item) { + public PlotItemStack getItem(ItemStack item) { if (item == null) { return null; } - final int id = item.getTypeId(); - final short data = item.getDurability(); - final int amount = item.getAmount(); + int id = item.getTypeId(); + short data = item.getDurability(); + int amount = item.getAmount(); String name = null; String[] lore = null; if (item.hasItemMeta()) { - final ItemMeta meta = item.getItemMeta(); + ItemMeta meta = item.getItemMeta(); if (meta.hasDisplayName()) { name = meta.getDisplayName(); } if (meta.hasLore()) { - final List itemLore = meta.getLore(); + List itemLore = meta.getLore(); lore = itemLore.toArray(new String[itemLore.size()]); } } @@ -104,10 +104,10 @@ public class BukkitInventoryUtil extends InventoryUtil { } @Override - public PlotItemStack[] getItems(final PlotPlayer player) { - final BukkitPlayer bp = (BukkitPlayer) player; - final PlayerInventory inv = bp.player.getInventory(); - final PlotItemStack[] items = new PlotItemStack[36]; + public PlotItemStack[] getItems(PlotPlayer player) { + BukkitPlayer bp = (BukkitPlayer) player; + PlayerInventory inv = bp.player.getInventory(); + PlotItemStack[] items = new PlotItemStack[36]; for (int i = 0; i < 36; i++) { items[i] = getItem(inv.getItem(i)); } @@ -115,12 +115,12 @@ public class BukkitInventoryUtil extends InventoryUtil { } @Override - public boolean isOpen(final PlotInventory inv) { + public boolean isOpen(PlotInventory inv) { if (!inv.isOpen()) { return false; } - final BukkitPlayer bp = (BukkitPlayer) inv.player; - final InventoryView opened = bp.player.getOpenInventory(); + BukkitPlayer bp = (BukkitPlayer) inv.player; + InventoryView opened = bp.player.getOpenInventory(); return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java index 92a192052..e01adf8b3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java @@ -16,35 +16,35 @@ public class BukkitPlainChatManager extends ChatManager> { } @Override - public void color(final PlotMessage m, final String color) { - final List parts = m.$(this); + public void color(PlotMessage m, String color) { + List parts = m.$(this); parts.get(parts.size() - 1).insert(0, color); } @Override - public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { + public void tooltip(PlotMessage m, PlotMessage... tooltips) { } @Override - public void command(final PlotMessage m, final String command) { + public void command(PlotMessage m, String command) { } @Override - public void text(final PlotMessage m, final String text) { + public void text(PlotMessage m, String text) { m.$(this).add(new StringBuilder(ChatColor.stripColor(text))); } @Override - public void send(final PlotMessage m, final PlotPlayer player) { - final StringBuilder built = new StringBuilder(); - for (final StringBuilder sb : m.$(this)) { + public void send(PlotMessage m, PlotPlayer player) { + StringBuilder built = new StringBuilder(); + for (StringBuilder sb : m.$(this)) { built.append(sb); } player.sendMessage(built.toString()); } @Override - public void suggest(final PlotMessage m, final String command) { + public void suggest(PlotMessage m, String command) { } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java index 1b07ba7d7..ab509031a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java @@ -50,10 +50,7 @@ import java.util.Map.Entry; import java.util.Set; /** - * Schematic Handler - * - - + * Schematic Handler. */ public class BukkitSchematicHandler extends SchematicHandler { @@ -66,10 +63,10 @@ public class BukkitSchematicHandler extends SchematicHandler { // Main positions Location[] corners = MainUtil.getCorners(world, regions); final Location bot = corners[0]; - final Location top = corners[1]; + Location top = corners[1]; final int width = (top.getX() - bot.getX()) + 1; - final int height = (top.getY() - bot.getY()) + 1; + int height = (top.getY() - bot.getY()) + 1; final int length = (top.getZ() - bot.getZ()) + 1; // Main Schematic tag final HashMap schematic = new HashMap<>(); @@ -136,16 +133,16 @@ public class BukkitSchematicHandler extends SchematicHandler { TaskManager.runTask(new Runnable() { @Override public void run() { - final long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); while (!chunks.isEmpty() && ((System.currentTimeMillis() - start) < 20)) { // save schematics - final ChunkLoc chunk = chunks.remove(0); - final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); + ChunkLoc chunk = chunks.remove(0); + Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); if (!bc.load(false)) { continue; } - final int X = chunk.x; - final int Z = chunk.z; + int X = chunk.x; + int Z = chunk.z; int xxb = X << 4; int zzb = Z << 4; int xxt = xxb + 15; @@ -164,16 +161,16 @@ public class BukkitSchematicHandler extends SchematicHandler { zzt = p2z; } for (int y = sy; y <= Math.min(255, ey); y++) { - final int ry = y - sy; - final int i1 = ry * width * length; + int ry = y - sy; + int i1 = ry * width * length; for (int z = zzb; z <= zzt; z++) { - final int rz = z - bz; - final int i2 = i1 + (rz * width); + int rz = z - bz; + int i2 = i1 + (rz * width); for (int x = xxb; x <= xxt; x++) { - final int rx = x - bx; - final int index = i2 + rx; - final Block block = worldObj.getBlockAt(x, y, z); - final int id = block.getTypeId(); + int rx = x - bx; + int index = i2 + rx; + Block block = worldObj.getBlockAt(x, y, z); + int id = block.getTypeId(); switch (id) { case 0: case 2: @@ -281,13 +278,13 @@ public class BukkitSchematicHandler extends SchematicHandler { case 151: case 178: { // TODO implement fully - final BlockState state = block.getState(); + BlockState state = block.getState(); if (state != null) { - final StateWrapper wrapper = new StateWrapper(state); - final CompoundTag rawTag = wrapper.getTag(); + StateWrapper wrapper = new StateWrapper(state); + CompoundTag rawTag = wrapper.getTag(); if (rawTag != null) { - final Map values = new HashMap<>(); - for (final Entry entry : rawTag.getValue().entrySet()) { + Map values = new HashMap<>(); + for (Entry entry : rawTag.getValue().entrySet()) { values.put(entry.getKey(), entry.getValue()); } values.put("id", new StringTag("id", wrapper.getId())); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java index 03a29b9d4..818520af4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -29,13 +29,13 @@ public class BukkitSetupUtils extends SetupUtils { if (!SetupUtils.generators.isEmpty()) { return; } - final String testWorld = "CheckingPlotSquaredGenerator"; - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + String testWorld = "CheckingPlotSquaredGenerator"; + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (plugin.isEnabled()) { - final ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, ""); + ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, ""); if (generator != null) { PS.get().removePlotAreas(testWorld); - final String name = plugin.getDescription().getName(); + String name = plugin.getDescription().getName(); GeneratorWrapper wrapped; if (generator instanceof GeneratorWrapper) { wrapped = (GeneratorWrapper) generator; @@ -49,10 +49,10 @@ public class BukkitSetupUtils extends SetupUtils { } @Override - public String setupWorld(final SetupObject object) { + public String setupWorld(SetupObject object) { SetupUtils.manager.updateGenerators(); ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step; - final String world = object.world; + String world = object.world; int type = object.type; String worldPath = "worlds." + object.world; if (!PS.get().config.contains(worldPath)) { @@ -69,7 +69,7 @@ public class BukkitSetupUtils extends SetupUtils { } ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath); HashMap options = new HashMap<>(); - for (final ConfigurationNode step : steps) { + for (ConfigurationNode step : steps) { options.put(step.getConstant(), step.getValue()); } options.put("generator.type", object.type); @@ -98,7 +98,7 @@ public class BukkitSetupUtils extends SetupUtils { break; } case 1: { - for (final ConfigurationNode step : steps) { + for (ConfigurationNode step : steps) { worldSection.set(step.getConstant(), step.getValue()); } PS.get().config.set("worlds." + world + "." + "generator.type", object.type); @@ -114,7 +114,7 @@ public class BukkitSetupUtils extends SetupUtils { break; } case 0: { - for (final ConfigurationNode step : steps) { + for (ConfigurationNode step : steps) { worldSection.set(step.getConstant(), step.getValue()); } break; @@ -122,7 +122,7 @@ public class BukkitSetupUtils extends SetupUtils { } try { PS.get().config.save(PS.get().configFile); - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); } if (object.setupGenerator != null) { @@ -142,7 +142,7 @@ public class BukkitSetupUtils extends SetupUtils { return world; } } - final WorldCreator wc = new WorldCreator(object.world); + WorldCreator wc = new WorldCreator(object.world); wc.generator(object.setupGenerator); wc.environment(Environment.NORMAL); Bukkit.createWorld(wc); @@ -166,34 +166,34 @@ public class BukkitSetupUtils extends SetupUtils { return object.world; } - public void setGenerator(final String world, final String generator) { - if ((Bukkit.getWorlds().isEmpty()) || !Bukkit.getWorlds().get(0).getName().equals(world)) { + public void setGenerator(String world, String generator) { + if (Bukkit.getWorlds().isEmpty() || !Bukkit.getWorlds().get(0).getName().equals(world)) { return; } - final File file = new File("bukkit.yml").getAbsoluteFile(); - final YamlConfiguration yml = YamlConfiguration.loadConfiguration(file); + File file = new File("bukkit.yml").getAbsoluteFile(); + YamlConfiguration yml = YamlConfiguration.loadConfiguration(file); yml.set("worlds." + world + ".generator", generator); try { yml.save(file); - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @Override - public String getGenerator(final PlotArea plotworld) { + public String getGenerator(PlotArea plotworld) { if (SetupUtils.generators.isEmpty()) { updateGenerators(); } - final World world = Bukkit.getWorld(plotworld.worldname); + World world = Bukkit.getWorld(plotworld.worldname); if (world == null) { return null; } - final ChunkGenerator generator = world.getGenerator(); + ChunkGenerator generator = world.getGenerator(); if (!(generator instanceof BukkitPlotGenerator)) { return null; } - for (final Entry> entry : generators.entrySet()) { + for (Entry> entry : generators.entrySet()) { GeneratorWrapper current = entry.getValue(); if (current.equals(generator)) { return entry.getKey(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java index e3b2dfb91..1d8292882 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java @@ -7,37 +7,38 @@ import org.bukkit.Bukkit; public class BukkitTaskManager extends TaskManager { @Override - public int taskRepeat(final Runnable r, final int interval) { + public int taskRepeat(Runnable r, int interval) { return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval); } - @SuppressWarnings("deprecation") @Override - public int taskRepeatAsync(final Runnable r, final int interval) { + @SuppressWarnings("deprecation") + @Override + public int taskRepeatAsync(Runnable r, int interval) { return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval); } @Override - public void taskAsync(final Runnable r) { + public void taskAsync(Runnable r) { BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId(); } @Override - public void task(final Runnable r) { + public void task(Runnable r) { BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId(); } @Override - public void taskLater(final Runnable r, final int delay) { + public void taskLater(Runnable r, int delay) { BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId(); } @Override - public void taskLaterAsync(final Runnable r, final int delay) { + public void taskLaterAsync(Runnable r, int delay) { BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay); } @Override - public void cancelTask(final int task) { + public void cancelTask(int task) { if (task != -1) { Bukkit.getScheduler().cancelTask(task); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 53c2fb330..da9bdd4b8 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -31,6 +31,7 @@ import org.bukkit.material.Step; import org.bukkit.material.Tree; import org.bukkit.material.WoodenStep; import org.bukkit.material.Wool; + import java.util.Arrays; import java.util.List; @@ -42,26 +43,26 @@ public class BukkitUtil extends WorldUtil { private static Player lastPlayer = null; private static PlotPlayer lastPlotPlayer = null; - public static void removePlayer(final String plr) { + public static void removePlayer(String plr) { lastPlayer = null; lastPlotPlayer = null; } - public static PlotPlayer getPlayer(final OfflinePlayer op) { + public static PlotPlayer getPlayer(OfflinePlayer op) { if (op.isOnline()) { return getPlayer(op.getPlayer()); } - final Player player = OfflinePlayerUtil.loadPlayer(op); + Player player = OfflinePlayerUtil.loadPlayer(op); player.loadData(); return new BukkitPlayer(player, true); } - public static PlotPlayer getPlayer(final Player player) { + public static PlotPlayer getPlayer(Player player) { if (player == lastPlayer) { return lastPlotPlayer; } - final String name = player.getName(); - final PlotPlayer pp = UUIDHandler.getPlayer(name); + String name = player.getName(); + PlotPlayer pp = UUIDHandler.getPlayer(name); if (pp != null) { return pp; } @@ -71,63 +72,64 @@ public class BukkitUtil extends WorldUtil { return lastPlotPlayer; } - public static Location getLocation(final org.bukkit.Location loc) { - return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ())); + public static Location getLocation(org.bukkit.Location location) { + return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ())); } - public static org.bukkit.Location getLocation(final Location loc) { - return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()); + public static org.bukkit.Location getLocation(Location location) { + return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()); } - public static World getWorld(final String string) { + public static World getWorld(String string) { if (StringMan.isEqual(string, lastString)) { if (lastWorld != null) { return lastWorld; } } - final World world = Bukkit.getWorld(string); + World world = Bukkit.getWorld(string); lastString = string; lastWorld = world; return world; } - public static String getWorld(final Entity entity) { + public static String getWorld(Entity entity) { return entity.getWorld().getName(); } - public static List getEntities(final String worldname) { + public static List getEntities(String worldname) { return getWorld(worldname).getEntities(); } - public static Location getLocation(final Entity entity) { - final org.bukkit.Location loc = entity.getLocation(); - final String world = loc.getWorld().getName(); + public static Location getLocation(Entity entity) { + org.bukkit.Location loc = entity.getLocation(); + String world = loc.getWorld().getName(); return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } - public static Location getLocationFull(final Entity entity) { - final org.bukkit.Location loc = entity.getLocation(); + public static Location getLocationFull(Entity entity) { + org.bukkit.Location loc = entity.getLocation(); return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()), loc.getYaw(), loc.getPitch()); } @Override - public boolean isWorld(final String world) { + public boolean isWorld(String world) { return getWorld(world) != null; } @Override - public String getBiome(final String world, final int x, final int z) { + public String getBiome(String world, int x, int z) { return getWorld(world).getBiome(x, z).name(); } @Override - public void setSign(final String worldname, final int x, final int y, final int z, final String[] lines) { - final World world = getWorld(worldname); - final Block block = world.getBlockAt(x, y, z); + public void setSign(String worldname, int x, int y, int z, String[] lines) { + World world = getWorld(worldname); + Block block = world.getBlockAt(x, y, z); // block.setType(Material.AIR); block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); - final BlockState blockstate = block.getState(); + BlockState blockstate = block.getState(); if (blockstate instanceof Sign) { final Sign sign = (Sign) blockstate; for (int i = 0; i < lines.length; i++) { @@ -144,11 +146,11 @@ public class BukkitUtil extends WorldUtil { } @Override - public String[] getSign(final Location loc) { - final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ()); + public String[] getSign(Location location) { + Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ()); if (block != null) { if (block.getState() instanceof Sign) { - final Sign sign = (Sign) block.getState(); + Sign sign = (Sign) block.getState(); return sign.getLines(); } } @@ -156,16 +158,16 @@ public class BukkitUtil extends WorldUtil { } @Override - public Location getSpawn(final String world) { - final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); + public Location getSpawn(String world) { + org.bukkit.Location temp = getWorld(world).getSpawnLocation(); return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); } @Override - public void setSpawn(Location loc) { - World world = getWorld(loc.getWorld()); + public void setSpawn(Location location) { + World world = getWorld(location.getWorld()); if (world != null) { - world.setSpawnLocation(loc.getX(), loc.getY(), loc.getZ()); + world.setSpawnLocation(location.getX(), location.getY(), location.getZ()); } } @@ -178,24 +180,24 @@ public class BukkitUtil extends WorldUtil { } @Override - public int getHighestBlock(final String world, final int x, final int z) { + public int getHighestBlock(String world, int x, int z) { return getWorld(world).getHighestBlockAt(x, z).getY(); } @Override - public int getBiomeFromString(final String biomeStr) { + public int getBiomeFromString(String biomeStr) { try { - final Biome biome = Biome.valueOf(biomeStr.toUpperCase()); + Biome biome = Biome.valueOf(biomeStr.toUpperCase()); return Arrays.asList(Biome.values()).indexOf(biome); - } catch (final IllegalArgumentException e) { + } catch (IllegalArgumentException e) { return -1; } } @Override public String[] getBiomeList() { - final Biome[] biomes = Biome.values(); - final String[] list = new String[biomes.length]; + Biome[] biomes = Biome.values(); + String[] list = new String[biomes.length]; for (int i = 0; i < biomes.length; i++) { list[i] = biomes[i].name(); } @@ -203,18 +205,18 @@ public class BukkitUtil extends WorldUtil { } @Override - public boolean addItems(final String worldname, final PlotItem items) { - final World world = getWorld(worldname); - final Block block = world.getBlockAt(items.x, items.y, items.z); + public boolean addItems(String worldName, PlotItem items) { + World world = getWorld(worldName); + Block block = world.getBlockAt(items.x, items.y, items.z); if (block == null) { return false; } - final BlockState state = block.getState(); + BlockState state = block.getState(); if (state instanceof InventoryHolder) { - final InventoryHolder holder = (InventoryHolder) state; - final Inventory inv = holder.getInventory(); + InventoryHolder holder = (InventoryHolder) state; + Inventory inv = holder.getInventory(); for (int i = 0; i < items.id.length; i++) { - final ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]); + ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]); inv.addItem(item); } state.update(true); @@ -224,11 +226,11 @@ public class BukkitUtil extends WorldUtil { } @Override - public boolean isBlockSolid(final PlotBlock block) { + public boolean isBlockSolid(PlotBlock block) { try { - final Material material = Material.getMaterial(block.id); + Material material = Material.getMaterial(block.id); if (material.isBlock() && material.isSolid() && !material.hasGravity()) { - final Class data = material.getData(); + Class data = material.getData(); if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding() || data.equals(Tree.class) || data.equals(Sandstone.class) @@ -245,16 +247,16 @@ public class BukkitUtil extends WorldUtil { } } return false; - } catch (final Exception e) { + } catch (Exception e) { return false; } } @Override - public String getClosestMatchingName(final PlotBlock block) { + public String getClosestMatchingName(PlotBlock block) { try { return Material.getMaterial(block.id).name(); - } catch (final Exception e) { + } catch (Exception e) { return null; } } @@ -262,13 +264,14 @@ public class BukkitUtil extends WorldUtil { @Override public StringComparison.ComparisonResult getClosestBlock(String name) { try { - final Material material = Material.valueOf(name.toUpperCase()); + Material material = Material.valueOf(name.toUpperCase()); return new StringComparison().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0)); } catch (IllegalArgumentException e) { + //ignored } try { byte data; - final String[] split = name.split(":"); + String[] split = name.split(":"); if (split.length == 2) { data = Byte.parseByte(split[1]); name = split[0]; @@ -281,23 +284,24 @@ public class BukkitUtil extends WorldUtil { id = Short.parseShort(split[0]); match = 0; } else { - final StringComparison.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); + StringComparison.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); match = comparison.match; id = (short) comparison.best.getId(); } - final PlotBlock block = new PlotBlock(id, data); - final StringComparison outer = new StringComparison<>(); + PlotBlock block = new PlotBlock(id, data); + StringComparison outer = new StringComparison<>(); return outer.new ComparisonResult(match, block); } catch (NumberFormatException e) { + //ignored } return null; } @Override - public void setBiomes(final String worldname, RegionWrapper region, final String biomeStr) { - final World world = getWorld(worldname); - final Biome biome = Biome.valueOf(biomeStr.toUpperCase()); + public void setBiomes(String worldName, RegionWrapper region, String biomeStr) { + World world = getWorld(worldName); + Biome biome = Biome.valueOf(biomeStr.toUpperCase()); for (int x = region.minX; x <= region.maxX; x++) { for (int z = region.minZ; z <= region.maxZ; z++) { world.setBiome(x, z, biome); @@ -306,9 +310,9 @@ public class BukkitUtil extends WorldUtil { } @Override - public PlotBlock getBlock(final Location loc) { - final World world = getWorld(loc.getWorld()); - final Block block = world.getBlockAt(loc.getX(), loc.getY(), loc.getZ()); + public PlotBlock getBlock(Location location) { + World world = getWorld(location.getWorld()); + Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ()); if (block == null) { return PlotBlock.EVERYTHING; } 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 96fa1fc22..9cb43a190 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java @@ -27,13 +27,24 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.scheduler.BukkitTask; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; @@ -76,13 +87,13 @@ public class Metrics { */ private volatile BukkitTask task = null; - public Metrics(final Plugin plugin) throws IOException { + public Metrics(Plugin plugin) throws IOException { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } this.plugin = plugin; - guid = UUID.randomUUID().toString(); - debug = false; + this.guid = UUID.randomUUID().toString(); + this.debug = false; } /** @@ -92,19 +103,19 @@ public class Metrics { * * @return byte[] the file as a byte array */ - public static byte[] gzip(final String input) { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + public static byte[] gzip(String input) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); } finally { if (gzos != null) { try { gzos.close(); - } catch (final IOException ignore) { + } catch (IOException ignore) { } } } @@ -120,14 +131,14 @@ public class Metrics { * * @throws UnsupportedEncodingException */ - private static void appendJSONPair(final StringBuilder json, final String key, final String value) { + private static void appendJSONPair(StringBuilder json, String key, String value) { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { @@ -149,11 +160,11 @@ public class Metrics { * * @return String */ - private static String escapeJSON(final String text) { - final StringBuilder builder = new StringBuilder(); + private static String escapeJSON(String text) { + StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { - final char chr = text.charAt(index); + char chr = text.charAt(index); switch (chr) { case '"': case '\\': @@ -174,7 +185,7 @@ public class Metrics { break; default: if (chr < ' ') { - final String t = "000" + Integer.toHexString(chr); + String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); @@ -193,7 +204,7 @@ public class Metrics { * * @return the encoded text, as UTF-8 */ - private static String urlEncode(final String text) throws UnsupportedEncodingException { + private static String urlEncode(String text) throws UnsupportedEncodingException { return URLEncoder.encode(text, "UTF-8"); } @@ -205,14 +216,14 @@ public class Metrics { * * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given */ - public Graph createGraph(final String name) { + public Graph createGraph(String name) { if (name == null) { throw new IllegalArgumentException("Graph name cannot be null"); } // Construct the graph object - final Graph graph = new Graph(name); + Graph graph = new Graph(name); // Now we can add our graph - graphs.add(graph); + this.graphs.add(graph); // and return back return graph; } @@ -222,11 +233,11 @@ public class Metrics { * * @param graph The name of the graph */ - public void addGraph(final Graph graph) { + public void addGraph(Graph graph) { if (graph == null) { throw new IllegalArgumentException("Graph cannot be null"); } - graphs.add(graph); + this.graphs.add(graph); } /** @@ -238,24 +249,24 @@ public class Metrics { */ public boolean start() { // Is metrics already running? - if (task != null) { + if (this.task != null) { return true; } // Begin hitting the server with glorious data - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { + this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { private boolean firstPost = true; @Override public void run() { try { - postPlugin(!firstPost); + postPlugin(!this.firstPost); // After the first post we set firstPost to // false // Each post thereafter will be a ping - firstPost = false; - } catch (final IOException e) { + this.firstPost = false; + } catch (IOException e) { e.printStackTrace(); - if (debug) { + if (Metrics.this.debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } @@ -271,7 +282,7 @@ public class Metrics { */ public void enable() throws IOException { // Enable Task, if it is not running - if (task == null) { + if (this.task == null) { start(); } } @@ -283,9 +294,9 @@ public class Metrics { */ public void disable() throws IOException { // Disable Task, if it is running - if (task != null) { - task.cancel(); - task = null; + if (this.task != null) { + this.task.cancel(); + this.task = null; } } @@ -301,7 +312,7 @@ public class Metrics { // plugin.getDataFolder() => base/plugins/PluginA/ // pluginsFolder => base/plugins/ // The base is not necessarily relative to the startup directory. - final File pluginsFolder = plugin.getDataFolder().getParentFile(); + File pluginsFolder = this.plugin.getDataFolder().getParentFile(); // return => base/plugins/PluginMetrics/config.yml return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); } @@ -309,18 +320,13 @@ public class Metrics { /** * Generic method that posts a plugin to the metrics website */ - private void postPlugin(final boolean isPing) throws IOException { + private void postPlugin(boolean isPing) throws IOException { // Server software specific section - final PluginDescriptionFile description = plugin.getDescription(); - final String pluginName = description.getName(); - final boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE - // if - // online - // mode - // is - // enabled - final String pluginVersion = description.getVersion(); - final String serverVersion = Bukkit.getVersion(); + PluginDescriptionFile description = this.plugin.getDescription(); + String pluginName = description.getName(); + boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled + String pluginVersion = description.getVersion(); + String serverVersion = Bukkit.getVersion(); int playersOnline = 0; try { if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() == Collection.class) { @@ -334,20 +340,19 @@ public class Metrics { // END server software specific section -- all code below does not use // any code outside of this class / Java // Construct the post data - final StringBuilder json = new StringBuilder(1024); + StringBuilder json = new StringBuilder(1024); json.append('{'); - // The plugin's description file containg all of the plugin data such as - // name, version, author, etc - appendJSONPair(json, "guid", guid); + // The plugin's description file containg all of the plugin data such as name, version, author, etc + appendJSONPair(json, "guid", this.guid); appendJSONPair(json, "plugin_version", pluginVersion); appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "players_online", Integer.toString(playersOnline)); // New data as of R6 - final String osname = System.getProperty("os.name"); + String osname = System.getProperty("os.name"); String osarch = System.getProperty("os.arch"); - final String osversion = System.getProperty("os.version"); - final String java_version = System.getProperty("java.version"); - final int coreCount = Runtime.getRuntime().availableProcessors(); + String osversion = System.getProperty("os.version"); + String java_version = System.getProperty("java.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); // normalize os arch .. amd64 -> x86_64 if (osarch.equals("amd64")) { osarch = "x86_64"; @@ -362,8 +367,8 @@ public class Metrics { if (isPing) { appendJSONPair(json, "ping", "1"); } - if (!graphs.isEmpty()) { - synchronized (graphs) { + if (!this.graphs.isEmpty()) { + synchronized (this.graphs) { json.append(','); json.append('"'); json.append("graphs"); @@ -371,10 +376,10 @@ public class Metrics { json.append(':'); json.append('{'); boolean firstGraph = true; - for (final Graph graph : graphs) { - final StringBuilder graphJson = new StringBuilder(); + for (Graph graph : this.graphs) { + StringBuilder graphJson = new StringBuilder(); graphJson.append('{'); - for (final Plotter plotter : graph.getPlotters()) { + for (Plotter plotter : graph.getPlotters()) { appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); } graphJson.append('}'); @@ -392,7 +397,7 @@ public class Metrics { // close json json.append('}'); // Create the url - final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); + URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it @@ -402,8 +407,8 @@ public class Metrics { } else { connection = url.openConnection(); } - final byte[] uncompressed = json.toString().getBytes(); - final byte[] compressed = gzip(json.toString()); + byte[] uncompressed = json.toString().getBytes(); + byte[] compressed = gzip(json.toString()); // Headers connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("Content-Type", "application/json"); @@ -412,7 +417,7 @@ public class Metrics { connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.setDoOutput(true); - if (debug) { + if (this.debug) { PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); } try { @@ -423,7 +428,7 @@ public class Metrics { String response; try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { response = reader.readLine(); - if (debug) { + if (this.debug) { PS.debug("[Metrics] Response for " + pluginName + ": " + response); } } @@ -437,18 +442,17 @@ public class Metrics { } else { // Is this the first update this hour? if ("1".equals(response) || response.contains("This is your first update this hour")) { - synchronized (graphs) { - for (final Graph graph : graphs) { - for (final Plotter plotter : graph.getPlotters()) { + synchronized (this.graphs) { + for (Graph graph : this.graphs) { + for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } - } - catch (Exception e) { - if (debug) { + } catch (Exception e) { + if (this.debug) { e.printStackTrace(); } } @@ -483,7 +487,7 @@ public class Metrics { */ private final Set plotters = new LinkedHashSet<>(); - private Graph(final String name) { + private Graph(String name) { this.name = name; } @@ -493,7 +497,7 @@ public class Metrics { * @return the Graph's name */ public String getName() { - return name; + return this.name; } /** @@ -501,8 +505,8 @@ public class Metrics { * * @param plotter the plotter to add to the graph */ - public void addPlotter(final Plotter plotter) { - plotters.add(plotter); + public void addPlotter(Plotter plotter) { + this.plotters.add(plotter); } /** @@ -510,8 +514,8 @@ public class Metrics { * * @param plotter the plotter to remove from the graph */ - public void removePlotter(final Plotter plotter) { - plotters.remove(plotter); + public void removePlotter(Plotter plotter) { + this.plotters.remove(plotter); } /** @@ -520,21 +524,21 @@ public class Metrics { * @return an unmodifiable {@link java.util.Set} of the plotter objects */ public Set getPlotters() { - return Collections.unmodifiableSet(plotters); + return Collections.unmodifiableSet(this.plotters); } @Override public int hashCode() { - return name.hashCode(); + return this.name.hashCode(); } @Override - public boolean equals(final Object object) { + public boolean equals(Object object) { if (!(object instanceof Graph)) { return false; } - final Graph graph = (Graph) object; - return graph.name.equals(name); + Graph graph = (Graph) object; + return graph.name.equals(this.name); } /** @@ -547,7 +551,7 @@ public class Metrics { /** * Interface used to collect custom data for a plugin */ - public static abstract class Plotter { + public abstract static class Plotter { /** * The plot's name @@ -566,7 +570,7 @@ public class Metrics { * * @param name the name of the plotter to use, which will show up on the website */ - public Plotter(final String name) { + public Plotter(String name) { this.name = name; } @@ -585,7 +589,7 @@ public class Metrics { * @return the plotted point's column name */ public String getColumnName() { - return name; + return this.name; } /** @@ -600,12 +604,12 @@ public class Metrics { } @Override - public boolean equals(final Object object) { + public boolean equals(Object object) { if (!(object instanceof Plotter)) { return false; } - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); + Plotter plotter = (Plotter) object; + return plotter.name.equals(this.name) && plotter.getValue() == getValue(); } } } \ No newline at end of file diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java index fa9207b62..09a99dabf 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java @@ -15,12 +15,27 @@ import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.*; +import java.util.AbstractList; +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -48,39 +63,43 @@ public class NbtFactory { // Loading/saving compounds private LoadCompoundMethod LOAD_COMPOUND; private Method SAVE_COMPOUND; + /** * Construct an instance of the NBT factory by deducing the class of NBTBase. */ private NbtFactory() { - if (BASE_CLASS == null) { + if (this.BASE_CLASS == null) { try { // Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing // with CraftBukkit or its derivatives. This does not work in MCPC+ however. - final ClassLoader loader = NbtFactory.class.getClassLoader(); + ClassLoader loader = NbtFactory.class.getClassLoader(); - final String packageName = getPackageName(); - final Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); + String packageName = getPackageName(); + Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); // Prepare NBT - COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); - BASE_CLASS = COMPOUND_CLASS.getSuperclass(); - NBT_GET_TYPE = getMethod(0, Modifier.STATIC, BASE_CLASS, "getTypeId"); - NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, BASE_CLASS, "createTag", byte.class); + this.COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); + this.BASE_CLASS = this.COMPOUND_CLASS.getSuperclass(); + this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId"); + this.NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class); // Prepare CraftItemStack - CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); - CRAFT_HANDLE = getField(null, CRAFT_STACK, "handle"); - STACK_TAG = getField(null, CRAFT_HANDLE.getType(), "tag"); + this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); + this.CRAFT_HANDLE = getField(null, this.CRAFT_STACK, "handle"); + this.STACK_TAG = getField(null, this.CRAFT_HANDLE.getType(), "tag"); // Loading/saving - final String nmsPackage = BASE_CLASS.getPackage().getName(); + String nmsPackage = this.BASE_CLASS.getPackage().getName(); initializeNMS(loader, nmsPackage); - LOAD_COMPOUND = READ_LIMITER_CLASS != null ? new LoadMethodSkinUpdate(STREAM_TOOLS, READ_LIMITER_CLASS) : - new LoadMethodWorldUpdate(STREAM_TOOLS); - SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, STREAM_TOOLS, null, BASE_CLASS, DataOutput.class); + if (this.READ_LIMITER_CLASS != null) { + this.LOAD_COMPOUND = new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS); + } else { + this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS); + } + this.SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class); - } catch (final ClassNotFoundException e) { + } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to find offline player.", e); } } @@ -101,7 +120,7 @@ public class NbtFactory { * Construct a new NBT list of an unspecified type. * @return The NBT list. */ - public static NbtList createList(final Object... content) { + public static NbtList createList(Object... content) { return createList(Arrays.asList(content)); } @@ -109,11 +128,11 @@ public class NbtFactory { * Construct a new NBT list of an unspecified type. * @return The NBT list. */ - public static NbtList createList(final Iterable iterable) { - final NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); + public static NbtList createList(Iterable iterable) { + NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); // Add the content as well - for (final Object obj : iterable) { + for (Object obj : iterable) { list.add(obj); } return list; @@ -121,7 +140,6 @@ public class NbtFactory { /** * Construct a new NBT compound. - *

* * @return The NBT compound. */ @@ -134,29 +152,33 @@ public class NbtFactory { * @param nmsList - the NBT list. * @return The wrapper. */ - public static NbtList fromList(final Object nmsList) { + public static NbtList fromList(Object nmsList) { return get().new NbtList(nmsList); } /** * Load the content of a file from a stream. - *

+ * * Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file. * @param stream - the stream supplier. * @param option - whether or not to decompress the input stream. * @return The decoded NBT compound. * @throws IOException If anything went wrong. */ - public static NbtCompound fromStream(final InputSupplier stream, final StreamOptions option) throws IOException { + public static NbtCompound fromStream(InputSupplier stream, StreamOptions option) throws IOException { InputStream input = null; DataInputStream data = null; boolean suppress = true; try { input = stream.getInput(); - data = new DataInputStream(new BufferedInputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input)); + if (option == StreamOptions.GZIP_COMPRESSION) { + data = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input))); + } else { + data = new DataInputStream(new BufferedInputStream(input)); + } - final NbtCompound result = fromCompound(get().LOAD_COMPOUND.loadNbt(data)); + NbtCompound result = fromCompound(get().LOAD_COMPOUND.loadNbt(data)); suppress = false; return result; @@ -171,14 +193,14 @@ public class NbtFactory { /** * Save the content of a NBT compound to a stream. - *

+ * * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. * @param source - the NBT compound to save. * @param stream - the stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public static void saveStream(final NbtCompound source, final ByteSink stream, final StreamOptions option) throws IOException { + public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException { OutputStream output = null; DataOutputStream data = null; boolean suppress = true; @@ -204,7 +226,7 @@ public class NbtFactory { * @param nmsCompound - the NBT compund. * @return The wrapper. */ - public static NbtCompound fromCompound(final Object nmsCompound) { + public static NbtCompound fromCompound(Object nmsCompound) { return get().new NbtCompound(nmsCompound); } @@ -215,9 +237,9 @@ public class NbtFactory { * @param compound - the new NBT compound, or NULL to remove it. * @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air. */ - public static void setItemTag(final ItemStack stack, final NbtCompound compound) { + public static void setItemTag(ItemStack stack, NbtCompound compound) { checkItemStack(stack); - final Object nms = getFieldValue(get().CRAFT_HANDLE, stack); + Object nms = getFieldValue(get().CRAFT_HANDLE, stack); // Now update the tag compound setFieldValue(get().STACK_TAG, nms, compound.getHandle()); @@ -232,14 +254,14 @@ public class NbtFactory { * @param stack - the item stack. * @return A wrapper for its NBT tag. */ - public static NbtCompound fromItemTag(final ItemStack stack) { + public static NbtCompound fromItemTag(ItemStack stack) { checkItemStack(stack); - final Object nms = getFieldValue(get().CRAFT_HANDLE, stack); - final Object tag = getFieldValue(get().STACK_TAG, nms); + Object nms = getFieldValue(get().CRAFT_HANDLE, stack); + Object tag = getFieldValue(get().STACK_TAG, nms); // Create the tag if it doesn't exist if (tag == null) { - final NbtCompound compound = createCompound(); + NbtCompound compound = createCompound(); setItemTag(stack, compound); return compound; } @@ -251,17 +273,17 @@ public class NbtFactory { * @param stack - the stack to convert. * @return The CraftItemStack version. */ - public static ItemStack getCraftItemStack(final ItemStack stack) { + public static ItemStack getCraftItemStack(ItemStack stack) { // Any need to convert? if ((stack == null) || get().CRAFT_STACK.isAssignableFrom(stack.getClass())) { return stack; } try { // Call the private constructor - final Constructor caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class); + Constructor caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class); caller.setAccessible(true); return (ItemStack) caller.newInstance(stack); - } catch (final Exception e) { + } catch (Exception e) { throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); } } @@ -270,7 +292,7 @@ public class NbtFactory { * Ensure that the given stack can store arbitrary NBT information. * @param stack - the stack to check. */ - private static void checkItemStack(final ItemStack stack) { + private static void checkItemStack(ItemStack stack) { if (stack == null) { throw new IllegalArgumentException("Stack cannot be NULL."); } @@ -289,26 +311,26 @@ public class NbtFactory { * @param params - the parameters to supply. * @return The result of the method. */ - private static Object invokeMethod(final Method method, final Object target, final Object... params) { + private static Object invokeMethod(Method method, Object target, Object... params) { try { return method.invoke(target, params); - } catch (final Exception e) { + } catch (Exception e) { throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); } } - private static void setFieldValue(final Field field, final Object target, final Object value) { + private static void setFieldValue(Field field, Object target, Object value) { try { field.set(target, value); - } catch (final Exception e) { + } catch (Exception e) { throw new RuntimeException("Unable to set " + field + " for " + target, e); } } - private static Object getFieldValue(final Field field, final Object target) { + private static Object getFieldValue(Field field, Object target) { try { return field.get(target); - } catch (final Exception e) { + } catch (Exception e) { throw new RuntimeException("Unable to retrieve " + field + " for " + target, e); } } @@ -323,9 +345,9 @@ public class NbtFactory { * @return The first method by this name. * @throws IllegalStateException If we cannot find this method. */ - private static Method getMethod(final int requireMod, final int bannedMod, final Class clazz, final String methodName, - final Class... params) { - for (final Method method : clazz.getDeclaredMethods()) { + private static Method getMethod(int requireMod, int bannedMod, Class clazz, String methodName, + Class... params) { + for (Method method : clazz.getDeclaredMethods()) { // Limitation: Doesn't handle overloads if (((method.getModifiers() & requireMod) == requireMod) && ((method.getModifiers() & bannedMod) == 0) @@ -351,12 +373,12 @@ public class NbtFactory { * @return The first field by this name. * @throws IllegalStateException If we cannot find this field. */ - private static Field getField(final Object instance, Class clazz, final String fieldName) { + private static Field getField(Object instance, Class clazz, String fieldName) { if (clazz == null) { clazz = instance.getClass(); } // Ignore access rules - for (final Field field : clazz.getDeclaredFields()) { + for (Field field : clazz.getDeclaredFields()) { if (field.getName().equals(fieldName)) { field.setAccessible(true); return field; @@ -369,18 +391,18 @@ public class NbtFactory { throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); } - private void initializeNMS(final ClassLoader loader, final String nmsPackage) { + private void initializeNMS(ClassLoader loader, String nmsPackage) { try { - STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); - READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); - } catch (final ClassNotFoundException e) { + this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); + this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); + } catch (ClassNotFoundException e) { // Ignore - we will detect this later } } private String getPackageName() { - final Server server = Bukkit.getServer(); - final String name = server != null ? server.getClass().getPackage().getName() : null; + Server server = Bukkit.getServer(); + String name = server != null ? server.getClass().getPackage().getName() : null; if ((name != null) && name.contains("craftbukkit")) { return name; @@ -391,12 +413,12 @@ public class NbtFactory { } @SuppressWarnings("unchecked") - private Map getDataMap(final Object handle) { + private Map getDataMap(Object handle) { return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle); } @SuppressWarnings("unchecked") - private List getDataList(final Object handle) { + private List getDataList(Object handle) { return (List) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); } @@ -405,7 +427,7 @@ public class NbtFactory { * @param value - the value of the element to create. Can be a List or a Map. * @return The NBT element. */ - private Object unwrapValue(final Object value) { + private Object unwrapValue(Object value) { if (value == null) { return null; } @@ -430,13 +452,13 @@ public class NbtFactory { * @param nms - the NBT element. * @return The wrapper equivalent. */ - private Object wrapNative(final Object nms) { + private Object wrapNative(Object nms) { if (nms == null) { return null; } - if (BASE_CLASS.isAssignableFrom(nms.getClass())) { - final NbtType type = getNbtType(nms); + if (this.BASE_CLASS.isAssignableFrom(nms.getClass())) { + NbtType type = getNbtType(nms); // Handle the different types switch (type) { @@ -457,8 +479,8 @@ public class NbtFactory { * @param value - the value, or NULL to keep the original value. * @return The created tag. */ - private Object createNbtTag(final NbtType type, final Object value) { - final Object tag = invokeMethod(NBT_CREATE_TAG, null, (byte) type.id); + private Object createNbtTag(NbtType type, Object value) { + Object tag = invokeMethod(this.NBT_CREATE_TAG, null, (byte) type.id); if (value != null) { setFieldValue(getDataField(type, tag), tag, value); @@ -472,11 +494,11 @@ public class NbtFactory { * @param nms - the NBT class instance. * @return The corresponding field. */ - private Field getDataField(final NbtType type, final Object nms) { - if (DATA_FIELD[type.id] == null) { - DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); + private Field getDataField(NbtType type, Object nms) { + if (this.DATA_FIELD[type.id] == null) { + this.DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); } - return DATA_FIELD[type.id]; + return this.DATA_FIELD[type.id]; } /** @@ -484,8 +506,8 @@ public class NbtFactory { * @param nms - the native NBT tag. * @return The corresponding type. */ - private NbtType getNbtType(final Object nms) { - final int type = (Byte) invokeMethod(NBT_GET_TYPE, nms); + private NbtType getNbtType(Object nms) { + int type = (Byte) invokeMethod(this.NBT_GET_TYPE, nms); return NBT_ENUM.get(type); } @@ -494,8 +516,8 @@ public class NbtFactory { * @param primitive - the primitive type. * @return The corresponding type. */ - private NbtType getPrimitiveType(final Object primitive) { - final NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); + private NbtType getPrimitiveType(Object primitive) { + NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); // Display the illegal value at least if (type == null) { @@ -529,7 +551,7 @@ public class NbtFactory { // Unique NBT type public final int id; - NbtType(final int id, final Class type) { + NbtType(int id, Class type) { this.id = id; NBT_CLASS.put(id, type); NBT_ENUM.put(id, this); @@ -567,9 +589,9 @@ public class NbtFactory { protected Method staticMethod; - protected void setMethod(final Method method) { - staticMethod = method; - staticMethod.setAccessible(true); + protected void setMethod(Method method) { + this.staticMethod = method; + this.staticMethod.setAccessible(true); } /** @@ -577,7 +599,7 @@ public class NbtFactory { * @param input - the input stream. * @return The loaded NBT compound. */ - public abstract Object loadNbt(final DataInput input); + public abstract Object loadNbt(DataInput input); } /** @@ -585,13 +607,13 @@ public class NbtFactory { */ private static class LoadMethodWorldUpdate extends LoadCompoundMethod { - public LoadMethodWorldUpdate(final Class streamClass) { + public LoadMethodWorldUpdate(Class streamClass) { setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class)); } @Override - public Object loadNbt(final DataInput input) { - return invokeMethod(staticMethod, null, input); + public Object loadNbt(DataInput input) { + return invokeMethod(this.staticMethod, null, input); } } @@ -602,15 +624,15 @@ public class NbtFactory { private Object readLimiter; - public LoadMethodSkinUpdate(final Class streamClass, final Class readLimiterClass) { + public LoadMethodSkinUpdate(Class streamClass, Class readLimiterClass) { setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass)); // Find the unlimited read limiter - for (final Field field : readLimiterClass.getDeclaredFields()) { + for (Field field : readLimiterClass.getDeclaredFields()) { if (readLimiterClass.isAssignableFrom(field.getType())) { try { - readLimiter = field.get(null); - } catch (final Exception e) { + this.readLimiter = field.get(null); + } catch (Exception e) { throw new RuntimeException("Cannot retrieve read limiter.", e); } } @@ -618,8 +640,8 @@ public class NbtFactory { } @Override - public Object loadNbt(final DataInput input) { - return invokeMethod(staticMethod, null, input, readLimiter); + public Object loadNbt(DataInput input) { + return invokeMethod(this.staticMethod, null, input, this.readLimiter); } } @@ -643,44 +665,44 @@ public class NbtFactory { */ public final class NbtCompound extends ConvertedMap { - private NbtCompound(final Object handle) { + private NbtCompound(Object handle) { super(handle, getDataMap(handle)); } // Simplifiying access to each value - public Byte getByte(final String key, final Byte defaultValue) { + public Byte getByte(String key, Byte defaultValue) { return containsKey(key) ? (Byte) get(key) : defaultValue; } - public Short getShort(final String key, final Short defaultValue) { + public Short getShort(String key, Short defaultValue) { return containsKey(key) ? (Short) get(key) : defaultValue; } - public Integer getInteger(final String key, final Integer defaultValue) { + public Integer getInteger(String key, Integer defaultValue) { return containsKey(key) ? (Integer) get(key) : defaultValue; } - public Long getLong(final String key, final Long defaultValue) { + public Long getLong(String key, Long defaultValue) { return containsKey(key) ? (Long) get(key) : defaultValue; } - public Float getFloat(final String key, final Float defaultValue) { + public Float getFloat(String key, Float defaultValue) { return containsKey(key) ? (Float) get(key) : defaultValue; } - public Double getDouble(final String key, final Double defaultValue) { + public Double getDouble(String key, Double defaultValue) { return containsKey(key) ? (Double) get(key) : defaultValue; } - public String getString(final String key, final String defaultValue) { + public String getString(String key, String defaultValue) { return containsKey(key) ? (String) get(key) : defaultValue; } - public byte[] getByteArray(final String key, final byte[] defaultValue) { + public byte[] getByteArray(String key, byte[] defaultValue) { return containsKey(key) ? (byte[]) get(key) : defaultValue; } - public int[] getIntegerArray(final String key, final int[] defaultValue) { + public int[] getIntegerArray(String key, int[] defaultValue) { return containsKey(key) ? (int[]) get(key) : defaultValue; } @@ -690,7 +712,7 @@ public class NbtFactory { * @param createNew - whether or not to create a new list if its missing. * @return An existing list, a new list or NULL. */ - public NbtList getList(final String key, final boolean createNew) { + public NbtList getList(String key, boolean createNew) { NbtList list = (NbtList) get(key); if ((list == null) && createNew) { @@ -705,7 +727,7 @@ public class NbtFactory { * @param createNew - whether or not to create a new map if its missing. * @return An existing map, a new map or NULL. */ - public NbtCompound getMap(final String key, final boolean createNew) { + public NbtCompound getMap(String key, boolean createNew) { return getMap(Collections.singletonList(key), createNew); } @@ -720,9 +742,9 @@ public class NbtFactory { * @param value - the new value of this entry. * @return This compound, for chaining. */ - public NbtCompound putPath(final String path, final Object value) { - final List entries = getPathElements(path); - final Map map = getMap(entries.subList(0, entries.size() - 1), true); + public NbtCompound putPath(String path, Object value) { + List entries = getPathElements(path); + Map map = getMap(entries.subList(0, entries.size() - 1), true); map.put(entries.get(entries.size() - 1), value); return this; @@ -737,9 +759,9 @@ public class NbtFactory { * @return The value, or NULL if not found. */ @SuppressWarnings("unchecked") - public T getPath(final String path) { - final List entries = getPathElements(path); - final NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); + public T getPath(String path) { + List entries = getPathElements(path); + NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); if (map != null) { return (T) map.get(entries.get(entries.size() - 1)); @@ -755,7 +777,7 @@ public class NbtFactory { * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public void saveTo(final ByteSink stream, final StreamOptions option) throws IOException { + public void saveTo(ByteSink stream, StreamOptions option) throws IOException { saveStream(this, stream, option); } @@ -765,10 +787,10 @@ public class NbtFactory { * @param createNew - whether or not to create new compounds on the way. * @return The map at this location. */ - private NbtCompound getMap(final Iterable path, final boolean createNew) { + private NbtCompound getMap(Iterable path, boolean createNew) { NbtCompound current = this; - for (final String entry : path) { + for (String entry : path) { NbtCompound child = (NbtCompound) current.get(entry); if (child == null) { @@ -787,7 +809,7 @@ public class NbtFactory { * @param path - the path to split. * @return The elements. */ - private List getPathElements(final String path) { + private List getPathElements(String path) { return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path)); } } @@ -803,7 +825,7 @@ public class NbtFactory { */ public final class NbtList extends ConvertedList { - private NbtList(final Object handle) { + private NbtList(Object handle) { super(handle, getDataList(handle)); } } @@ -817,15 +839,15 @@ public class NbtFactory { // Don't recreate wrapper objects private final ConcurrentMap cache = new MapMaker().weakKeys().makeMap(); - public Object wrap(final Object value) { - Object current = cache.get(value); + public Object wrap(Object value) { + Object current = this.cache.get(value); if (current == null) { current = wrapNative(value); // Only cache composite objects if ((current instanceof ConvertedMap) || (current instanceof ConvertedList)) { - cache.put(value, current); + this.cache.put(value, current); } } return current; @@ -844,57 +866,57 @@ public class NbtFactory { private final CachedNativeWrapper cache = new CachedNativeWrapper(); - public ConvertedMap(final Object handle, final Map original) { + public ConvertedMap(Object handle, Map original) { this.handle = handle; this.original = original; } // For converting back and forth - protected Object wrapOutgoing(final Object value) { - return cache.wrap(value); + protected Object wrapOutgoing(Object value) { + return this.cache.wrap(value); } - protected Object unwrapIncoming(final Object wrapped) { + protected Object unwrapIncoming(Object wrapped) { return unwrapValue(wrapped); } // Modification @Override - public Object put(final String key, final Object value) { - return wrapOutgoing(original.put(key, unwrapIncoming(value))); + public Object put(String key, Object value) { + return wrapOutgoing(this.original.put(key, unwrapIncoming(value))); } // Performance @Override - public Object get(final Object key) { - return wrapOutgoing(original.get(key)); + public Object get(Object key) { + return wrapOutgoing(this.original.get(key)); } @Override - public Object remove(final Object key) { - return wrapOutgoing(original.remove(key)); + public Object remove(Object key) { + return wrapOutgoing(this.original.remove(key)); } @Override - public boolean containsKey(final Object key) { - return original.containsKey(key); + public boolean containsKey(Object key) { + return this.original.containsKey(key); } @Override public Set> entrySet() { return new AbstractSet>() { @Override - public boolean add(final Entry e) { - final String key = e.getKey(); - final Object value = e.getValue(); + public boolean add(Entry e) { + String key = e.getKey(); + Object value = e.getValue(); - original.put(key, unwrapIncoming(value)); + ConvertedMap.this.original.put(key, unwrapIncoming(value)); return true; } @Override public int size() { - return original.size(); + return ConvertedMap.this.original.size(); } @Override @@ -905,7 +927,7 @@ public class NbtFactory { } private Iterator> iterator() { - final Iterator> proxy = original.entrySet().iterator(); + final Iterator> proxy = this.original.entrySet().iterator(); return new Iterator>() { @Override @@ -915,7 +937,7 @@ public class NbtFactory { @Override public Entry next() { - final Entry entry = proxy.next(); + Entry entry = proxy.next(); return new SimpleEntry(entry.getKey(), wrapOutgoing(entry.getValue())); } @@ -929,7 +951,7 @@ public class NbtFactory { @Override public Object getHandle() { - return handle; + return this.handle; } } @@ -945,61 +967,61 @@ public class NbtFactory { private final List original; private final CachedNativeWrapper cache = new CachedNativeWrapper(); - public ConvertedList(final Object handle, final List original) { - if (NBT_LIST_TYPE == null) { - NBT_LIST_TYPE = getField(handle, null, "type"); + public ConvertedList(Object handle, List original) { + if (NbtFactory.this.NBT_LIST_TYPE == null) { + NbtFactory.this.NBT_LIST_TYPE = getField(handle, null, "type"); } this.handle = handle; this.original = original; } - protected Object wrapOutgoing(final Object value) { - return cache.wrap(value); + protected Object wrapOutgoing(Object value) { + return this.cache.wrap(value); } - protected Object unwrapIncoming(final Object wrapped) { + protected Object unwrapIncoming(Object wrapped) { return unwrapValue(wrapped); } @Override - public Object get(final int index) { - return wrapOutgoing(original.get(index)); + public Object get(int index) { + return wrapOutgoing(this.original.get(index)); } @Override public int size() { - return original.size(); + return this.original.size(); } @Override - public Object set(final int index, final Object element) { - return wrapOutgoing(original.set(index, unwrapIncoming(element))); + public Object set(int index, Object element) { + return wrapOutgoing(this.original.set(index, unwrapIncoming(element))); } @Override - public void add(final int index, final Object element) { - final Object nbt = unwrapIncoming(element); + public void add(int index, Object element) { + Object nbt = unwrapIncoming(element); // Set the list type if its the first element if (size() == 0) { - setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id); + setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) getNbtType(nbt).id); } - original.add(index, nbt); + this.original.add(index, nbt); } @Override - public Object remove(final int index) { - return wrapOutgoing(original.remove(index)); + public Object remove(int index) { + return wrapOutgoing(this.original.remove(index)); } @Override - public boolean remove(final Object o) { - return original.remove(unwrapIncoming(o)); + public boolean remove(Object o) { + return this.original.remove(unwrapIncoming(o)); } @Override public Object getHandle() { - return handle; + return this.handle; } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java index 61144ddf4..17b15e224 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java @@ -19,15 +19,15 @@ import java.util.UUID; public class OfflinePlayerUtil { - public static Player loadPlayer(final String name) { + public static Player loadPlayer(String name) { return loadPlayer(Bukkit.getOfflinePlayer(name)); } - public static Player loadPlayer(final UUID id) { + public static Player loadPlayer(UUID id) { return loadPlayer(Bukkit.getOfflinePlayer(id)); } - public static Player loadPlayer(final OfflinePlayer player) { + public static Player loadPlayer(OfflinePlayer player) { if (player == null) { return null; } @@ -37,21 +37,21 @@ public class OfflinePlayerUtil { return loadPlayer(player.getUniqueId(), player.getName()); } - private static Player loadPlayer(final UUID id, final String name) { - final Object server = getMinecraftServer(); - final Object interactManager = newPlayerInteractManager(); - final Object worldServer = getWorldServer(); - final Object profile = newGameProfile(id, name); - final Class entityPlayerClass = getNmsClass("EntityPlayer"); - final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), + private static Player loadPlayer(UUID id, String name) { + Object server = getMinecraftServer(); + Object interactManager = newPlayerInteractManager(); + Object worldServer = getWorldServer(); + Object profile = newGameProfile(id, name); + Class entityPlayerClass = getNmsClass("EntityPlayer"); + Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), getNmsClass("PlayerInteractManager")); - final Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); + Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); return (Player) getBukkitEntity(entityPlayer); } - private static Object newGameProfile(final UUID id, final String name) { - final Class gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); + private static Object newGameProfile(UUID id, String name) { + Class gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); if (gameProfileClass == null) { //Before uuids return name; } @@ -65,17 +65,17 @@ public class OfflinePlayerUtil { } private static Object newPlayerInteractManager() { - final Object worldServer = getWorldServer(); - final Class playerInteractClass = getNmsClass("PlayerInteractManager"); - final Class worldClass = getNmsClass("World"); - final Constructor c = makeConstructor(playerInteractClass, worldClass); + Object worldServer = getWorldServer(); + Class playerInteractClass = getNmsClass("PlayerInteractManager"); + Class worldClass = getNmsClass("World"); + Constructor c = makeConstructor(playerInteractClass, worldClass); return callConstructor(c, worldServer); } private static Object getWorldServer() { - final Object server = getMinecraftServer(); - final Class minecraftServerClass = getNmsClass("MinecraftServer"); - final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); + Object server = getMinecraftServer(); + Class minecraftServerClass = getNmsClass("MinecraftServer"); + Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); return callMethod(getWorldServer, server, 0); } @@ -85,8 +85,8 @@ public class OfflinePlayerUtil { return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer()); } - private static Entity getBukkitEntity(final Object o) { - final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); + private static Entity getBukkitEntity(Object o) { + Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); return callMethod(getBukkitEntity, o); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java index 780fabeb8..362c6083a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java @@ -1,5 +1,7 @@ package com.plotsquared.bukkit.util; +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.Location; @@ -17,11 +19,12 @@ import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.entity.Player; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; import java.util.Map.Entry; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - /** * An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS) * @@ -29,17 +32,9 @@ import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; */ public class SendChunk { - // // Ref Class - private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); - private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); - private final RefClass classPacket = getRefClass("{nms}.Packet"); - private final RefClass classConnection = getRefClass("{nms}.PlayerConnection"); - private final RefClass classChunk = getRefClass("{nms}.Chunk"); - private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); - private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); private final RefMethod methodGetHandlePlayer; private final RefMethod methodGetHandleChunk; - private final RefConstructor MapChunk; + private final RefConstructor mapChunk; private final RefField connection; private final RefMethod send; private final RefMethod methodInitLighting; @@ -48,32 +43,39 @@ public class SendChunk { * Constructor */ public SendChunk() { - methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); - methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); - methodInitLighting = classChunk.getMethod("initLighting"); - MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); - connection = classEntityPlayer.getField("playerConnection"); - send = classConnection.getMethod("sendPacket", classPacket.getRealClass()); + RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); + this.methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); + RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); + this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); + RefClass classChunk = getRefClass("{nms}.Chunk"); + this.methodInitLighting = classChunk.getMethod("initLighting"); + RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); + this.mapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); + RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); + this.connection = classEntityPlayer.getField("playerConnection"); + RefClass classPacket = getRefClass("{nms}.Packet"); + RefClass classConnection = getRefClass("{nms}.PlayerConnection"); + this.send = classConnection.getMethod("sendPacket", classPacket.getRealClass()); } - public void sendChunk(final Collection input) { - final HashSet chunks = new HashSet(input); - final HashMap> map = new HashMap<>(); - final int view = Bukkit.getServer().getViewDistance(); - for (final Chunk chunk : chunks) { - final String world = chunk.getWorld().getName(); + public void sendChunk(Collection input) { + HashSet chunks = new HashSet(input); + HashMap> map = new HashMap<>(); + int view = Bukkit.getServer().getViewDistance(); + for (Chunk chunk : chunks) { + String world = chunk.getWorld().getName(); ArrayList list = map.get(world); if (list == null) { list = new ArrayList<>(); map.put(world, list); } list.add(chunk); - final Object c = methodGetHandleChunk.of(chunk).call(); - methodInitLighting.of(c).call(); + Object c = this.methodGetHandleChunk.of(chunk).call(); + this.methodInitLighting.of(c).call(); } for (Entry entry : UUIDHandler.getPlayers().entrySet()) { PlotPlayer pp = entry.getValue(); - final Plot plot = pp.getCurrentPlot(); + Plot plot = pp.getCurrentPlot(); Location loc = null; String world; if (plot != null) { @@ -82,29 +84,29 @@ public class SendChunk { loc = pp.getLocation(); world = loc.getWorld(); } - final ArrayList list = map.get(world); + ArrayList list = map.get(world); if (list == null) { continue; } if (loc == null) { loc = pp.getLocation(); } - final int cx = loc.getX() >> 4; - final int cz = loc.getZ() >> 4; - final Player player = ((BukkitPlayer) pp).player; - final Object entity = methodGetHandlePlayer.of(player).call(); + int cx = loc.getX() >> 4; + int cz = loc.getZ() >> 4; + Player player = ((BukkitPlayer) pp).player; + Object entity = this.methodGetHandlePlayer.of(player).call(); - for (final Chunk chunk : list) { - final int dx = Math.abs(cx - chunk.getX()); - final int dz = Math.abs(cz - chunk.getZ()); + for (Chunk chunk : list) { + int dx = Math.abs(cx - chunk.getX()); + int dz = Math.abs(cz - chunk.getZ()); if ((dx > view) || (dz > view)) { continue; } - final Object c = methodGetHandleChunk.of(chunk).call(); + Object c = this.methodGetHandleChunk.of(chunk).call(); chunks.remove(chunk); - final Object con = connection.of(entity).get(); - final Object packet = MapChunk.create(c, true, 65535); - send.of(con).call(packet); + Object con = this.connection.of(entity).get(); + Object packet = this.mapChunk.create(c, true, 65535); + this.send.of(con).call(packet); } } for (final Chunk chunk : chunks) { @@ -113,8 +115,8 @@ public class SendChunk { public void run() { try { chunk.unload(true, false); - } catch (final Throwable e) { - final String worldname = chunk.getWorld().getName(); + } catch (Throwable e) { + String worldname = chunk.getWorld().getName(); PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname @@ -125,10 +127,10 @@ public class SendChunk { } } - public void sendChunk(final String worldname, final Collection locs) { - final World myworld = Bukkit.getWorld(worldname); - final ArrayList chunks = new ArrayList<>(); - for (final ChunkLoc loc : locs) { + public void sendChunk(String worldname, Collection locs) { + World myworld = Bukkit.getWorld(worldname); + ArrayList chunks = new ArrayList<>(); + for (ChunkLoc loc : locs) { if (myworld.isChunkLoaded(loc.x, loc.z)) { chunks.add(myworld.getChunkAt(loc.x, loc.z)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java index fec7d3240..ac3b57ac7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java @@ -14,24 +14,24 @@ import java.util.Iterator; public class SetGenCB { - public static void setGenerator(final World world) throws Exception { + public static void setGenerator(World world) throws Exception { SetupUtils.manager.updateGenerators(); PS.get().removePlotAreas(world.getName()); - final ChunkGenerator gen = world.getGenerator(); + ChunkGenerator gen = world.getGenerator(); if (gen == null) { return; } - final String name = gen.getClass().getCanonicalName(); + String name = gen.getClass().getCanonicalName(); boolean set = false; - for (final GeneratorWrapper wrapper : SetupUtils.generators.values()) { + for (GeneratorWrapper wrapper : SetupUtils.generators.values()) { ChunkGenerator newGen = (ChunkGenerator) wrapper.getPlatformGenerator(); if (newGen == null) { newGen = (ChunkGenerator) wrapper; } if (newGen.getClass().getCanonicalName().equals(name)) { // set generator - final Field generator = world.getClass().getDeclaredField("generator"); - final Field populators = world.getClass().getDeclaredField("populators"); + Field generator = world.getClass().getDeclaredField("generator"); + Field populators = world.getClass().getDeclaredField("populators"); generator.setAccessible(true); populators.setAccessible(true); // Set populators (just in case) @@ -45,7 +45,7 @@ public class SetGenCB { } } if (!set) { - final Iterator iter = world.getPopulators().iterator(); + Iterator iter = world.getPopulators().iterator(); while (iter.hasNext()) { if (iter.next() instanceof BukkitAugmentedGenerator) { iter.remove(); 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 939b1610a..3666a1b9d 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 @@ -17,12 +17,13 @@ public class FastChunk_1_8_3 extends PlotChunk { public short[] relight; public int[][] biomes; public Chunk chunk; - public FastChunk_1_8_3(final ChunkWrapper chunk) { + + public FastChunk_1_8_3(ChunkWrapper chunk) { super(chunk); - ids = new char[16][]; - count = new short[16]; - air = new short[16]; - relight = new short[16]; + this.ids = new char[16][]; + this.count = new short[16]; + this.air = new short[16]; + this.relight = new short[16]; } @Override @@ -33,17 +34,17 @@ public class FastChunk_1_8_3 extends PlotChunk { @Override public Chunk getChunk() { - if (chunk == null) { - final ChunkWrapper cl = getChunkWrapper(); - chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z); + if (this.chunk == null) { + ChunkWrapper cl = getChunkWrapper(); + this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z); } - return chunk; + return this.chunk; } @Override - public void setChunkWrapper(final ChunkWrapper loc) { + public void setChunkWrapper(ChunkWrapper loc) { super.setChunkWrapper(loc); - chunk = null; + this.chunk = null; } /** @@ -51,44 +52,44 @@ public class FastChunk_1_8_3 extends PlotChunk { * @param i * @return */ - public int getCount(final int i) { - return count[i]; + public int getCount(int i) { + return this.count[i]; } - public int getAir(final int i) { - return air[i]; + public int getAir(int i) { + return this.air[i]; } public void setCount(int i, short value) { - count[i] = value; + this.count[i] = value; } /** - * Get the number of block changes in a specified section + * Get the number of block changes in a specified section. * @param i * @return */ - public int getRelight(final int i) { - return relight[i]; + public int getRelight(int i) { + return this.relight[i]; } public int getTotalCount() { int total = 0; for (int i = 0; i < 16; i++) { - total += count[i]; + total += this.count[i]; } return total; } public int getTotalRelight() { if (getTotalCount() == 0) { - Arrays.fill(count, (short) 1); - Arrays.fill(relight, Short.MAX_VALUE); + Arrays.fill(this.count, (short) 1); + Arrays.fill(this.relight, Short.MAX_VALUE); return Short.MAX_VALUE; } int total = 0; for (int i = 0; i < 16; i++) { - total += relight[i]; + total += this.relight[i]; } return total; } @@ -98,24 +99,24 @@ public class FastChunk_1_8_3 extends PlotChunk { * @param i * @return */ - public char[] getIdArray(final int i) { - return ids[i]; + public char[] getIdArray(int i) { + return this.ids[i]; } @Override - public void setBlock(final int x, final int y, final int z, final int id, byte data) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; - char[] vs = ids[i]; + public void setBlock(int x, int y, int z, int id, byte data) { + int i = MainUtil.CACHE_I[y][x][z]; + int j = MainUtil.CACHE_J[y][x][z]; + char[] vs = this.ids[i]; if (vs == null) { - vs = ids[i] = new char[4096]; - count[i]++; + vs = this.ids[i] = new char[4096]; + this.count[i]++; } else if (vs[j] == 0) { - count[i]++; + this.count[i]++; } switch (id) { case 0: - air[i]++; + this.air[i]++; vs[j] = (char) 1; return; case 10: @@ -129,7 +130,7 @@ public class FastChunk_1_8_3 extends PlotChunk { case 124: case 138: case 169: - relight[i]++; + this.relight[i]++; case 2: case 4: case 13: @@ -193,7 +194,7 @@ public class FastChunk_1_8_3 extends PlotChunk { case 130: case 76: case 62: - relight[i]++; + this.relight[i]++; case 54: case 146: case 61: @@ -212,12 +213,12 @@ public class FastChunk_1_8_3 extends PlotChunk { @Override public PlotChunk clone() { FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper()); - toReturn.air = air.clone(); - toReturn.count = count.clone(); - toReturn.relight = relight.clone(); - toReturn.ids = new char[ids.length][]; - for (int i = 0; i < ids.length; i++) { - char[] matrix = ids[i]; + toReturn.air = this.air.clone(); + toReturn.count = this.count.clone(); + toReturn.relight = this.relight.clone(); + toReturn.ids = new char[this.ids.length][]; + for (int i = 0; i < this.ids.length; i++) { + char[] matrix = this.ids[i]; if (matrix != null) { toReturn.ids[i] = new char[matrix.length]; System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length); @@ -229,18 +230,18 @@ public class FastChunk_1_8_3 extends PlotChunk { @Override public PlotChunk shallowClone() { FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper()); - toReturn.air = air; - toReturn.count = count; - toReturn.relight = relight; - toReturn.ids = ids; + toReturn.air = this.air; + toReturn.count = this.count; + toReturn.relight = this.relight; + toReturn.ids = this.ids; return toReturn; } @Override public void setBiome(int x, int z, int biome) { - if (biomes == null) { - biomes = new int[16][16]; + if (this.biomes == null) { + this.biomes = new int[16][16]; } - biomes[x][z] = biome; + this.biomes[x][z] = biome; } } 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 a47854654..73502bbd3 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 @@ -17,12 +17,13 @@ public class FastChunk_1_9 extends PlotChunk { public short[] relight; public int[][] biomes; public Chunk chunk; - public FastChunk_1_9(final ChunkWrapper chunk) { + + public FastChunk_1_9(ChunkWrapper chunk) { super(chunk); - ids = new int[16][]; - count = new short[16]; - air = new short[16]; - relight = new short[16]; + this.ids = new int[16][]; + this.count = new short[16]; + this.air = new short[16]; + this.relight = new short[16]; } @Override @@ -33,17 +34,17 @@ public class FastChunk_1_9 extends PlotChunk { @Override public Chunk getChunk() { - if (chunk == null) { - final ChunkWrapper cl = getChunkWrapper(); - chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z); + if (this.chunk == null) { + ChunkWrapper cl = getChunkWrapper(); + this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z); } - return chunk; + return this.chunk; } @Override - public void setChunkWrapper(final ChunkWrapper loc) { + public void setChunkWrapper(ChunkWrapper loc) { super.setChunkWrapper(loc); - chunk = null; + this.chunk = null; } /** @@ -51,16 +52,16 @@ public class FastChunk_1_9 extends PlotChunk { * @param i * @return */ - public int getCount(final int i) { - return count[i]; + public int getCount(int i) { + return this.count[i]; } - public int getAir(final int i) { - return air[i]; + public int getAir(int i) { + return this.air[i]; } public void setCount(int i, short value) { - count[i] = value; + this.count[i] = value; } /** @@ -68,27 +69,27 @@ public class FastChunk_1_9 extends PlotChunk { * @param i * @return */ - public int getRelight(final int i) { - return relight[i]; + public int getRelight(int i) { + return this.relight[i]; } public int getTotalCount() { int total = 0; for (int i = 0; i < 16; i++) { - total += count[i]; + total += this.count[i]; } return total; } public int getTotalRelight() { if (getTotalCount() == 0) { - Arrays.fill(count, (short) 1); - Arrays.fill(relight, Short.MAX_VALUE); + Arrays.fill(this.count, (short) 1); + Arrays.fill(this.relight, Short.MAX_VALUE); return Short.MAX_VALUE; } int total = 0; for (int i = 0; i < 16; i++) { - total += relight[i]; + total += this.relight[i]; } return total; } @@ -98,28 +99,28 @@ public class FastChunk_1_9 extends PlotChunk { * @param i * @return */ - public int[] getIdArray(final int i) { - return ids[i]; + public int[] getIdArray(int i) { + return this.ids[i]; } public int[][] getIdArrays() { - return ids; + return this.ids; } @Override - public void setBlock(final int x, final int y, final int z, final int id, byte data) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; - int[] vs = ids[i]; + public void setBlock(int x, int y, int z, int id, byte data) { + int i = MainUtil.CACHE_I[y][x][z]; + int j = MainUtil.CACHE_J[y][x][z]; + int[] vs = this.ids[i]; if (vs == null) { - vs = ids[i] = new int[4096]; - count[i]++; + vs = this.ids[i] = new int[4096]; + this.count[i]++; } else if (vs[j] == 0) { - count[i]++; + this.count[i]++; } switch (id) { case 0: - air[i]++; + this.air[i]++; vs[j] = -1; return; case 10: @@ -133,7 +134,7 @@ public class FastChunk_1_9 extends PlotChunk { case 124: case 138: case 169: - relight[i]++; + this.relight[i]++; case 2: case 4: case 13: @@ -192,12 +193,12 @@ public class FastChunk_1_9 extends PlotChunk { case 190: case 191: case 192: - vs[j] = (id); + vs[j] = id; return; case 130: case 76: case 62: - relight[i]++; + this.relight[i]++; case 54: case 146: case 61: @@ -216,12 +217,12 @@ public class FastChunk_1_9 extends PlotChunk { @Override public PlotChunk clone() { FastChunk_1_9 toReturn = new FastChunk_1_9(getChunkWrapper()); - toReturn.air = air.clone(); - toReturn.count = count.clone(); - toReturn.relight = relight.clone(); - toReturn.ids = new int[ids.length][]; - for (int i = 0; i < ids.length; i++) { - int[] matrix = ids[i]; + toReturn.air = this.air.clone(); + toReturn.count = this.count.clone(); + toReturn.relight = this.relight.clone(); + toReturn.ids = new int[this.ids.length][]; + for (int i = 0; i < this.ids.length; i++) { + int[] matrix = this.ids[i]; if (matrix != null) { toReturn.ids[i] = new int[matrix.length]; System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length); @@ -233,18 +234,18 @@ public class FastChunk_1_9 extends PlotChunk { @Override public PlotChunk shallowClone() { FastChunk_1_9 toReturn = new FastChunk_1_9(getChunkWrapper()); - toReturn.air = air; - toReturn.count = count; - toReturn.relight = relight; - toReturn.ids = ids; + toReturn.air = this.air; + toReturn.count = this.count; + toReturn.relight = this.relight; + toReturn.ids = this.ids; return toReturn; } @Override public void setBiome(int x, int z, int biome) { - if (biomes == null) { - biomes = new int[16][16]; + if (this.biomes == null) { + this.biomes = new int[16][16]; } - biomes[x][z] = biome; + this.biomes[x][z] = biome; } } 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 fc2fb1614..bd5d0c413 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 @@ -1,5 +1,7 @@ package com.plotsquared.bukkit.util.block; +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; @@ -21,8 +23,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - public class FastQueue_1_7 extends SlowQueue { private final RefClass classBlock = getRefClass("{nms}.Block"); @@ -37,24 +37,24 @@ public class FastQueue_1_7 extends SlowQueue { private final SendChunk chunksender; - private HashMap toUpdate = new HashMap<>(); + private final HashMap toUpdate = new HashMap<>(); public FastQueue_1_7() throws NoSuchMethodException, RuntimeException { - methodGetHandle = classCraftWorld.getMethod("getHandle"); - methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); - methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class); - methodGetById = classBlock.getMethod("getById", int.class); - methodInitLighting = classChunk.getMethod("initLighting"); - chunksender = new SendChunk(); + 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); + this.methodGetById = this.classBlock.getMethod("getById", int.class); + this.methodInitLighting = this.classChunk.getMethod("initLighting"); + this.chunksender = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.isEmpty()) { + if (FastQueue_1_7.this.toUpdate.isEmpty()) { return; } int count = 0; - final ArrayList chunks = new ArrayList<>(); - final Iterator> i = toUpdate.entrySet().iterator(); + ArrayList chunks = new ArrayList<>(); + Iterator> i = FastQueue_1_7.this.toUpdate.entrySet().iterator(); while (i.hasNext() && (count < 128)) { chunks.add(i.next().getValue()); i.remove(); @@ -69,12 +69,12 @@ public class FastQueue_1_7 extends SlowQueue { MainUtil.initCache(); } - public void update(final Collection chunks) { + public void update(Collection chunks) { if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { - for (final Chunk chunk : chunks) { + for (Chunk chunk : chunks) { chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); chunk.unload(true, false); chunk.load(); @@ -82,8 +82,8 @@ public class FastQueue_1_7 extends SlowQueue { return; } try { - chunksender.sendChunk(chunks); - } catch (final Throwable e) { + this.chunksender.sendChunk(chunks); + } catch (Throwable e) { e.printStackTrace(); MainUtil.canSendChunk = false; } @@ -91,36 +91,36 @@ public class FastQueue_1_7 extends SlowQueue { /** * This should be overridden by any specialized queues - * @param pc + * @param plotChunk */ @Override - public void execute(PlotChunk pc) { - SlowChunk sc = (SlowChunk) pc; - Chunk chunk = pc.getChunk(); - ChunkWrapper wrapper = pc.getChunkWrapper(); - if (!toUpdate.containsKey(wrapper)) { - toUpdate.put(wrapper, chunk); + public void execute(PlotChunk plotChunk) { + SlowChunk sc = (SlowChunk) plotChunk; + Chunk chunk = plotChunk.getChunk(); + ChunkWrapper wrapper = plotChunk.getChunkWrapper(); + if (!this.toUpdate.containsKey(wrapper)) { + this.toUpdate.put(wrapper, chunk); } chunk.load(true); World world = chunk.getWorld(); - final Object w = methodGetHandle.of(world).call(); - final Object c = methodGetChunkAt.of(w).call(wrapper.x, wrapper.z); + Object w = this.methodGetHandle.of(world).call(); + Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z); for (int i = 0; i < sc.result.length; i++) { PlotBlock[] result2 = sc.result[i]; if (result2 == null) { continue; } for (int j = 0; j < 4096; j++) { - final int x = MainUtil.x_loc[i][j]; - final int y = MainUtil.y_loc[i][j]; - final int z = MainUtil.z_loc[i][j]; + int x = MainUtil.x_loc[i][j]; + int y = MainUtil.y_loc[i][j]; + int z = MainUtil.z_loc[i][j]; PlotBlock newBlock = result2[j]; if (newBlock.id == -1) { chunk.getBlock(x, y, z).setData(newBlock.data, false); continue; } - final Object block = methodGetById.call(newBlock.id); - methodA.of(c).call(x, y, z, block, newBlock.data); + Object block = this.methodGetById.call(newBlock.id); + this.methodA.of(c).call(x, y, z, block, newBlock.data); } } int[][] biomes = sc.biomes; @@ -152,29 +152,29 @@ public class FastQueue_1_7 extends SlowQueue { } /** - * This should be overriden by any specialized queues + * This should be overridden by any specialized queues * @param chunk * @param fixAll */ @Override public boolean fixLighting(PlotChunk chunk, boolean fixAll) { - Object c = methodGetHandle.of(chunk.getChunk()).call(); - methodInitLighting.of(c).call(); + Object c = this.methodGetHandle.of(chunk.getChunk()).call(); + this.methodInitLighting.of(c).call(); return true; } /** * This should be overridden by any specialized queues * @param world - * @param locs + * @param locations */ @Override - public void sendChunk(String world, Collection locs) { + public void sendChunk(String world, Collection locations) { World worldObj = BukkitUtil.getWorld(world); - for (ChunkLoc loc : locs) { + for (ChunkLoc loc : locations) { ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); - toUpdate.remove(wrapper); + this.toUpdate.remove(wrapper); } - chunksender.sendChunk(world, locs); + this.chunksender.sendChunk(world, locations); } } 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 906745bcd..f1dafe14c 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 @@ -1,5 +1,7 @@ package com.plotsquared.bukkit.util.block; +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; @@ -23,8 +25,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - public class FastQueue_1_8 extends SlowQueue { private final RefMethod methodInitLighting; @@ -34,31 +34,31 @@ public class FastQueue_1_8 extends SlowQueue { private final RefClass classChunk = getRefClass("{nms}.Chunk"); private final RefClass classWorld = getRefClass("{nms}.World"); private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - private HashMap toUpdate = new HashMap<>(); - private RefMethod methodGetHandle; - private RefMethod methodGetChunkAt; - private RefMethod methodA; - private RefMethod methodGetByCombinedId; - private RefConstructor constructorBlockPosition; - private SendChunk chunksender; + private final HashMap toUpdate = new HashMap<>(); + private final RefMethod methodGetHandle; + private final RefMethod methodGetChunkAt; + private final RefMethod methodA; + private final RefMethod methodGetByCombinedId; + private final RefConstructor constructorBlockPosition; + private final SendChunk chunksender; public FastQueue_1_8() throws NoSuchMethodException, RuntimeException { - methodInitLighting = classChunk.getMethod("initLighting"); - constructorBlockPosition = classBlockPosition.getConstructor(int.class, int.class, int.class); - methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); - methodGetHandle = classCraftWorld.getMethod("getHandle"); - methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); - methodA = classChunk.getMethod("a", classBlockPosition, classIBlockData); - chunksender = new SendChunk(); + 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); + this.methodGetHandle = this.classCraftWorld.getMethod("getHandle"); + this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class); + this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData); + this.chunksender = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.isEmpty()) { + if (FastQueue_1_8.this.toUpdate.isEmpty()) { return; } int count = 0; - final ArrayList chunks = new ArrayList(); - final Iterator> i = toUpdate.entrySet().iterator(); + ArrayList chunks = new ArrayList(); + Iterator> i = FastQueue_1_8.this.toUpdate.entrySet().iterator(); while (i.hasNext() && (count < 128)) { chunks.add(i.next().getValue()); i.remove(); @@ -73,12 +73,12 @@ public class FastQueue_1_8 extends SlowQueue { MainUtil.initCache(); } - public void update(final Collection chunks) { + public void update(Collection chunks) { if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { - for (final Chunk chunk : chunks) { + for (Chunk chunk : chunks) { chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); chunk.unload(true, false); chunk.load(); @@ -86,38 +86,38 @@ public class FastQueue_1_8 extends SlowQueue { return; } try { - chunksender.sendChunk(chunks); - } catch (final Throwable e) { + this.chunksender.sendChunk(chunks); + } catch (Throwable e) { e.printStackTrace(); MainUtil.canSendChunk = false; } } /** - * This should be overriden by any specialized queues - * @param pc + * This should be overridden by any specialized queues. + * @param plotChunk */ @Override - public void execute(PlotChunk pc) { - SlowChunk sc = (SlowChunk) pc; - Chunk chunk = pc.getChunk(); - ChunkWrapper wrapper = pc.getChunkWrapper(); - if (!toUpdate.containsKey(wrapper)) { - toUpdate.put(wrapper, chunk); + public void execute(PlotChunk plotChunk) { + SlowChunk sc = (SlowChunk) plotChunk; + Chunk chunk = plotChunk.getChunk(); + ChunkWrapper wrapper = plotChunk.getChunkWrapper(); + if (!this.toUpdate.containsKey(wrapper)) { + this.toUpdate.put(wrapper, chunk); } chunk.load(true); World world = chunk.getWorld(); - final Object w = methodGetHandle.of(world).call(); - final Object c = methodGetChunkAt.of(w).call(wrapper.x, wrapper.z); + Object w = this.methodGetHandle.of(world).call(); + Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z); for (int i = 0; i < sc.result.length; i++) { PlotBlock[] result2 = sc.result[i]; if (result2 == null) { continue; } for (int j = 0; j < 4096; j++) { - final int x = MainUtil.x_loc[i][j]; - final int y = MainUtil.y_loc[i][j]; - final int z = MainUtil.z_loc[i][j]; + int x = MainUtil.x_loc[i][j]; + int y = MainUtil.y_loc[i][j]; + int z = MainUtil.z_loc[i][j]; PlotBlock newBlock = result2[j]; if (newBlock.id == -1) { chunk.getBlock(x, y, z).setData(newBlock.data, false); @@ -162,7 +162,7 @@ public class FastQueue_1_8 extends SlowQueue { case 33: case 151: case 178: { - final Block block = world.getBlockAt(x, y, z); + Block block = world.getBlockAt(x, y, z); if (block.getData() == newBlock.data) { if (block.getTypeId() != newBlock.id) { block.setTypeId(newBlock.id, false); @@ -179,8 +179,8 @@ public class FastQueue_1_8 extends SlowQueue { } // Start data value shortcut - final Block block = world.getBlockAt(x, y, z); - final int currentId = block.getTypeId(); + Block block = world.getBlockAt(x, y, z); + int currentId = block.getTypeId(); if (currentId == newBlock.id) { switch (newBlock.id) { case 0: @@ -323,9 +323,9 @@ public class FastQueue_1_8 extends SlowQueue { // End blockstate workaround // // check sign - final Object pos = constructorBlockPosition.create(x, y, z); - final Object combined = methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); - methodA.of(chunk).call(pos, combined); + Object pos = this.constructorBlockPosition.create(x, y, z); + Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); + this.methodA.of(chunk).call(pos, combined); } } int[][] biomes = sc.biomes; @@ -348,7 +348,7 @@ public class FastQueue_1_8 extends SlowQueue { } /** - * This should be overridden by any specialized queues + * This should be overridden by any specialized queues. * @param wrap */ @Override @@ -357,27 +357,27 @@ public class FastQueue_1_8 extends SlowQueue { } /** - * This should be overridden by any specialized queues + * This should be overridden by any specialized queues. * @param fixAll */ @Override public boolean fixLighting(PlotChunk chunk, boolean fixAll) { - Object c = methodGetHandle.of(chunk.getChunk()).call(); - methodInitLighting.of(c).call(); + Object c = this.methodGetHandle.of(chunk.getChunk()).call(); + this.methodInitLighting.of(c).call(); return true; } /** - * This should be overridden by any specialized queues - * @param locs + * This should be overridden by any specialized queues. + * @param locations */ @Override - public void sendChunk(String world, Collection locs) { + public void sendChunk(String world, Collection locations) { World worldObj = BukkitUtil.getWorld(world); - for (ChunkLoc loc : locs) { + for (ChunkLoc loc : locations) { ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); - toUpdate.remove(wrapper); + this.toUpdate.remove(wrapper); } - chunksender.sendChunk(world, locs); + this.chunksender.sendChunk(world, locations); } } 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 90e006849..fa7d165ae 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 @@ -1,15 +1,20 @@ package com.plotsquared.bukkit.util.block; +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.util.*; +import com.intellectualcrafters.plot.util.ChunkManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.PlotChunk; import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor; import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor; +import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; -import com.plotsquared.bukkit.util.BukkitUtil; +import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.util.SendChunk; import org.bukkit.Chunk; import org.bukkit.Material; @@ -20,59 +25,57 @@ import org.bukkit.block.Biome; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map.Entry; - -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; +import java.util.Set; public class FastQueue_1_8_3 extends SlowQueue { private final SendChunk chunksender; - private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); - private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); - private final RefClass classPacket = getRefClass("{nms}.Packet"); - private final RefClass classConnection = getRefClass("{nms}.PlayerConnection"); - private final RefClass classChunk = getRefClass("{nms}.Chunk"); - private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); - private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - private final RefClass classWorld = getRefClass("{nms}.World"); - private final RefField mustSave = classChunk.getField("mustSave"); - private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - private final RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); - private HashMap toUpdate = new HashMap<>(); - private RefMethod methodGetHandleChunk; - private RefConstructor MapChunk; - private RefMethod methodInitLighting; - private RefConstructor classBlockPositionConstructor; - private RefConstructor classChunkSectionConstructor; - private RefMethod methodX; - private RefMethod methodAreNeighborsLoaded; - private RefField fieldSections; - private RefField fieldWorld; - private RefMethod methodGetIdArray; + private final HashMap toUpdate = new HashMap<>(); + private final RefMethod methodGetHandleChunk; + private final RefConstructor MapChunk; + private final RefMethod methodInitLighting; + private final RefConstructor classBlockPositionConstructor; + private final RefConstructor classChunkSectionConstructor; + private final RefMethod methodX; + private final RefMethod methodAreNeighborsLoaded; + private final RefField fieldSections; + private final RefField fieldWorld; + private final RefMethod methodGetIdArray; public FastQueue_1_8_3() throws NoSuchMethodException, RuntimeException { - methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); - methodInitLighting = classChunk.getMethod("initLighting"); - MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); - classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); - methodX = classWorld.getMethod("x", classBlockPosition.getRealClass()); - fieldSections = classChunk.getField("sections"); - fieldWorld = classChunk.getField("world"); - methodGetIdArray = classChunkSection.getMethod("getIdArray"); - methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); - classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); - chunksender = new SendChunk(); + RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); + this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); + RefClass classChunk = getRefClass("{nms}.Chunk"); + this.methodInitLighting = classChunk.getMethod("initLighting"); + RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); + this.MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); + RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); + this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); + RefClass classWorld = getRefClass("{nms}.World"); + this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass()); + this.fieldSections = classChunk.getField("sections"); + this.fieldWorld = classChunk.getField("world"); + RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); + this.methodGetIdArray = classChunkSection.getMethod("getIdArray"); + this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); + this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); + this.chunksender = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.isEmpty()) { + if (FastQueue_1_8_3.this.toUpdate.isEmpty()) { return; } int count = 0; - final ArrayList chunks = new ArrayList(); - final Iterator> i = toUpdate.entrySet().iterator(); - while (i.hasNext() && (count < 128)) { + ArrayList chunks = new ArrayList<>(); + Iterator> i = FastQueue_1_8_3.this.toUpdate.entrySet().iterator(); + while (i.hasNext() && count < 128) { chunks.add(i.next().getValue()); i.remove(); count++; @@ -86,12 +89,12 @@ public class FastQueue_1_8_3 extends SlowQueue { MainUtil.initCache(); } - public void update(final Collection chunks) { + public void update(Collection chunks) { if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { - for (final Chunk chunk : chunks) { + for (Chunk chunk : chunks) { chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); chunk.unload(true, false); chunk.load(); @@ -99,70 +102,70 @@ public class FastQueue_1_8_3 extends SlowQueue { return; } try { - chunksender.sendChunk(chunks); - } catch (final Throwable e) { + this.chunksender.sendChunk(chunks); + } catch (Throwable e) { e.printStackTrace(); MainUtil.canSendChunk = false; } } /** - * This should be overridden by any specialized queues - * @param pc + * This should be overridden by any specialized queues. + * @param plotChunk */ @Override - public void execute(PlotChunk pc) { - FastChunk_1_8_3 fs = (FastChunk_1_8_3) pc; - Chunk chunk = pc.getChunk(); - final World world = chunk.getWorld(); - ChunkWrapper wrapper = pc.getChunkWrapper(); - if (!toUpdate.containsKey(wrapper)) { - toUpdate.put(wrapper, chunk); + public void execute(PlotChunk plotChunk) { + FastChunk_1_8_3 fs = (FastChunk_1_8_3) plotChunk; + Chunk chunk = plotChunk.getChunk(); + World world = chunk.getWorld(); + ChunkWrapper wrapper = plotChunk.getChunkWrapper(); + if (!this.toUpdate.containsKey(wrapper)) { + this.toUpdate.put(wrapper, chunk); } chunk.load(true); try { - final boolean flag = world.getEnvironment() == Environment.NORMAL; + boolean flag = world.getEnvironment() == Environment.NORMAL; // Sections - final Method getHandele = chunk.getClass().getDeclaredMethod("getHandle"); - final Object c = getHandele.invoke(chunk); - final Class clazz = c.getClass(); - final Field sf = clazz.getDeclaredField("sections"); - sf.setAccessible(true); - final Field tf = clazz.getDeclaredField("tileEntities"); - final Field ef = clazz.getDeclaredField("entitySlices"); + Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); + Object c = getHandle.invoke(chunk); + Class clazz = c.getClass(); + Field sections1 = clazz.getDeclaredField("sections"); + sections1.setAccessible(true); + Field tileEntities = clazz.getDeclaredField("tileEntities"); + Field entitySlices = clazz.getDeclaredField("entitySlices"); - final Object[] sections = (Object[]) sf.get(c); - final HashMap tiles = (HashMap) tf.get(c); - final List[] entities = (List[]) ef.get(c); + Object[] sections = (Object[]) sections1.get(c); + HashMap tiles = (HashMap) tileEntities.get(c); + List[] entities = (List[]) entitySlices.get(c); - Method xm = null; - Method ym = null; - Method zm = null; + Method getX = null; + Method getY = null; + Method getZ = null; // Trim tiles - final Set> entryset = (Set>) (Set) tiles.entrySet(); - final Iterator> iter = entryset.iterator(); - while (iter.hasNext()) { - final Entry tile = iter.next(); - final Object pos = tile.getKey(); - if (xm == null) { - final Class clazz2 = pos.getClass().getSuperclass(); - xm = clazz2.getDeclaredMethod("getX"); - ym = clazz2.getDeclaredMethod("getY"); - zm = clazz2.getDeclaredMethod("getZ"); + Set> entrySet = (Set>) (Set) tiles.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Entry tile = iterator.next(); + Object pos = tile.getKey(); + if (getX == null) { + Class clazz2 = pos.getClass().getSuperclass(); + getX = clazz2.getDeclaredMethod("getX"); + getY = clazz2.getDeclaredMethod("getY"); + getZ = clazz2.getDeclaredMethod("getZ"); } - final int lx = (int) xm.invoke(pos) & 15; - final int ly = (int) ym.invoke(pos); - final int lz = (int) zm.invoke(pos) & 15; - final int j = MainUtil.CACHE_I[ly][lx][lz]; - final int k = MainUtil.CACHE_J[ly][lx][lz]; - final char[] array = fs.getIdArray(j); + int lx = (int) getX.invoke(pos) & 15; + int ly = (int) getY.invoke(pos); + int lz = (int) getZ.invoke(pos) & 15; + int j = MainUtil.CACHE_I[ly][lx][lz]; + int k = MainUtil.CACHE_J[ly][lx][lz]; + char[] array = fs.getIdArray(j); if (array == null) { continue; } if (array[k] != 0) { - iter.remove(); + iterator.remove(); } } @@ -178,7 +181,7 @@ public class FastQueue_1_8_3 extends SlowQueue { if (fs.getCount(j) == 0) { continue; } - final char[] newArray = fs.getIdArray(j); + char[] newArray = fs.getIdArray(j); if (newArray == null) { continue; } @@ -187,10 +190,10 @@ public class FastQueue_1_8_3 extends SlowQueue { section = sections[j] = newChunkSection(j << 4, flag, newArray); continue; } - final char[] currentArray = getIdArray(section); + char[] currentArray = getIdArray(section); boolean fill = true; for (int k = 0; k < newArray.length; k++) { - final char n = newArray[k]; + char n = newArray[k]; switch (n) { case 0: fill = false; @@ -209,8 +212,8 @@ public class FastQueue_1_8_3 extends SlowQueue { } } // Clear - } catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException | - NoSuchFieldException e) { + } catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException + | NoSuchFieldException e) { e.printStackTrace(); } int[][] biomes = fs.biomes; @@ -232,16 +235,16 @@ public class FastQueue_1_8_3 extends SlowQueue { } } - public Object newChunkSection(final int i, final boolean flag, final char[] ids) { - return classChunkSectionConstructor.create(i, flag, ids); + public Object newChunkSection(int i, boolean flag, char[] ids) { + return this.classChunkSectionConstructor.create(i, flag, ids); } - public char[] getIdArray(final Object obj) { - return (char[]) methodGetIdArray.of(obj).call(); + public char[] getIdArray(Object obj) { + return (char[]) this.methodGetIdArray.of(obj).call(); } /** - * This should be overridden by any specialized queues + * This should be overridden by any specialized queues. * @param wrap */ @Override @@ -251,13 +254,13 @@ public class FastQueue_1_8_3 extends SlowQueue { /** * This should be overridden by any specialized queues - * @param pc + * @param plotChunk */ @Override - public boolean fixLighting(PlotChunk pc, boolean fixAll) { + public boolean fixLighting(PlotChunk plotChunk, boolean fixAll) { try { - FastChunk_1_8_3 bc = (FastChunk_1_8_3) pc; - final Chunk chunk = bc.getChunk(); + FastChunk_1_8_3 bc = (FastChunk_1_8_3) plotChunk; + Chunk chunk = bc.getChunk(); if (!chunk.isLoaded()) { chunk.load(false); } else { @@ -266,12 +269,12 @@ public class FastQueue_1_8_3 extends SlowQueue { } // Initialize lighting - final Object c = methodGetHandleChunk.of(chunk).call(); + Object c = this.methodGetHandleChunk.of(chunk).call(); - if (fixAll && !(boolean) methodAreNeighborsLoaded.of(c).call(1)) { + if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) { World world = chunk.getWorld(); ChunkWrapper wrapper = bc.getChunkWrapper(); - String worldname = wrapper.world; + String worldName = wrapper.world; for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) { for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) { if (x != 0 && z != 0) { @@ -279,44 +282,46 @@ public class FastQueue_1_8_3 extends SlowQueue { while (!other.isLoaded()) { other.load(true); } - ChunkManager.manager.loadChunk(worldname, new ChunkLoc(x, z), true); + ChunkManager.manager.loadChunk(worldName, new ChunkLoc(x, z), true); } } } -// if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) { -// return false; -// } +/* + if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) { + return false; + } +*/ } - methodInitLighting.of(c).call(); + this.methodInitLighting.of(c).call(); - if ((bc.getTotalRelight() == 0 && !fixAll)) { + if (bc.getTotalRelight() == 0 && !fixAll) { return true; } - final Object[] sections = (Object[]) fieldSections.of(c).get(); - final Object w = fieldWorld.of(c).get(); + Object[] sections = (Object[]) this.fieldSections.of(c).get(); + Object w = this.fieldWorld.of(c).get(); - final int X = chunk.getX() << 4; - final int Z = chunk.getZ() << 4; + int X = chunk.getX() << 4; + int Z = chunk.getZ() << 4; - RefExecutor relight = methodX.of(w); + RefExecutor relight = this.methodX.of(w); for (int j = 0; j < sections.length; j++) { - final Object section = sections[j]; + Object section = sections[j]; if (section == null) { continue; } if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) { continue; } - final char[] array = getIdArray(section); + char[] array = getIdArray(section); int l = PseudoRandom.random.random(2); for (int k = 0; k < array.length; k++) { - final int i = array[k]; + int i = array[k]; if (i < 16) { continue; } - final short id = (short) (i >> 4); + short id = (short) (i >> 4); switch (id) { // Lighting default: if (!fixAll) { @@ -341,19 +346,19 @@ public class FastQueue_1_8_3 extends SlowQueue { case 130: case 138: case 169: - final int x = MainUtil.x_loc[j][k]; - final int y = MainUtil.y_loc[j][k]; - final int z = MainUtil.z_loc[j][k]; + int x = MainUtil.x_loc[j][k]; + int y = MainUtil.y_loc[j][k]; + int z = MainUtil.z_loc[j][k]; if (isSurrounded(sections, x, y, z)) { continue; } - final Object pos = classBlockPositionConstructor.create(X + x, y, Z + z); + Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); relight.call(pos); } } } return true; - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); } return false; @@ -389,17 +394,16 @@ public class FastQueue_1_8_3 extends SlowQueue { } /** - * This should be overridden by any specialized queues + * This should be overridden by any specialized queues. * @param world - * @param locs + * @param locations */ @Override - public void sendChunk(String world, Collection locs) { - World worldObj = BukkitUtil.getWorld(world); - for (ChunkLoc loc : locs) { + public void sendChunk(String world, Collection locations) { + for (ChunkLoc loc : locations) { ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); - toUpdate.remove(wrapper); + this.toUpdate.remove(wrapper); } - chunksender.sendChunk(world, locs); + this.chunksender.sendChunk(world, locations); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java index 974dbcf2c..f62120585 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java @@ -36,7 +36,7 @@ import java.util.Set; public class FastQueue_1_9 extends SlowQueue { private final Object air; - private final SendChunk chunksender; + private final SendChunk chunkSender; private final HashMap toUpdate = new HashMap<>(); private final RefMethod methodGetHandleChunk; private final RefMethod methodInitLighting; @@ -55,36 +55,36 @@ public class FastQueue_1_9 extends SlowQueue { public FastQueue_1_9() throws RuntimeException { RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); + this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); RefClass classChunk = getRefClass("{nms}.Chunk"); - methodInitLighting = classChunk.getMethod("initLighting"); + this.methodInitLighting = classChunk.getMethod("initLighting"); RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); + this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); RefClass classWorld = getRefClass("{nms}.World"); - methodW = classWorld.getMethod("w", classBlockPosition.getRealClass()); - fieldSections = classChunk.getField("sections"); - fieldWorld = classChunk.getField("world"); + this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass()); + this.fieldSections = classChunk.getField("sections"); + this.fieldWorld = classChunk.getField("world"); RefClass classBlock = getRefClass("{nms}.Block"); RefClass classIBlockData = getRefClass("{nms}.IBlockData"); - methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass()); - methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); + this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass()); + this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); - methodGetBlocks = classChunkSection.getMethod("getBlocks"); - methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class); - methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass()); - methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); - classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); - air = methodGetByCombinedId.call(0); - chunksender = new SendChunk(); + this.methodGetBlocks = classChunkSection.getMethod("getBlocks"); + this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class); + this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass()); + this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); + this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); + this.air = this.methodGetByCombinedId.call(0); + this.chunkSender = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.isEmpty()) { + if (FastQueue_1_9.this.toUpdate.isEmpty()) { return; } int count = 0; - final ArrayList chunks = new ArrayList<>(); - final Iterator> i = toUpdate.entrySet().iterator(); + ArrayList chunks = new ArrayList<>(); + Iterator> i = FastQueue_1_9.this.toUpdate.entrySet().iterator(); while (i.hasNext() && count < 128) { chunks.add(i.next().getValue()); i.remove(); @@ -99,12 +99,12 @@ public class FastQueue_1_9 extends SlowQueue { MainUtil.initCache(); } - public void update(final Collection chunks) { + public void update(Collection chunks) { if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { - for (final Chunk chunk : chunks) { + for (Chunk chunk : chunks) { chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); chunk.unload(true, true); chunk.load(); @@ -112,8 +112,8 @@ public class FastQueue_1_9 extends SlowQueue { return; } try { - chunksender.sendChunk(chunks); - } catch (final Throwable e) { + this.chunkSender.sendChunk(chunks); + } catch (Throwable e) { e.printStackTrace(); MainUtil.canSendChunk = false; } @@ -121,60 +121,60 @@ public class FastQueue_1_9 extends SlowQueue { /** * This should be overridden by any specialized queues - * @param pc + * @param plotChunk */ @Override - public void execute(PlotChunk pc) { - FastChunk_1_9 fs = (FastChunk_1_9) pc; - Chunk chunk = pc.getChunk(); - final World world = chunk.getWorld(); - ChunkWrapper wrapper = pc.getChunkWrapper(); - if (!toUpdate.containsKey(wrapper)) { - toUpdate.put(wrapper, chunk); + public void execute(PlotChunk plotChunk) { + FastChunk_1_9 fs = (FastChunk_1_9) plotChunk; + Chunk chunk = plotChunk.getChunk(); + World world = chunk.getWorld(); + ChunkWrapper wrapper = plotChunk.getChunkWrapper(); + if (!this.toUpdate.containsKey(wrapper)) { + this.toUpdate.put(wrapper, chunk); } chunk.load(true); try { - final boolean flag = world.getEnvironment() == Environment.NORMAL; + boolean flag = world.getEnvironment() == Environment.NORMAL; // Sections - final Method getHandele = chunk.getClass().getDeclaredMethod("getHandle"); - final Object c = getHandele.invoke(chunk); - final Class clazz = c.getClass(); - final Field sf = clazz.getDeclaredField("sections"); + Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); + Object c = getHandle.invoke(chunk); + Class clazz = c.getClass(); + Field sf = clazz.getDeclaredField("sections"); sf.setAccessible(true); - final Field tf = clazz.getDeclaredField("tileEntities"); - final Field entitySlices = clazz.getDeclaredField("entitySlices"); + Field tf = clazz.getDeclaredField("tileEntities"); + Field entitySlices = clazz.getDeclaredField("entitySlices"); - final Object[] sections = (Object[]) sf.get(c); - final HashMap tiles = (HashMap) tf.get(c); - final Collection[] entities = (Collection[]) entitySlices.get(c); + Object[] sections = (Object[]) sf.get(c); + HashMap tiles = (HashMap) tf.get(c); + Collection[] entities = (Collection[]) entitySlices.get(c); Method xm = null; Method ym = null; Method zm = null; // Trim tiles - final Set> entryset = (Set>) (Set) tiles.entrySet(); - final Iterator> iter = entryset.iterator(); - while (iter.hasNext()) { - final Entry tile = iter.next(); - final Object pos = tile.getKey(); + Set> entrySet = (Set>) (Set) tiles.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Entry tile = iterator.next(); + Object pos = tile.getKey(); if (xm == null) { - final Class clazz2 = pos.getClass().getSuperclass(); + Class clazz2 = pos.getClass().getSuperclass(); xm = clazz2.getDeclaredMethod("getX"); ym = clazz2.getDeclaredMethod("getY"); zm = clazz2.getDeclaredMethod("getZ"); } - final int lx = (int) xm.invoke(pos) & 15; - final int ly = (int) ym.invoke(pos); - final int lz = (int) zm.invoke(pos) & 15; - final int j = MainUtil.CACHE_I[ly][lx][lz]; - final int k = MainUtil.CACHE_J[ly][lx][lz]; - final int[] array = fs.getIdArray(j); + int lx = (int) xm.invoke(pos) & 15; + int ly = (int) ym.invoke(pos); + int lz = (int) zm.invoke(pos) & 15; + int j = MainUtil.CACHE_I[ly][lx][lz]; + int k = MainUtil.CACHE_J[ly][lx][lz]; + int[] array = fs.getIdArray(j); if (array == null) { continue; } if (array[k] != 0) { - iter.remove(); + iterator.remove(); } } @@ -190,7 +190,7 @@ public class FastQueue_1_9 extends SlowQueue { if (fs.getCount(j) == 0) { continue; } - final int[] newArray = fs.getIdArray(j); + int[] newArray = fs.getIdArray(j); if (newArray == null) { continue; } @@ -206,11 +206,11 @@ public class FastQueue_1_9 extends SlowQueue { section = sections[j] = newChunkSection(j << 4, flag, array); continue; } - final Object currentArray = getBlocks(section); - RefExecutor setType = methodSetType.of(section); + Object currentArray = getBlocks(section); + RefExecutor setType = this.methodSetType.of(section); boolean fill = true; for (int k = 0; k < newArray.length; k++) { - final int n = newArray[k]; + int n = newArray[k]; switch (n) { case 0: fill = false; @@ -220,15 +220,15 @@ public class FastQueue_1_9 extends SlowQueue { int x = MainUtil.x_loc[j][k]; int y = MainUtil.y_loc[j][k]; int z = MainUtil.z_loc[j][k]; - setType.call(x, y & 15, z, air); + setType.call(x, y & 15, z, this.air); continue; } default: { int x = MainUtil.x_loc[j][k]; int y = MainUtil.y_loc[j][k]; int z = MainUtil.z_loc[j][k]; - Object iblock = methodGetByCombinedId.call((int) n); - setType.call(x, y & 15, z, iblock); + Object iBlock = this.methodGetByCombinedId.call((int) n); + setType.call(x, y & 15, z, iBlock); } } } @@ -260,12 +260,12 @@ public class FastQueue_1_9 extends SlowQueue { } } - public Object newChunkSection(final int i, final boolean flag, final char[] ids) { - return classChunkSectionConstructor.create(i, flag, ids); + public Object newChunkSection(int i, boolean flag, char[] ids) { + return this.classChunkSectionConstructor.create(i, flag, ids); } - public Object getBlocks(final Object obj) { - return methodGetBlocks.of(obj).call(); + public Object getBlocks(Object obj) { + return this.methodGetBlocks.of(obj).call(); } /** @@ -285,7 +285,7 @@ public class FastQueue_1_9 extends SlowQueue { public boolean fixLighting(PlotChunk pc, boolean fixAll) { try { FastChunk_1_9 bc = (FastChunk_1_9) pc; - final Chunk chunk = bc.getChunk(); + Chunk chunk = bc.getChunk(); if (!chunk.isLoaded()) { chunk.load(false); } else { @@ -294,9 +294,9 @@ public class FastQueue_1_9 extends SlowQueue { } // Initialize lighting - final Object c = methodGetHandleChunk.of(chunk).call(); + Object c = this.methodGetHandleChunk.of(chunk).call(); - if (fixAll && !(boolean) methodAreNeighborsLoaded.of(c).call(1)) { + if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) { World world = chunk.getWorld(); ChunkWrapper wrapper = bc.getChunkWrapper(); String worldname = wrapper.world; @@ -313,36 +313,36 @@ public class FastQueue_1_9 extends SlowQueue { } } - methodInitLighting.of(c).call(); + this.methodInitLighting.of(c).call(); if (bc.getTotalRelight() == 0 && !fixAll) { return true; } - final Object[] sections = (Object[]) fieldSections.of(c).get(); - final Object w = fieldWorld.of(c).get(); + Object[] sections = (Object[]) this.fieldSections.of(c).get(); + Object w = this.fieldWorld.of(c).get(); - final int X = chunk.getX() << 4; - final int Z = chunk.getZ() << 4; + int X = chunk.getX() << 4; + int Z = chunk.getZ() << 4; - RefExecutor relight = methodW.of(w); + RefExecutor relight = this.methodW.of(w); for (int j = 0; j < sections.length; j++) { - final Object section = sections[j]; + Object section = sections[j]; if (section == null) { continue; } if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) { continue; } - final int[] array = bc.getIdArray(j); + int[] array = bc.getIdArray(j); if (array != null) { int l = PseudoRandom.random.random(2); for (int k = 0; k < array.length; k++) { - final int i = array[k]; + int i = array[k]; if (i < 16) { continue; } - final short id = (short) (i >> 4); + short id = (short) (i >> 4); switch (id) { // Lighting default: if (!fixAll) { @@ -367,20 +367,20 @@ public class FastQueue_1_9 extends SlowQueue { case 130: case 138: case 169: - final int x = MainUtil.x_loc[j][k]; - final int y = MainUtil.y_loc[j][k]; - final int z = MainUtil.z_loc[j][k]; + int x = MainUtil.x_loc[j][k]; + int y = MainUtil.y_loc[j][k]; + int z = MainUtil.z_loc[j][k]; if (isSurrounded(bc.getIdArrays(), x, y, z)) { continue; } - final Object pos = classBlockPositionConstructor.create(X + x, y, Z + z); + Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); relight.call(pos); } } } } return true; - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); } return false; @@ -397,7 +397,7 @@ public class FastQueue_1_9 extends SlowQueue { public boolean isSolid(int i) { if (i != 0) { Material material = Material.getMaterial(i); - return material != null && Material.getMaterial(i).isOccluding(); + return material != null && Material.getMaterial(i).isOccluding(); } return false; } @@ -420,8 +420,8 @@ public class FastQueue_1_9 extends SlowQueue { public int getId(Object section, int x, int y, int z) { int j = MainUtil.CACHE_J[y][x][z]; - Object iblock = methodGetType.of(section).call(x, y & 15, z); - return (int) methodGetCombinedId.call(iblock); + Object iBlock = this.methodGetType.of(section).call(x, y & 15, z); + return (int) this.methodGetCombinedId.call(iBlock); } public int getId(Object[] sections, int x, int y, int z) { @@ -436,26 +436,26 @@ public class FastQueue_1_9 extends SlowQueue { if (section == null) { return 0; } -// Object array = getBlocks(section); + // Object array = getBlocks(section); return getId(section, x, y, z); } /** * This should be overridden by any specialized queues * @param world - * @param locs + * @param locations */ @Override - public void sendChunk(final String world, final Collection locs) { + public void sendChunk(final String world, final Collection locations) { World worldObj = BukkitUtil.getWorld(world); - for (ChunkLoc loc : locs) { + for (ChunkLoc loc : locations) { ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); - toUpdate.remove(wrapper); + this.toUpdate.remove(wrapper); } TaskManager.runTaskLater(new Runnable() { @Override public void run() { - chunksender.sendChunk(world, locs); + FastQueue_1_9.this.chunkSender.sendChunk(world, locations); } }, 1); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java index a93ae4f64..8b0f2af43 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java @@ -33,40 +33,40 @@ public class GenChunk extends PlotChunk { @Override public Chunk getChunkAbs() { ChunkWrapper wrap = getChunkWrapper(); - if (chunk == null || wrap.x != chunk.getX() || wrap.z != chunk.getZ()) { - chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z); + if (this.chunk == null || wrap.x != this.chunk.getX() || wrap.z != this.chunk.getZ()) { + this.chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z); } - return chunk; + return this.chunk; } @Override public void setBiome(int x, int z, int biome) { - grid.setBiome(x, z, biomes[biome]); + this.grid.setBiome(x, z, this.biomes[biome]); } public void setBiome(int x, int z, Biome biome) { - if (grid != null) { - grid.setBiome(x, z, biome); + if (this.grid != null) { + this.grid.setBiome(x, z, biome); } } @Override public void setBlock(int x, int y, int z, int id, byte data) { - if (result == null) { - cd.setBlock(x, y, z, id, data); + if (this.result == null) { + this.cd.setBlock(x, y, z, id, data); return; } int i = MainUtil.CACHE_I[y][x][z]; - short[] v = result[i]; + short[] v = this.result[i]; if (v == null) { - result[i] = v = new short[4096]; + this.result[i] = v = new short[4096]; } int j = MainUtil.CACHE_J[y][x][z]; v[j] = (short) id; if (data != 0) { - byte[] vd = result_data[i]; + byte[] vd = this.result_data[i]; if (vd == null) { - result_data[i] = vd = new byte[4096]; + this.result_data[i] = vd = new byte[4096]; } vd[j] = data; } @@ -75,32 +75,32 @@ public class GenChunk extends PlotChunk { @Override public PlotChunk clone() { GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper()); - if (result != null) { - for (int i = 0; i < result.length; i++) { - short[] matrix = result[i]; + if (this.result != null) { + for (int i = 0; i < this.result.length; i++) { + short[] matrix = this.result[i]; if (matrix != null) { toReturn.result[i] = new short[matrix.length]; System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length); } } - for (int i = 0; i < result_data.length; i++) { - byte[] matrix = result_data[i]; + for (int i = 0; i < this.result_data.length; i++) { + byte[] matrix = this.result_data[i]; if (matrix != null) { toReturn.result_data[i] = new byte[matrix.length]; System.arraycopy(matrix, 0, toReturn.result_data[i], 0, matrix.length); } } } - toReturn.cd = cd; + toReturn.cd = this.cd; return toReturn; } @Override public PlotChunk shallowClone() { GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper()); - toReturn.result = result; - toReturn.result_data = result_data; - toReturn.cd = cd; + toReturn.result = this.result; + toReturn.result_data = this.result_data; + toReturn.cd = this.cd; return toReturn; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java index de679eab9..d31262fbb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java @@ -11,6 +11,7 @@ public class SlowChunk extends PlotChunk { public PlotBlock[][] result = new PlotBlock[16][]; public int[][] biomes; + public SlowChunk(ChunkWrapper chunk) { super(chunk); } @@ -23,25 +24,25 @@ public class SlowChunk extends PlotChunk { @Override public void setBiome(int x, int z, int biome) { - if (biomes == null) { - biomes = new int[16][16]; + if (this.biomes == null) { + this.biomes = new int[16][16]; } - biomes[x][z] = biome; + this.biomes[x][z] = biome; } @Override public void setBlock(int x, int y, int z, int id, byte data) { - if (result[y >> 4] == null) { - result[y >> 4] = new PlotBlock[4096]; + if (this.result[y >> 4] == null) { + this.result[y >> 4] = new PlotBlock[4096]; } - result[MainUtil.CACHE_I[y][x][z]][MainUtil.CACHE_J[y][x][z]] = new PlotBlock((short) id, data); + this.result[MainUtil.CACHE_I[y][x][z]][MainUtil.CACHE_J[y][x][z]] = new PlotBlock((short) id, data); } @Override public PlotChunk clone() { SlowChunk toReturn = new SlowChunk(getChunkWrapper()); - for (int i = 0; i < result.length; i++) { - PlotBlock[] matrix = result[i]; + for (int i = 0; i < this.result.length; i++) { + PlotBlock[] matrix = this.result[i]; if (matrix != null) { toReturn.result[i] = new PlotBlock[matrix.length]; System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length); @@ -53,7 +54,7 @@ public class SlowChunk extends PlotChunk { @Override public PlotChunk shallowClone() { SlowChunk toReturn = new SlowChunk(getChunkWrapper()); - toReturn.result = result; + toReturn.result = this.result; return toReturn; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java index b4751c249..f9a3c0bc8 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java @@ -30,18 +30,18 @@ public class SlowQueue implements PlotQueue { if (y > 255 || y < 0) { return false; } - final ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4); + ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4); x = x & 15; z = z & 15; - PlotChunk result = blocks.get(wrap); + PlotChunk result = this.blocks.get(wrap); if (result == null) { result = getChunk(wrap); result.setBlock(x, y, z, id, data); - final PlotChunk previous = blocks.put(wrap, result); + PlotChunk previous = this.blocks.put(wrap, result); if (previous == null) { return true; } - blocks.put(wrap, previous); + this.blocks.put(wrap, previous); result = previous; } result.setBlock(x, y, z, id, data); @@ -50,7 +50,7 @@ public class SlowQueue implements PlotQueue { @Override public void setChunk(PlotChunk chunk) { - blocks.put(chunk.getChunkWrapper(), chunk); + this.blocks.put(chunk.getChunkWrapper(), chunk); } @Override @@ -59,11 +59,11 @@ public class SlowQueue implements PlotQueue { throw new IllegalStateException("Must be called from main thread!"); } try { - if (blocks.isEmpty()) { + if (this.blocks.isEmpty()) { return null; } - final Iterator>> iter = blocks.entrySet().iterator(); - final PlotChunk toReturn = iter.next().getValue(); + Iterator>> iter = this.blocks.entrySet().iterator(); + PlotChunk toReturn = iter.next().getValue(); if (SetQueue.IMP.isWaiting()) { return null; } @@ -71,7 +71,7 @@ public class SlowQueue implements PlotQueue { execute(toReturn); fixLighting(toReturn, true); return toReturn; - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); return null; } @@ -83,17 +83,17 @@ public class SlowQueue implements PlotQueue { throw new IllegalStateException("Must be called from main thread!"); } try { - if (blocks.isEmpty()) { + if (this.blocks.isEmpty()) { return null; } - final PlotChunk toReturn = blocks.remove(wrap); + PlotChunk toReturn = this.blocks.remove(wrap); if (toReturn == null) { return null; } execute(toReturn); fixLighting(toReturn, fixLighting); return toReturn; - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); return null; } @@ -101,16 +101,16 @@ public class SlowQueue implements PlotQueue { @Override public void clear() { - blocks.clear(); + this.blocks.clear(); } /** - * This should be overriden by any specialized queues - * @param pc + * This should be overridden by any specialized queues. + * @param plotChunk */ - public void execute(PlotChunk pc) { - SlowChunk sc = (SlowChunk) pc; - Chunk chunk = pc.getChunk(); + public void execute(PlotChunk plotChunk) { + SlowChunk sc = (SlowChunk) plotChunk; + Chunk chunk = plotChunk.getChunk(); chunk.load(true); for (int i = 0; i < sc.result.length; i++) { PlotBlock[] result2 = sc.result[i]; @@ -118,9 +118,9 @@ public class SlowQueue implements PlotQueue { continue; } for (int j = 0; j < 4096; j++) { - final int x = MainUtil.x_loc[i][j]; - final int y = MainUtil.y_loc[i][j]; - final int z = MainUtil.z_loc[i][j]; + int x = MainUtil.x_loc[i][j]; + int y = MainUtil.y_loc[i][j]; + int z = MainUtil.z_loc[i][j]; Block block = chunk.getBlock(x, y, z); PlotBlock newBlock = result2[j]; if (newBlock == null) { @@ -252,7 +252,7 @@ public class SlowQueue implements PlotQueue { } /** - * This should be overriden by any specialized queues + * This should be overridden by any specialized queues. * @param wrap */ @Override @@ -261,7 +261,7 @@ public class SlowQueue implements PlotQueue { } /** - * This should be overriden by any specialized queues + * This should be overridden by any specialized queues. * @param fixAll */ @Override @@ -271,11 +271,11 @@ public class SlowQueue implements PlotQueue { } /** - * This should be overriden by any specialized queues - * @param locs + * This should be overridden by any specialized queues. + * @param locations */ @Override - public void sendChunk(String world, Collection locs) { + public void sendChunk(String world, Collection locations) { // Do nothing } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java index 697e3a979..48d5e50ca 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java @@ -1,41 +1,40 @@ package com.plotsquared.bukkit.uuid; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; - import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.object.BukkitOfflinePlayer; import com.plotsquared.bukkit.object.BukkitPlayer; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; + +import java.util.UUID; public class DefaultUUIDWrapper extends UUIDWrapper { @Override - public UUID getUUID(final PlotPlayer player) { + public UUID getUUID(PlotPlayer player) { return ((BukkitPlayer) player).player.getUniqueId(); } @Override - public UUID getUUID(final OfflinePlotPlayer player) { + public UUID getUUID(OfflinePlotPlayer player) { return player.getUUID(); } @Override - public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) { + public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); } @Override - public UUID getUUID(final String name) { + public UUID getUUID(String name) { return Bukkit.getOfflinePlayer(name).getUniqueId(); } @Override public OfflinePlotPlayer[] getOfflinePlayers() { - final OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); - final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; + OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); + BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; for (int i = 0; i < ops.length; i++) { toReturn[i] = new BukkitOfflinePlayer(ops[i]); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java index 0acb942f6..24c6fd691 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -19,6 +19,7 @@ import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.util.NbtFactory; import org.bukkit.Bukkit; import org.bukkit.World; + import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; @@ -32,18 +33,18 @@ import java.util.UUID; public class FileUUIDHandler extends UUIDHandlerImplementation { - public FileUUIDHandler(final UUIDWrapper wrapper) { + public FileUUIDHandler(UUIDWrapper wrapper) { super(wrapper); } @Override - public boolean startCaching(final Runnable whenDone) { + public boolean startCaching(Runnable whenDone) { return super.startCaching(whenDone) && cache(whenDone); } public boolean cache(final Runnable whenDone) { final File container = Bukkit.getWorldContainer(); - final List worlds = Bukkit.getWorlds(); + List worlds = Bukkit.getWorlds(); final String world; if (worlds.isEmpty()) { world = "world"; @@ -54,10 +55,10 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { @Override public void run() { PS.debug(C.PREFIX + "&6Starting player data caching for: " + world); - final File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt"); + File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt"); if (uuidfile.exists()) { try { - final List lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8); + List lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8); for (String line : lines) { try { line = line.trim(); @@ -65,55 +66,55 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { continue; } line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - final String[] split = line.split("\\|"); - final String name = split[0]; - if ((name.isEmpty()) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) { + String[] split = line.split("\\|"); + String name = split[0]; + if (name.isEmpty() || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) { continue; } - final UUID uuid = uuidWrapper.getUUID(name); + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); if (uuid == null) { continue; } UUIDHandler.add(new StringWrapper(name), uuid); - } catch (final Exception e2) { + } catch (Exception e2) { e2.printStackTrace(); } } - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); } } if (Settings.TWIN_MODE_UUID) { - final HashBiMap toAdd = HashBiMap.create(new HashMap()); + HashBiMap toAdd = HashBiMap.create(new HashMap()); toAdd.put(new StringWrapper("*"), DBFunc.everyone); - final HashSet all = UUIDHandler.getAllUUIDS(); + HashSet all = UUIDHandler.getAllUUIDS(); PS.debug("&aFast mode UUID caching enabled!"); - final File playerdataFolder = new File(container, world + File.separator + "playerdata"); - final String[] dat = playerdataFolder.list(new FilenameFilter() { + File playerdataFolder = new File(container, world + File.separator + "playerdata"); + String[] dat = playerdataFolder.list(new FilenameFilter() { @Override - public boolean accept(final File f, final String s) { + public boolean accept(File f, String s) { return s.endsWith(".dat"); } }); - final boolean check = all.isEmpty(); + boolean check = all.isEmpty(); if (dat != null) { - for (final String current : dat) { - final String s = current.replaceAll(".dat$", ""); + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); try { - final UUID uuid = UUID.fromString(s); + UUID uuid = UUID.fromString(s); if (check || all.remove(uuid)) { - final File file = new File(playerdataFolder + File.separator + current); - final InputSupplier is = com.google.common.io.Files.newInputStreamSupplier(file); - final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); - final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); - final String name = (String) bukkit.get("lastKnownName"); - final long last = (long) bukkit.get("lastPlayed"); + File file = new File(playerdataFolder + File.separator + current); + InputSupplier is = com.google.common.io.Files.newInputStreamSupplier(file); + NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); + NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); + String name = (String) bukkit.get("lastKnownName"); + long last = (long) bukkit.get("lastPlayed"); if (ExpireManager.IMP != null) { ExpireManager.IMP.storeDate(uuid, last); } toAdd.put(new StringWrapper(name), uuid); } - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); PS.debug(C.PREFIX + "Invalid playerdata: " + current); } @@ -129,45 +130,45 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files"); } } - final HashBiMap toAdd = HashBiMap.create(new HashMap()); + HashBiMap toAdd = HashBiMap.create(new HashMap()); toAdd.put(new StringWrapper("*"), DBFunc.everyone); - final HashSet worlds = new HashSet<>(); + HashSet worlds = new HashSet<>(); worlds.add(world); worlds.add("world"); - final HashSet uuids = new HashSet<>(); - final HashSet names = new HashSet<>(); + HashSet uuids = new HashSet<>(); + HashSet names = new HashSet<>(); File playerdataFolder = null; - for (final String worldname : worlds) { + for (String worldName : worlds) { // Getting UUIDs - playerdataFolder = new File(container, worldname + File.separator + "playerdata"); + playerdataFolder = new File(container, worldName + File.separator + "playerdata"); String[] dat = playerdataFolder.list(new FilenameFilter() { @Override - public boolean accept(final File f, final String s) { + public boolean accept(File f, String s) { return s.endsWith(".dat"); } }); if ((dat != null) && (dat.length != 0)) { - for (final String current : dat) { - final String s = current.replaceAll(".dat$", ""); + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); try { - final UUID uuid = UUID.fromString(s); + UUID uuid = UUID.fromString(s); uuids.add(uuid); - } catch (final Exception e) { + } catch (Exception e) { PS.debug(C.PREFIX + "Invalid playerdata: " + current); } } break; } // Getting names - final File playersFolder = new File(worldname + File.separator + "players"); + File playersFolder = new File(worldName + File.separator + "players"); dat = playersFolder.list(new FilenameFilter() { @Override - public boolean accept(final File f, final String s) { + public boolean accept(File f, String s) { return s.endsWith(".dat"); } }); if ((dat != null) && (dat.length != 0)) { - for (final String current : dat) { + for (String current : dat) { names.add(current.replaceAll(".dat$", "")); } break; @@ -175,21 +176,21 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } for (UUID uuid : uuids) { try { - final File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat"); + File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat"); if (!file.exists()) { continue; } - final ByteSource is = com.google.common.io.Files.asByteSource(file); - final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); - final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); - final String name = (String) bukkit.get("lastKnownName"); - final long last = (long) bukkit.get("lastPlayed"); + ByteSource is = com.google.common.io.Files.asByteSource(file); + NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); + NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); + String name = (String) bukkit.get("lastKnownName"); + long last = (long) bukkit.get("lastPlayed"); if (Settings.OFFLINE_MODE) { if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name)) { - uuid = uuidWrapper.getUUID(name); + uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); } else { - final long most = (long) compound.get("UUIDMost"); - final long least = (long) compound.get("UUIDLeast"); + long most = (long) compound.get("UUIDMost"); + long least = (long) compound.get("UUIDLeast"); uuid = new UUID(most, least); } } @@ -197,23 +198,23 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { ExpireManager.IMP.storeDate(uuid, last); } toAdd.put(new StringWrapper(name), uuid); - } catch (final Throwable e) { + } catch (Throwable e) { PS.debug(C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } - for (final String name : names) { - final UUID uuid = uuidWrapper.getUUID(name); - final StringWrapper nameWrap = new StringWrapper(name); + for (String name : names) { + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + StringWrapper nameWrap = new StringWrapper(name); toAdd.put(nameWrap, uuid); } if (getUUIDMap().isEmpty()) { - for (final OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers()) { - final long last = op.getLastPlayed(); + for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { + long last = op.getLastPlayed(); if (last != 0) { - final String name = op.getName(); - final StringWrapper wrap = new StringWrapper(name); - final UUID uuid = uuidWrapper.getUUID(op); + String name = op.getName(); + StringWrapper wrap = new StringWrapper(name); + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op); toAdd.put(wrap, uuid); if (ExpireManager.IMP != null) { ExpireManager.IMP.storeDate(uuid, last); @@ -235,7 +236,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - ifFetch.value = uuidWrapper.getUUID(name); + ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); TaskManager.runTask(ifFetch); } }); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java index 3ee8d6518..bc6a12bb9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java @@ -1,14 +1,5 @@ package com.plotsquared.bukkit.uuid; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.Server; -import org.bukkit.entity.Player; - import com.google.common.base.Charsets; import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.PS; @@ -17,50 +8,58 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.bukkit.object.BukkitOfflinePlayer; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.Server; +import org.bukkit.entity.Player; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.UUID; public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { - private Method getOnline = null; private final Object[] arg = new Object[0]; + private Method getOnline = null; public LowerOfflineUUIDWrapper() { try { - getOnline = Server.class.getMethod("getOnlinePlayers"); - } catch (final NoSuchMethodException | SecurityException e) { + this.getOnline = Server.class.getMethod("getOnlinePlayers"); + } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } @Override - public UUID getUUID(final PlotPlayer player) { + public UUID getUUID(PlotPlayer player) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } @Override - public UUID getUUID(final OfflinePlotPlayer player) { + public UUID getUUID(OfflinePlotPlayer player) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } @Override - public UUID getUUID(final OfflinePlayer player) { + public UUID getUUID(OfflinePlayer player) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } @Override - public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) { - final BiMap map = UUIDHandler.getUuidMap().inverse(); + public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { + BiMap map = UUIDHandler.getUuidMap().inverse(); String name; try { name = map.get(uuid).value; - } catch (final NullPointerException e) { + } catch (NullPointerException e) { name = null; } if (name != null) { - final OfflinePlayer op = Bukkit.getOfflinePlayer(name); + OfflinePlayer op = Bukkit.getOfflinePlayer(name); if (op.hasPlayedBefore()) { return new BukkitOfflinePlayer(op); } } - for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) { + for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { if (getUUID(player).equals(uuid)) { return new BukkitOfflinePlayer(player); } @@ -70,36 +69,35 @@ public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { @Override public Player[] getOnlinePlayers() { - if (getOnline == null) { + if (this.getOnline == null) { Collection onlinePlayers = Bukkit.getOnlinePlayers(); return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } try { - final Object players = getOnline.invoke(Bukkit.getServer(), arg); + Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); if (players instanceof Player[]) { return (Player[]) players; } else { - @SuppressWarnings("unchecked") - final Collection p = (Collection) players; + @SuppressWarnings("unchecked") Collection p = (Collection) players; return p.toArray(new Player[p.size()]); } - } catch (final Exception e) { + } catch (Exception e) { PS.debug("Failed to resolve online players"); - getOnline = null; + this.getOnline = null; Collection onlinePlayers = Bukkit.getOnlinePlayers(); return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } } @Override - public UUID getUUID(final String name) { + public UUID getUUID(String name) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); } @Override public OfflinePlotPlayer[] getOfflinePlayers() { - final OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); - final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; + OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); + BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; for (int i = 0; i < ops.length; i++) { toReturn[i] = new BukkitOfflinePlayer(ops[i]); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java index 69df39e7f..22086b90f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java @@ -1,14 +1,5 @@ package com.plotsquared.bukkit.uuid; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.Server; -import org.bukkit.entity.Player; - import com.google.common.base.Charsets; import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.PS; @@ -18,49 +9,57 @@ import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.object.BukkitOfflinePlayer; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.Server; +import org.bukkit.entity.Player; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.UUID; public class OfflineUUIDWrapper extends UUIDWrapper { - private Method getOnline = null; private final Object[] arg = new Object[0]; + private Method getOnline = null; public OfflineUUIDWrapper() { try { - getOnline = Server.class.getMethod("getOnlinePlayers"); - } catch (final NoSuchMethodException | SecurityException e) { + this.getOnline = Server.class.getMethod("getOnlinePlayers"); + } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } @Override - public UUID getUUID(final PlotPlayer player) { + public UUID getUUID(PlotPlayer player) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } @Override - public UUID getUUID(final OfflinePlotPlayer player) { + public UUID getUUID(OfflinePlotPlayer player) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } - - public UUID getUUID(final OfflinePlayer player) { + + public UUID getUUID(OfflinePlayer player) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } @Override - public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) { - final BiMap map = UUIDHandler.getUuidMap().inverse(); + public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { + BiMap map = UUIDHandler.getUuidMap().inverse(); String name; try { name = map.get(uuid).value; - } catch (final NullPointerException e) { + } catch (NullPointerException e) { name = null; } if (name != null) { - final OfflinePlayer op = Bukkit.getOfflinePlayer(name); + OfflinePlayer op = Bukkit.getOfflinePlayer(name); if (op.hasPlayedBefore()) { return new BukkitOfflinePlayer(op); } } - for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) { + for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { if (getUUID(player).equals(uuid)) { return new BukkitOfflinePlayer(player); } @@ -69,36 +68,35 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } public Player[] getOnlinePlayers() { - if (getOnline == null) { + if (this.getOnline == null) { Collection onlinePlayers = Bukkit.getOnlinePlayers(); return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } try { - final Object players = getOnline.invoke(Bukkit.getServer(), arg); + Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); if (players instanceof Player[]) { return (Player[]) players; } else { - @SuppressWarnings("unchecked") - final Collection p = (Collection) players; + @SuppressWarnings("unchecked") Collection p = (Collection) players; return p.toArray(new Player[p.size()]); } - } catch (final Exception e) { + } catch (Exception e) { PS.debug("Failed to resolve online players"); - getOnline = null; + this.getOnline = null; Collection onlinePlayers = Bukkit.getOnlinePlayers(); return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } } @Override - public UUID getUUID(final String name) { + public UUID getUUID(String name) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); } @Override public OfflinePlotPlayer[] getOfflinePlayers() { - final OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); - final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; + OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); + BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; for (int i = 0; i < ops.length; i++) { toReturn[i] = new BukkitOfflinePlayer(ops[i]); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java index 86d125820..0dea0d87b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -15,7 +15,9 @@ import com.intellectualcrafters.plot.uuid.UUIDWrapper; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; @@ -31,35 +33,34 @@ import java.util.UUID; public class SQLUUIDHandler extends UUIDHandlerImplementation { - final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; final int MAX_REQUESTS = 500; - final int INTERVAL = 12000; - final JSONParser jsonParser = new JSONParser(); - private final SQLite _sqLite; + private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; + private final int INTERVAL = 12000; + private final JSONParser jsonParser = new JSONParser(); + private final SQLite sqlite; - public SQLUUIDHandler(final UUIDWrapper wrapper) { + public SQLUUIDHandler(UUIDWrapper wrapper) { super(wrapper); - _sqLite = new SQLite("./plugins/PlotSquared/usercache.db"); + this.sqlite = new SQLite("./plugins/PlotSquared/usercache.db"); try { - _sqLite.openConnection(); - } catch (final Exception e) { + this.sqlite.openConnection(); + } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } - try { - final PreparedStatement stmt = getConnection().prepareStatement( - "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))"); + try (PreparedStatement stmt = getConnection().prepareStatement( + "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)" + + ")")) { stmt.execute(); - stmt.close(); - } catch (final SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } startCaching(null); } private Connection getConnection() { - synchronized (_sqLite) { - return _sqLite.getConnection(); + synchronized (this.sqlite) { + return this.sqlite.getConnection(); } } @@ -72,9 +73,9 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { @Override public void run() { try { - final HashBiMap toAdd = HashBiMap.create(new HashMap()); - final PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); - final ResultSet resultSet = statement.executeQuery(); + HashBiMap toAdd = HashBiMap.create(new HashMap()); + PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); + ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { StringWrapper username = new StringWrapper(resultSet.getString("username")); UUID uuid = UUID.fromString(resultSet.getString("uuid")); @@ -86,7 +87,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { // This should be called as long as there are some unknown plots final ArrayDeque toFetch = new ArrayDeque<>(); - for (final UUID u : UUIDHandler.getAllUUIDS()) { + for (UUID u : UUIDHandler.getAllUUIDS()) { if (!uuidExists(u)) { toFetch.add(u); } @@ -97,7 +98,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } return; } - final FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); + FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); fileHandler.startCaching(new Runnable() { @Override public void run() { @@ -122,70 +123,25 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } for (int i = 0; i < Math.min(500, toFetch.size()); i++) { UUID uuid = toFetch.pop(); - HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); + HttpURLConnection connection = + (HttpURLConnection) new URL(SQLUUIDHandler.this.PROFILE_URL + uuid.toString().replace("-", "")) + .openConnection(); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); - JSONObject response = (JSONObject) jsonParser.parse(reader); + JSONObject response = (JSONObject) SQLUUIDHandler.this.jsonParser.parse(reader); String name = (String) response.get("name"); if (name != null) { add(new StringWrapper(name), uuid); } } - } catch (Exception e) { + } catch (IOException | ParseException e) { e.printStackTrace(); } - TaskManager.runTaskLaterAsync(this, INTERVAL); + TaskManager.runTaskLaterAsync(this, SQLUUIDHandler.this.INTERVAL); } }); - /* - * This API is no longer accessible. - */ - // if (!Settings.OFFLINE_MODE) { - // PS.debug(C.PREFIX.s() + "&cWill fetch &6" + toFetch.size() + "&c from mojang!"); - // - // int i = 0; - // final Iterator iterator = toFetch.iterator(); - // while (iterator.hasNext()) { - // final StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user="); - // final List currentIteration = new ArrayList<>(); - // while ((i++ <= 15) && iterator.hasNext()) { - // final UUID _uuid = iterator.next(); - // url.append(_uuid.toString()); - // if (iterator.hasNext()) { - // url.append(","); - // } - // currentIteration.add(_uuid); - // } - // PS.debug(C.PREFIX.s() + "&cWill attempt to fetch &6" + currentIteration.size() + "&c uuids from: &6" + url.toString()); - // try { - // final HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection(); - // connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - // final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - // String line; - // final StringBuilder rawJSON = new StringBuilder(); - // while ((line = reader.readLine()) != null) { - // rawJSON.append(line); - // } - // reader.close(); - // final JSONObject object = new JSONObject(rawJSON.toString()); - // for (final UUID _u : currentIteration) { - // final Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username"); - // if ((o == null) || !(o instanceof String)) { - // continue; - // } - // add(new StringWrapper(o.toString()), _u); - // } - // } catch (final Exception e) { - // e.printStackTrace(); - // } - // i = 0; - // } - // } - // if (whenDone != null) { - // whenDone.run(); - // } } }); - } catch (final SQLException e) { + } catch (SQLException e) { throw new SQLUUIDHandlerException("Couldn't select :s", e); } } @@ -203,7 +159,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { @Override public void run() { try { - URL url = new URL(PROFILE_URL); + URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); @@ -215,12 +171,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { stream.write(body.getBytes()); stream.flush(); stream.close(); - JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); + JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); JSONObject jsonProfile = (JSONObject) array.get(0); String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); - ifFetch.value = UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); - } catch (Exception e) { + ifFetch.value = UUID.fromString( + id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id + .substring(20, 32)); + } catch (IOException | ParseException e) { e.printStackTrace(); } TaskManager.runTask(ifFetch); @@ -233,7 +191,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { super.handleShutdown(); try { getConnection().close(); - } catch (final SQLException e) { + } catch (SQLException e) { throw new SQLUUIDHandlerException("Couldn't close database connection", e); } } @@ -245,13 +203,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - try { - final PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)"); + try (PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { statement.setString(1, uuid.toString()); statement.setString(2, name.toString()); statement.execute(); PS.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); - } catch (final SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -270,13 +227,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - try { - final PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?"); + try (PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { statement.setString(1, name.value); statement.setString(2, uuid.toString()); statement.execute(); PS.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + "'"); - } catch (final SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -285,7 +241,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { private class SQLUUIDHandlerException extends RuntimeException { - SQLUUIDHandlerException(final String s, final Throwable c) { + SQLUUIDHandlerException(String s, Throwable c) { super("SQLUUIDHandler caused an exception: " + s, c); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java index 9ea662411..b85fddb02 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java @@ -21,221 +21,225 @@ import java.io.File; import java.util.List; public interface IPlotMain { - + /** - * Log a message to console + * Log a message to console. * @param message */ - void log(final String message); - + void log(String message); + /** - * Get the `PlotSquared` directory (e.g. /plugins/PlotSquared or /mods/PlotSquared) + * Get the `PlotSquared` directory. * @return */ File getDirectory(); - + /** - * Get the directory containing all the worlds + * Get the directory containing all the worlds. * @return */ File getWorldContainer(); - + /** - * Wrap a player into a PlotPlayer object - * @param obj + * Wrap a player into a PlotPlayer object. + * @param player * @return */ - PlotPlayer wrapPlayer(final Object obj); - + PlotPlayer wrapPlayer(Object player); + /** - * Disable the implementation - * - If a full disable isn't feasibly, just disable what it can + * Disable the implementation. + * + *
    + *
  • If a full disable isn't feasibly, just disable what it can.
  • + *
*/ void disable(); - + /** - * Get the version of the PlotSquared being used + * Get the version of the PlotSquared being used. * @return */ int[] getPluginVersion(); - + /** - * Get the version of Minecraft that is running - * (used to check what protocols and such are supported) + * Get the version of Minecraft that is running. * @return */ int[] getServerVersion(); - + /** - * Get the nms package prefix + * Get the nms package prefix. * @return */ String getNMSPackage(); - + /** - * Get the schematic handler + * Get the schematic handler. * @return */ SchematicHandler initSchematicHandler(); - + /** - * Get the schematic handler + * Get the schematic handler. * @return */ ChatManager initChatManager(); - + /** - * The task manager will run and manage minecraft tasks + * The task manager will run and manage Minecraft tasks. * @return */ TaskManager getTaskManager(); - + /** - * Run the task that will kill road mobs + * Run the task that will kill road mobs. */ void runEntityTask(); - + /** - * Register the implementation specific commands + * Register the implementation specific commands. */ void registerCommands(); - + /** - * Register the protection system (used to protect blocks and such) + * Register the protection system. */ void registerPlayerEvents(); - + /** - * Register inventory related events (used for inventory guis) + * Register inventory related events. */ void registerInventoryEvents(); - + /** - * Register plot plus related events (whatever these are?) + * Register plot plus related events. */ void registerPlotPlusEvents(); - + /** - * Register force field events (why is this a thing?) + * Register force field events. */ void registerForceFieldEvents(); - + /** - * Register the WorldEdit hook + * Register the WorldEdit hook. */ boolean initWorldEdit(); - + /** - * Get the economy provider + * Get the economy provider. * @return */ EconHandler getEconomyHandler(); - + /** - * Get the Plot Queue class + * Get the {@link PlotQueue} class. * @return */ PlotQueue initPlotQueue(); - + /** - * Get the World Util class + * Get the {@link WorldUtil} class. * @return */ WorldUtil initWorldUtil(); - + /** - * Get the EventUtil class + * Get the EventUtil class. * @return */ EventUtil initEventUtil(); - + /** - * Get the chunk manager + * Get the chunk manager. * @return */ ChunkManager initChunkManager(); - + /** - * Get the setuputils class (used for world creation) + * Get the {@link SetupUtils} class. * @return */ SetupUtils initSetupUtils(); - + /** - * Get HybridUtils class (common functions useful for hybrid world generation) + * Get {@link HybridUtils} class. * @return */ HybridUtils initHybridUtils(); - + /** - * Start the metrics task + * Start Metrics. */ void startMetrics(); - + /** - * If a world is already loaded, set the generator (use NMS if required) + * If a world is already loaded, set the generator (use NMS if required). * @param world */ - void setGenerator(final String world); - + void setGenerator(String world); + /** - * Get the UUIDHandlerImplementation which will cache and provide UUIDs + * Get the {@link UUIDHandlerImplementation} which will cache and provide UUIDs. * @return */ UUIDHandlerImplementation initUUIDHandler(); - + /** - * Get the InventoryUtil class (used for implementation specific inventory guis) + * Get the {@link InventoryUtil} class (used for implementation specific inventory guis). * @return */ InventoryUtil initInventoryUtil(); - + /** - * Run the converter for the implementation (not necessarily PlotMe, just any plugin that we can convert from) + * Run the converter for the implementation (not necessarily PlotMe, just any plugin that we can convert from). * @return */ boolean initPlotMeConverter(); - + /** - * Unregister a PlotPlayer from cache e.g. if they have logged off + * Unregister a PlotPlayer from cache e.g. if they have logged off. * @param player */ - void unregister(final PlotPlayer player); - + void unregister(PlotPlayer player); + /** - * Get the generator wrapper for a world (world) and generator (name) + * Get the generator wrapper for a world (world) and generator (name). * @param world * @param name * @return */ - GeneratorWrapper getGenerator(final String world, final String name); - + GeneratorWrapper getGenerator(String world, String name); + /** - * + * + * @param generator + * @return */ GeneratorWrapper wrapPlotGenerator(IndependentPlotGenerator generator); - + /** - * Register the chunk processor which will clean out chunks that have too many blockstates or entities + * Register the chunk processor which will clean out chunks that have too many blockstates or entities. */ void registerChunkProcessor(); - + /** - * Register the world initialization events (used to keep track of worlds being generated) + * Register the world initialization events (used to keep track of worlds being generated). */ void registerWorldEvents(); - + /** - * Get the name of the server + * Get the name of the server. * @return */ String getServerName(); - + /** - * Get the class that will manage player titles + * Get the class that will manage player titles. * @return */ AbstractTitle initTitleManager(); - + List getPluginIds(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PS.java b/Core/src/main/java/com/intellectualcrafters/plot/PS.java index 7c6cb45f1..e8e726521 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/PS.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/PS.java @@ -41,7 +41,7 @@ import com.intellectualcrafters.plot.util.ExpireManager; import com.intellectualcrafters.plot.util.InventoryUtil; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.PlotGamemode; +import com.intellectualcrafters.plot.util.PlotGameMode; import com.intellectualcrafters.plot.util.PlotWeather; import com.intellectualcrafters.plot.util.ReflectionUtils; import com.intellectualcrafters.plot.util.SchematicHandler; @@ -54,6 +54,7 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.area.QuadMap; import com.plotsquared.listener.WESubscriber; import com.sk89q.worldedit.WorldEdit; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -85,11 +86,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** - * An implementation of the core, - * with a static getter for easy access - * - * @author Sauilitired | Citymonstret - * @author boy0001 | Empire92 + * An implementation of the core, with a static getter for easy access. */ public class PS { @@ -97,11 +94,11 @@ public class PS { private static PS instance; private final HashSet plotareaHashCheck = new HashSet<>(); /** - * All plot areas mapped by world (quick world access) + * All plot areas mapped by world (quick world access). */ private final HashMap plotareamap = new HashMap<>(); /** - * All plot areas mapped by location (quick location based access) + * All plot areas mapped by location (quick location based access). */ private final HashMap> plotareagrid = new HashMap<>(); public HashMap> clusters_tmp; @@ -119,86 +116,86 @@ public class PS { public URL update; private boolean plotareaHasCollision = false; /** - * All plot areas (quick global access) + * All plot areas (quick global access). */ private PlotArea[] plotareas = new PlotArea[0]; // private: private File storageFile; - private File FILE = null; // This file - private int[] VERSION = null; - private int[] LAST_VERSION; - private String PLATFORM = null; + private File file = null; // This file + private int[] version = null; + private int[] lastVersion; + private String platform = null; private Database database; private Thread thread; /** - * Initialize PlotSquared with the desired Implementation class + * Initialize PlotSquared with the desired Implementation class. * @param imp_class */ - public PS(final IPlotMain imp_class, final String platform) { + public PS(IPlotMain imp_class, String platform) { try { instance = this; - thread = Thread.currentThread(); + this.thread = Thread.currentThread(); SetupUtils.generators = new HashMap<>(); - IMP = imp_class; - new ReflectionUtils(IMP.getNMSPackage()); + this.IMP = imp_class; + new ReflectionUtils(this.IMP.getNMSPackage()); try { URL url = PS.class.getProtectionDomain().getCodeSource().getLocation(); - FILE = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); + this.file = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); } catch (MalformedURLException | URISyntaxException | SecurityException | NullPointerException e) { e.printStackTrace(); - FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared.jar"); - if (!FILE.exists()) { - FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar"); + this.file = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared.jar"); + if (!this.file.exists()) { + this.file = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar"); } } - VERSION = IMP.getPluginVersion(); - PLATFORM = platform; + this.version = this.IMP.getPluginVersion(); + this.platform = platform; if (getJavaVersion() < 1.7) { log(C.CONSOLE_JAVA_OUTDATED_1_7); - IMP.disable(); + this.IMP.disable(); return; } if (getJavaVersion() < 1.8) { log(C.CONSOLE_JAVA_OUTDATED_1_8); } - TASK = IMP.getTaskManager(); + this.TASK = this.IMP.getTaskManager(); if (!C.ENABLED.s().isEmpty()) { log(C.ENABLED); } setupConfigs(); - translationFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "PlotSquared.use_THIS.yml"); - C.load(translationFile); + this.translationFile = new File(this.IMP.getDirectory() + File.separator + "translations" + File.separator + "PlotSquared.use_THIS.yml"); + C.load(this.translationFile); setupDefaultFlags(); setupDatabase(); CommentManager.registerDefaultInboxes(); // Tasks if (Settings.KILL_ROAD_MOBS || Settings.KILL_ROAD_VEHICLES) { - IMP.runEntityTask(); + this.IMP.runEntityTask(); } - if (IMP.initWorldEdit()) { - worldedit = WorldEdit.getInstance(); + if (this.IMP.initWorldEdit()) { + this.worldedit = WorldEdit.getInstance(); WorldEdit.getInstance().getEventBus().register(new WESubscriber()); MainCommand.getInstance().createCommand(new WE_Anywhere()); } // Events - IMP.registerCommands(); - IMP.registerPlayerEvents(); - IMP.registerInventoryEvents(); - IMP.registerPlotPlusEvents(); - IMP.registerForceFieldEvents(); - IMP.registerWorldEvents(); + this.IMP.registerCommands(); + this.IMP.registerPlayerEvents(); + this.IMP.registerInventoryEvents(); + this.IMP.registerPlotPlusEvents(); + this.IMP.registerForceFieldEvents(); + this.IMP.registerWorldEvents(); if (Settings.METRICS) { - IMP.startMetrics(); + this.IMP.startMetrics(); } else { log(C.CONSOLE_PLEASE_ENABLE_METRICS); } if (Settings.CHUNK_PROCESSOR) { - IMP.registerChunkProcessor(); + this.IMP.registerChunkProcessor(); } // create UUIDWrapper - UUIDHandler.implementation = IMP.initUUIDHandler(); + UUIDHandler.implementation = this.IMP.initUUIDHandler(); TaskManager.runTaskLater(new Runnable() { @Override public void run() { @@ -206,7 +203,7 @@ public class PS { UUIDHandler.startCaching(new Runnable() { @Override public void run() { - for (final Plot plot : getPlots()) { + for (Plot plot : getPlots()) { if (plot.hasOwner() && plot.temp != -1) { if (UUIDHandler.getName(plot.owner) == null) { UUIDHandler.implementation.unknown.add(plot.owner); @@ -228,7 +225,7 @@ public class PS { @Override public void run() { - if (IMP.initPlotMeConverter()) { + if (PS.this.IMP.initPlotMeConverter()) { log("&c=== IMPORTANT ==="); log("&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PLOTME!"); log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); @@ -243,30 +240,30 @@ public class PS { } }, 20); // create event util class - EventUtil.manager = IMP.initEventUtil(); + EventUtil.manager = this.IMP.initEventUtil(); // create Hybrid utility class - HybridUtils.manager = IMP.initHybridUtils(); + HybridUtils.manager = this.IMP.initHybridUtils(); // Inventory utility class - InventoryUtil.manager = IMP.initInventoryUtil(); + InventoryUtil.manager = this.IMP.initInventoryUtil(); // create setup util class - SetupUtils.manager = IMP.initSetupUtils(); + SetupUtils.manager = this.IMP.initSetupUtils(); // World Util - WorldUtil.IMP = IMP.initWorldUtil(); + WorldUtil.IMP = this.IMP.initWorldUtil(); // Set block - SetQueue.IMP.queue = IMP.initPlotQueue(); + SetQueue.IMP.queue = this.IMP.initPlotQueue(); // Set chunk - ChunkManager.manager = IMP.initChunkManager(); + ChunkManager.manager = this.IMP.initChunkManager(); // Schematic handler - SchematicHandler.manager = IMP.initSchematicHandler(); + SchematicHandler.manager = this.IMP.initSchematicHandler(); // Titles - AbstractTitle.TITLE_CLASS = IMP.initTitleManager(); + AbstractTitle.TITLE_CLASS = this.IMP.initTitleManager(); // Chat - ChatManager.manager = IMP.initChatManager(); + ChatManager.manager = this.IMP.initChatManager(); // Economy TaskManager.runTask(new Runnable() { @Override public void run() { - EconHandler.manager = IMP.getEconomyHandler(); + EconHandler.manager = PS.this.IMP.getEconomyHandler(); } }); @@ -274,33 +271,34 @@ public class PS { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final URL url = Updater.getUpdate(); + URL url = Updater.getUpdate(); if (url != null) { - update = url; - } else if (LAST_VERSION == null) { + PS.this.update = url; + } else if (PS.this.lastVersion == null) { log("&aThanks for installing PlotSquared!"); - } else if (!PS.get().checkVersion(LAST_VERSION, VERSION)) { - log("&aThanks for updating from " + StringMan.join(LAST_VERSION, ".") + " to " + StringMan.join(VERSION, ".") + "!"); - DBFunc.dbManager.updateTables(LAST_VERSION); + } else if (!PS.get().checkVersion(PS.this.lastVersion, PS.this.version)) { + log("&aThanks for updating from " + StringMan.join(PS.this.lastVersion, ".") + " to " + StringMan.join(PS.this.version, ".") + + "!"); + DBFunc.dbManager.updateTables(PS.this.lastVersion); } } }); // World generators: - final ConfigurationSection section = config.getConfigurationSection("worlds"); + final ConfigurationSection section = this.config.getConfigurationSection("worlds"); if (section != null) { - for (final String world : section.getKeys(false)) { + for (String world : section.getKeys(false)) { if (world.equals("CheckingPlotSquaredGenerator")) { continue; } if (WorldUtil.IMP.isWorld(world)) { - IMP.setGenerator(world); + this.IMP.setGenerator(world); } } TaskManager.runTaskLater(new Runnable() { @Override public void run() { - for (final String world : section.getKeys(false)) { + for (String world : section.getKeys(false)) { if (world.equals("CheckingPlotSquaredGenerator")) { continue; } @@ -308,7 +306,7 @@ public class PS { PS.debug("&c`" + world + "` was not properly loaded - PlotSquared will now try to load it properly: "); PS.debug("&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); PS.debug("&8 - &7Your world management plugin may be faulty (or non existant)"); - IMP.setGenerator(world); + PS.this.IMP.setGenerator(world); } } } @@ -324,13 +322,13 @@ public class PS { copyFile("s_chinese.yml", "translations"); copyFile("italian.yml", "translations"); showDebug(); - } catch (final Throwable e) { + } catch (Throwable e) { e.printStackTrace(); } } /** - * Get the instance of PlotSquared + * Get the instance of PlotSquared. * * @return the instance created by IPlotMain */ @@ -339,12 +337,12 @@ public class PS { } /** - * Log a message to the IPlotMain logger + * Log a message to the IPlotMain logger. * * @param message Message to log * @see IPlotMain#log(String) */ - public static void log(final Object message) { + public static void log(Object message) { get().IMP.log(StringMan.getString(message)); } @@ -353,18 +351,18 @@ public class PS { } /** - * Log a message to the IPlotMain logger + * Log a message to the IPlotMain logger. * * @param message Message to log * @see IPlotMain#log(String) */ - public static void debug(final Object message) { + public static void debug(Object message) { if (Settings.DEBUG) { log(message); } } - public boolean isMainThread(final Thread thread) { + public boolean isMainThread(Thread thread) { return this.thread == thread; } @@ -374,7 +372,7 @@ public class PS { * @param version2 * @return true if `version` is >= `version2` */ - public boolean checkVersion(final int[] version, int... version2) { + public boolean checkVersion(int[] version, int... version2) { return version[0] > version2[0] || version[0] == version2[0] && version[1] > version2[1] || version[0] == version2[0] && version[1] == version2[1] && version[2] >= version2[2]; } @@ -384,7 +382,7 @@ public class PS { * @return last version in config or null */ public int[] getLastVersion() { - return LAST_VERSION; + return this.lastVersion; } /** @@ -392,7 +390,7 @@ public class PS { * @return current version in config or null */ public int[] getVersion() { - return VERSION; + return this.version; } /** @@ -401,7 +399,7 @@ public class PS { * @return The server platform */ public String getPlatform() { - return PLATFORM; + return this.platform; } /** @@ -411,25 +409,26 @@ public class PS { * @see Database#getConnection() To get the database connection */ public Database getDatabase() { - return database; + return this.database; } /** - * Get the relevant plot area for a location.
- * - If there is only one plot area globally that will be returned
- * - If there is only one plot area in the world, it will return that
- * - If the plot area for a location cannot be unambiguously resolved; null will be returned
- *
+ * Get the relevant plot area for a location. + *
    + *
  • If there is only one plot area globally that will be returned
  • + *
  • If there is only one plot area in the world, it will return that
  • + *
  • If the plot area for a location cannot be unambiguously resolved; null will be returned
  • + *
* Note: An applicable plot area may not include the location i.e. clusters - * @param loc + * @param location * @return */ - public PlotArea getApplicablePlotArea(Location loc) { - switch (plotareas.length) { + public PlotArea getApplicablePlotArea(Location location) { + switch (this.plotareas.length) { case 0: return null; case 1: - return plotareas[0]; + return this.plotareas[0]; case 2: case 3: case 4: @@ -437,18 +436,18 @@ public class PS { case 6: case 7: case 8: - String world = loc.getWorld(); + String world = location.getWorld(); int hash = world.hashCode(); - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { if (hash == area.worldhash) { - if (area.contains(loc.getX(), loc.getZ()) && (!plotareaHasCollision || world.equals(area.worldname))) { + if (area.contains(location.getX(), location.getZ()) && (!this.plotareaHasCollision || world.equals(area.worldname))) { return area; } } } return null; default: - PlotArea[] areas = plotareamap.get(loc.getWorld()); + PlotArea[] areas = this.plotareamap.get(location.getWorld()); if (areas == null) { return null; } @@ -464,8 +463,8 @@ public class PS { case 6: case 7: case 8: - x = loc.getX(); - y = loc.getY(); + x = location.getX(); + y = location.getY(); for (PlotArea area : areas) { if (area.contains(x, y)) { return area; @@ -473,14 +472,14 @@ public class PS { } return null; default: - QuadMap search = plotareagrid.get(loc.getWorld()); - return search.get(loc.getX(), loc.getZ()); + QuadMap search = this.plotareagrid.get(location.getWorld()); + return search.get(location.getX(), location.getZ()); } } } public PlotArea getPlotArea(String world, String id) { - PlotArea[] areas = plotareamap.get(world); + PlotArea[] areas = this.plotareamap.get(world); if (areas == null) { return null; } @@ -499,7 +498,7 @@ public class PS { } public PlotArea getPlotAreaAbs(String world, String id) { - PlotArea[] areas = plotareamap.get(world); + PlotArea[] areas = this.plotareamap.get(world); if (areas == null) { return null; } @@ -513,9 +512,9 @@ public class PS { public PlotArea getPlotAreaByString(String search) { String[] split = search.split(";|,"); - PlotArea[] areas = plotareamap.get(split[0]); + PlotArea[] areas = this.plotareamap.get(split[0]); if (areas == null) { - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { if (area.worldname.equalsIgnoreCase(split[0])) { if (area.id == null || split.length == 2 && area.id.equalsIgnoreCase(split[1])) { return area; @@ -539,24 +538,26 @@ public class PS { } public Set getPlotAreas(String world, RegionWrapper region) { - QuadMap areas = plotareagrid.get(world); + QuadMap areas = this.plotareagrid.get(world); return areas != null ? areas.get(region) : new HashSet(); } /** - * Get the plot area which contains a location.
- * - If the plot area does not contain a location, null will be returned + * Get the plot area which contains a location. + *
    + *
  • If the plot area does not contain a location, null will be returned.
  • + *
* - * @param loc + * @param location * @return */ - public PlotArea getPlotAreaAbs(Location loc) { - switch (plotareas.length) { + public PlotArea getPlotAreaAbs(Location location) { + switch (this.plotareas.length) { case 0: return null; case 1: - PlotArea pa = plotareas[0]; - return pa.contains(loc) ? pa : null; + PlotArea pa = this.plotareas[0]; + return pa.contains(location) ? pa : null; case 2: case 3: case 4: @@ -564,18 +565,18 @@ public class PS { case 6: case 7: case 8: - String world = loc.getWorld(); + String world = location.getWorld(); int hash = world.hashCode(); - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { if (hash == area.worldhash) { - if (area.contains(loc.getX(), loc.getZ()) && (!plotareaHasCollision || world.equals(area.worldname))) { + if (area.contains(location.getX(), location.getZ()) && (!this.plotareaHasCollision || world.equals(area.worldname))) { return area; } } } return null; default: - PlotArea[] areas = plotareamap.get(loc.getWorld()); + PlotArea[] areas = this.plotareamap.get(location.getWorld()); if (areas == null) { return null; } @@ -584,7 +585,7 @@ public class PS { switch (areas.length) { case 0: PlotArea a = areas[0]; - return a.contains(loc.getX(), loc.getZ()) ? a : null; + return a.contains(location.getX(), location.getZ()) ? a : null; case 2: case 3: case 4: @@ -592,8 +593,8 @@ public class PS { case 6: case 7: case 8: - x = loc.getX(); - y = loc.getY(); + x = location.getX(); + y = location.getY(); for (PlotArea area : areas) { if (area.contains(x, y)) { return area; @@ -601,8 +602,8 @@ public class PS { } return null; default: - QuadMap search = plotareagrid.get(loc.getWorld()); - return search.get(loc.getX(), loc.getZ()); + QuadMap search = this.plotareagrid.get(location.getWorld()); + return search.get(location.getX(), location.getZ()); } } } @@ -611,22 +612,22 @@ public class PS { return plot.getArea().manager; } - public PlotManager getPlotManager(Location loc) { - PlotArea pa = getPlotAreaAbs(loc); + public PlotManager getPlotManager(Location location) { + PlotArea pa = getPlotAreaAbs(location); return pa != null ? pa.manager : null; } /** - * Add a global reference to a plot world + * Add a global reference to a plot world. * - * @param plotarea World Name + * @param plotarea The PlotArea * @see #removePlotArea(PlotArea) To remove the reference */ - public void addPlotArea(final PlotArea plotarea) { - HashMap plots = plots_tmp.remove(plotarea.toString()); + public void addPlotArea(PlotArea plotarea) { + HashMap plots = this.plots_tmp.remove(plotarea.toString()); if (plots == null) { if (plotarea.TYPE == 2) { - plots = plots_tmp.get(plotarea.worldname); + plots = this.plots_tmp.get(plotarea.worldname); if (plots != null) { Iterator> iter = plots.entrySet().iterator(); while (iter.hasNext()) { @@ -646,10 +647,10 @@ public class PS { } } if (Settings.ENABLE_CLUSTERS) { - Set clusters = clusters_tmp.remove(plotarea.toString()); + Set clusters = this.clusters_tmp.remove(plotarea.toString()); if (clusters == null) { if (plotarea.TYPE == 2) { - clusters = clusters_tmp.get(plotarea.worldname); + clusters = this.clusters_tmp.get(plotarea.worldname); if (clusters != null) { Iterator iter = clusters.iterator(); while (iter.hasNext()) { @@ -671,9 +672,9 @@ public class PS { Set globalAreas = getPlotAreas(); localAreas.add(plotarea); globalAreas.add(plotarea); - plotareas = globalAreas.toArray(new PlotArea[globalAreas.size()]); - plotareamap.put(plotarea.worldname, localAreas.toArray(new PlotArea[localAreas.size()])); - QuadMap map = plotareagrid.get(plotarea.worldname); + this.plotareas = globalAreas.toArray(new PlotArea[globalAreas.size()]); + this.plotareamap.put(plotarea.worldname, localAreas.toArray(new PlotArea[localAreas.size()])); + QuadMap map = this.plotareagrid.get(plotarea.worldname); if (map == null) { map = new QuadMap(Integer.MAX_VALUE, 0, 0) { @Override @@ -681,27 +682,27 @@ public class PS { return value.getRegion(); } }; - plotareagrid.put(plotarea.worldname, map); + this.plotareagrid.put(plotarea.worldname, map); } map.add(plotarea); } /** - * Remove a plot world reference + * Remove a plot world reference. * - * @param area World name + * @param area The PlotArea * @see #addPlotArea(PlotArea) To add a reference */ - public void removePlotArea(final PlotArea area) { + public void removePlotArea(PlotArea area) { Set areas = getPlotAreas(area.worldname); areas.remove(area); - plotareas = areas.toArray(new PlotArea[areas.size()]); + this.plotareas = areas.toArray(new PlotArea[areas.size()]); if (areas.isEmpty()) { - plotareamap.remove(area.worldname); - plotareagrid.remove(area.worldname); + this.plotareamap.remove(area.worldname); + this.plotareagrid.remove(area.worldname); } else { - plotareamap.put(area.worldname, areas.toArray(new PlotArea[areas.size()])); - plotareagrid.get(area.worldname).remove(area); + this.plotareamap.put(area.worldname, areas.toArray(new PlotArea[areas.size()])); + this.plotareagrid.get(area.worldname).remove(area); } setPlotsTmp(area); } @@ -713,21 +714,21 @@ public class PS { } private void setPlotsTmp(PlotArea area) { - if (plots_tmp == null) { - plots_tmp = new HashMap<>(); + if (this.plots_tmp == null) { + this.plots_tmp = new HashMap<>(); } - HashMap map = plots_tmp.get(area.toString()); + HashMap map = this.plots_tmp.get(area.toString()); if (map == null) { map = new HashMap<>(); - plots_tmp.put(area.toString(), map); + this.plots_tmp.put(area.toString(), map); } for (Plot plot : area.getPlots()) { map.put(plot.getId(), plot); } - if (clusters_tmp == null) { - clusters_tmp = new HashMap<>(); + if (this.clusters_tmp == null) { + this.clusters_tmp = new HashMap<>(); } - clusters_tmp.put(area.toString(), area.getClusters()); + this.clusters_tmp.put(area.toString(), area.getClusters()); } public Set getClusters(String world) { @@ -742,7 +743,7 @@ public class PS { } /** - * A more generic way to filter plots - make your own method if you need complex filters + * A more generic way to filter plots - make your own method if you need complex filters. * @param filters * @return */ @@ -751,14 +752,14 @@ public class PS { foreachPlotArea(new RunnableVal() { @Override public void run(PlotArea value) { - for (final PlotFilter filter : filters) { + for (PlotFilter filter : filters) { if (!filter.allowsArea(value)) { continue; } } for (Entry entry2 : value.getPlotEntries()) { Plot plot = entry2.getValue(); - for (final PlotFilter filter : filters) { + for (PlotFilter filter : filters) { if (!filter.allowsPlot(plot)) { continue; } @@ -771,8 +772,8 @@ public class PS { } /** - * Get all the plots in a single set - * @return Set of Plot + * Get all the plots in a single set. + * @return Set of Plots */ public Set getPlots() { int size = getPlotCount(); @@ -787,17 +788,17 @@ public class PS { } public void setPlots(HashMap> plots) { - if (plots_tmp == null) { - plots_tmp = new HashMap<>(); + if (this.plots_tmp == null) { + this.plots_tmp = new HashMap<>(); } for (Entry> entry : plots.entrySet()) { String world = entry.getKey(); PlotArea area = getPlotArea(world, null); if (area == null) { - HashMap map = plots_tmp.get(world); + HashMap map = this.plots_tmp.get(world); if (map == null) { map = new HashMap<>(); - plots_tmp.put(world, map); + this.plots_tmp.put(world, map); } map.putAll(entry.getValue()); } else { @@ -811,8 +812,8 @@ public class PS { } /** - * Get all the base plots in a single set (for merged plots it just returns the bottom plot) - * @return Set of base Plot + * Get all the base plots in a single set (for merged plots it just returns the bottom plot). + * @return Set of base Plots */ public Set getBasePlots() { int size = getPlotCount(); @@ -831,10 +832,10 @@ public class PS { return result; } - public ArrayList sortPlotsByTemp(final Collection plots) { + public ArrayList sortPlotsByTemp(Collection plots) { int max = 0; int overflowCount = 0; - for (final Plot plot : plots) { + for (Plot plot : plots) { if (plot.temp > 0) { if (plot.temp > max) { max = plot.temp; @@ -843,24 +844,24 @@ public class PS { overflowCount++; } } - final Plot[] array = new Plot[max + 1]; - final List overflow = new ArrayList<>(overflowCount); - for (final Plot plot : plots) { + Plot[] array = new Plot[max + 1]; + List overflow = new ArrayList<>(overflowCount); + for (Plot plot : plots) { if (plot.temp <= 0) { overflow.add(plot); } else { array[plot.temp] = plot; } } - final ArrayList result = new ArrayList<>(plots.size()); - for (final Plot plot : array) { + ArrayList result = new ArrayList<>(plots.size()); + for (Plot plot : array) { if (plot != null) { result.add(plot); } } Collections.sort(overflow, new Comparator() { @Override - public int compare(final Plot a, final Plot b) { + public int compare(Plot a, Plot b) { return a.hashCode() - b.hashCode(); } }); @@ -869,18 +870,18 @@ public class PS { } /** - * Sort plots by hashcode + * Sort plots by hashcode. * @param plots * @return * @deprecated Unchecked, please use {@link #sortPlots(Collection, SortType, PlotArea)} which has additional checks before calling this */ @Deprecated - public ArrayList sortPlotsByHash(final Collection plots) { + public ArrayList sortPlotsByHash(Collection plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; - for (final Plot plot : plots) { - final int hash = MathMan.getPositiveId(plot.hashCode()); + for (Plot plot : plots) { + int hash = MathMan.getPositiveId(plot.hashCode()); if (hash > max) { if (hash >= hardmax) { overflowSize++; @@ -890,11 +891,11 @@ public class PS { } } hardmax = Math.min(hardmax, max); - final Plot[] cache = new Plot[hardmax + 1]; - final List overflow = new ArrayList<>(overflowSize); - final ArrayList extra = new ArrayList<>(); - for (final Plot plot : plots) { - final int hash = MathMan.getPositiveId(plot.hashCode()); + Plot[] cache = new Plot[hardmax + 1]; + List overflow = new ArrayList<>(overflowSize); + ArrayList extra = new ArrayList<>(); + for (Plot plot : plots) { + int hash = MathMan.getPositiveId(plot.hashCode()); if (hash < hardmax) { if (hash >= 0) { cache[hash] = plot; @@ -907,28 +908,28 @@ public class PS { overflow.add(plot); } } - final Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); + Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); sortPlotsByHash(overflowArray); - final ArrayList result = new ArrayList<>(cache.length + overflowArray.length); - for (final Plot plot : cache) { + ArrayList result = new ArrayList<>(cache.length + overflowArray.length); + for (Plot plot : cache) { if (plot != null) { result.add(plot); } } Collections.addAll(result, overflowArray); - for (final Plot plot : extra) { + for (Plot plot : extra) { result.add(plot); } return result; } @Deprecated - public ArrayList sortPlotsByTimestamp(final Collection plots) { + public ArrayList sortPlotsByTimestamp(Collection plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; - for (final Plot plot : plots) { - final int hash = MathMan.getPositiveId(plot.hashCode()); + for (Plot plot : plots) { + int hash = MathMan.getPositiveId(plot.hashCode()); if (hash > max) { if (hash >= hardmax) { overflowSize++; @@ -938,11 +939,11 @@ public class PS { } } hardmax = Math.min(hardmax, max); - final Plot[] cache = new Plot[hardmax + 1]; - final List overflow = new ArrayList<>(overflowSize); - final ArrayList extra = new ArrayList<>(); - for (final Plot plot : plots) { - final int hash = MathMan.getPositiveId(plot.hashCode()); + Plot[] cache = new Plot[hardmax + 1]; + List overflow = new ArrayList<>(overflowSize); + ArrayList extra = new ArrayList<>(); + for (Plot plot : plots) { + int hash = MathMan.getPositiveId(plot.hashCode()); if (hash < hardmax) { if (hash >= 0) { cache[hash] = plot; @@ -955,29 +956,29 @@ public class PS { overflow.add(plot); } } - final Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); + Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); sortPlotsByHash(overflowArray); - final ArrayList result = new ArrayList<>(cache.length + overflowArray.length); - for (final Plot plot : cache) { + ArrayList result = new ArrayList<>(cache.length + overflowArray.length); + for (Plot plot : cache) { if (plot != null) { result.add(plot); } } Collections.addAll(result, overflowArray); - for (final Plot plot : extra) { + for (Plot plot : extra) { result.add(plot); } return result; } /** - * Sort plots by creation timestamp + * Sort plots by creation timestamp. * @param input * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks * @return */ @Deprecated - public List sortPlotsByModified(final Collection input) { + public List sortPlotsByModified(Collection input) { List list; if (input instanceof List) { list = (List) input; @@ -998,8 +999,8 @@ public class PS { * @param input */ @Deprecated - public void sortPlotsByHash(final Plot[] input) { - final List[] bucket = new ArrayList[32]; + public void sortPlotsByHash(Plot[] input) { + List[] bucket = new ArrayList[32]; for (int i = 0; i < bucket.length; i++) { bucket[i] = new ArrayList<>(); } @@ -1007,7 +1008,7 @@ public class PS { int placement = 1; while (!maxLength) { maxLength = true; - for (final Plot i : input) { + for (Plot i : input) { int tmp = MathMan.getPositiveId(i.hashCode()) / placement; bucket[tmp & 31].add(i); if (maxLength && tmp > 0) { @@ -1016,7 +1017,7 @@ public class PS { } int a = 0; for (int b = 0; b < 32; b++) { - for (final Plot i : bucket[b]) { + for (Plot i : bucket[b]) { input[a++] = i; } bucket[b].clear(); @@ -1026,28 +1027,28 @@ public class PS { } /** - * Sort a collection of plots by world (with a priority world), then by hashcode + * Sort a collection of plots by world (with a priority world), then by hashcode. * @param myplots * @param type The sorting method to use for each world (timestamp, or hash) - * @param priorityArea - Use null, "world" or "gibberish" if you want default world order + * @param priorityArea Use null, "world", or "gibberish" if you want default world order * @return ArrayList of plot */ - public ArrayList sortPlots(final Collection myplots, final SortType type, final PlotArea priorityArea) { + public ArrayList sortPlots(Collection myplots, SortType type, final PlotArea priorityArea) { // group by world // sort each - final HashMap> map = new HashMap<>(); + HashMap> map = new HashMap<>(); int totalSize = getPlotCount(); if (myplots.size() == totalSize) { - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { map.put(area, area.getPlots()); } } else { - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { map.put(area, new ArrayList(0)); } Collection lastList = null; PlotArea lastWorld = null; - for (final Plot plot : myplots) { + for (Plot plot : myplots) { if (lastWorld == plot.getArea()) { lastList.add(plot); } else { @@ -1057,18 +1058,18 @@ public class PS { } } } - List areas = Arrays.asList(plotareas); + List areas = Arrays.asList(this.plotareas); Collections.sort(areas, new Comparator() { @Override - public int compare(final PlotArea a, final PlotArea b) { + public int compare(PlotArea a, PlotArea b) { if (priorityArea != null && StringMan.isEqual(a.toString(), b.toString())) { return -1; } return a.hashCode() - b.hashCode(); } }); - final ArrayList toReturn = new ArrayList<>(myplots.size()); - for (final PlotArea area : areas) { + ArrayList toReturn = new ArrayList<>(myplots.size()); + for (PlotArea area : areas) { switch (type) { case CREATION_DATE: toReturn.addAll(sortPlotsByTemp(map.get(area))); @@ -1089,24 +1090,24 @@ public class PS { } /** - * Get all the plots owned by a player name + * Get all the plots owned by a player name. * @param world * @param player * @return Set of Plot */ - public Set getPlots(final String world, final String player) { - final UUID uuid = UUIDHandler.getUUID(player, null); + public Set getPlots(String world, String player) { + UUID uuid = UUIDHandler.getUUID(player, null); return getPlots(world, uuid); } /** - * Get all the plots owned by a player name + * Get all the plots owned by a player name. * @param area * @param player * @return Set of Plot */ - public Set getPlots(final PlotArea area, final String player) { - final UUID uuid = UUIDHandler.getUUID(player, null); + public Set getPlots(PlotArea area, String player) { + UUID uuid = UUIDHandler.getUUID(player, null); return getPlots(area, uuid); } @@ -1116,8 +1117,8 @@ public class PS { * @param player * @return Set of plot */ - public Set getPlots(final String world, final PlotPlayer player) { - final UUID uuid = player.getUUID(); + public Set getPlots(String world, PlotPlayer player) { + UUID uuid = player.getUUID(); return getPlots(world, uuid); } @@ -1127,8 +1128,8 @@ public class PS { * @param player * @return Set of plot */ - public Set getPlots(final PlotArea area, final PlotPlayer player) { - final UUID uuid = player.getUUID(); + public Set getPlots(PlotArea area, PlotPlayer player) { + UUID uuid = player.getUUID(); return getPlots(area, uuid); } @@ -1138,9 +1139,9 @@ public class PS { * @param uuid * @return Set of plot */ - public Set getPlots(final String world, final UUID uuid) { - final ArrayList myplots = new ArrayList<>(); - for (final Plot plot : getPlots(world)) { + public Set getPlots(String world, UUID uuid) { + ArrayList myplots = new ArrayList<>(); + for (Plot plot : getPlots(world)) { if (plot.hasOwner()) { if (plot.isOwnerAbs(uuid)) { myplots.add(plot); @@ -1156,9 +1157,9 @@ public class PS { * @param uuid * @return Set of plot */ - public Set getPlots(final PlotArea area, final UUID uuid) { - final ArrayList myplots = new ArrayList<>(); - for (final Plot plot : getPlots(area)) { + public Set getPlots(PlotArea area, UUID uuid) { + ArrayList myplots = new ArrayList<>(); + for (Plot plot : getPlots(area)) { if (plot.hasOwner()) { if (plot.isOwnerAbs(uuid)) { myplots.add(plot); @@ -1177,7 +1178,7 @@ public class PS { */ @Deprecated public boolean isPlotWorld(String world) { - return plotareamap.containsKey(world); + return this.plotareamap.containsKey(world); } /** @@ -1186,13 +1187,13 @@ public class PS { * @see #getPlotAreaByString(String) to get the PlotArea object * @return if a plot world is registered */ - public boolean hasPlotArea(final String world) { - switch (plotareas.length) { + public boolean hasPlotArea(String world) { + switch (this.plotareas.length) { case 0: return false; case 1: - PlotArea a = plotareas[0]; - return world.hashCode() == a.worldhash && (!plotareaHasCollision || a.worldname.equals(world)); + PlotArea a = this.plotareas[0]; + return world.hashCode() == a.worldhash && (!this.plotareaHasCollision || a.worldname.equals(world)); case 2: case 3: case 4: @@ -1201,18 +1202,18 @@ public class PS { case 7: case 8: int hash = world.hashCode(); - for (PlotArea area : plotareas) { - if (area.worldhash == hash && (!plotareaHasCollision || area.worldname.equals(world))) { + for (PlotArea area : this.plotareas) { + if (area.worldhash == hash && (!this.plotareaHasCollision || area.worldname.equals(world))) { return true; } } return false; default: - return plotareamap.containsKey(world); + return this.plotareamap.containsKey(world); } } - public Collection getPlots(final String world) { + public Collection getPlots(String world) { final HashSet set = new HashSet<>(); foreachPlotArea(world, new RunnableVal() { @Override @@ -1223,11 +1224,11 @@ public class PS { return set; } - public Collection getPlots(final PlotArea area) { + public Collection getPlots(PlotArea area) { return area == null ? new HashSet() : area.getPlots(); } - public Plot getPlot(PlotArea area, final PlotId id) { + public Plot getPlot(PlotArea area, PlotId id) { return area == null ? null : id == null ? null : area.getPlot(id); } @@ -1236,11 +1237,11 @@ public class PS { * @param player * @return Set of Plot */ - public Set getPlots(final PlotPlayer player) { + public Set getPlots(PlotPlayer player) { return getPlots(player.getUUID()); } - public Set getBasePlots(final PlotPlayer player) { + public Set getBasePlots(PlotPlayer player) { return getBasePlots(player.getUUID()); } @@ -1299,7 +1300,7 @@ public class PS { * @param callEvent If to call an event about the plot being removed * @return true if plot existed | false if it didn't */ - public boolean removePlot(Plot plot, final boolean callEvent) { + public boolean removePlot(Plot plot, boolean callEvent) { if (plot == null) { return false; } @@ -1308,8 +1309,8 @@ public class PS { } if (plot.getArea().removePlot(plot.getId())) { PlotId last = (PlotId) plot.getArea().getMeta("lastPlot"); - final int last_max = Math.max(Math.abs(last.x), Math.abs(last.y)); - final int this_max = Math.max(Math.abs(plot.getId().x), Math.abs(plot.getId().y)); + int last_max = Math.max(Math.abs(last.x), Math.abs(last.y)); + int this_max = Math.max(Math.abs(plot.getId().x), Math.abs(plot.getId().y)); if (this_max < last_max) { plot.getArea().setMeta("lastPlot", plot.getId()); } @@ -1330,19 +1331,19 @@ public class PS { * @param world The world to load * @param baseGenerator The generator for that world, or null if no generator */ - public void loadWorld(final String world, final GeneratorWrapper baseGenerator) { + public void loadWorld(String world, GeneratorWrapper baseGenerator) { if (world.equals("CheckingPlotSquaredGenerator")) { return; } - if (!plotareaHasCollision && !plotareaHashCheck.add(world.hashCode())) { - plotareaHasCollision = true; + if (!this.plotareaHasCollision && !this.plotareaHashCheck.add(world.hashCode())) { + this.plotareaHasCollision = true; } - final Set worlds = config.contains("worlds") ? config.getConfigurationSection("worlds").getKeys(false) : new HashSet(); - final String path = "worlds." + world; - ConfigurationSection worldSection = config.getConfigurationSection(path); + Set worlds = this.config.contains("worlds") ? this.config.getConfigurationSection("worlds").getKeys(false) : new HashSet(); + String path = "worlds." + world; + ConfigurationSection worldSection = this.config.getConfigurationSection(path); int type = worldSection != null ? worldSection.getInt("generator.type") : 0; if (type == 0) { - if (plotareamap.containsKey(world)) { + if (this.plotareamap.containsKey(world)) { PS.debug("World possibly already loaded: " + world); return; } @@ -1351,12 +1352,12 @@ public class PS { pg = baseGenerator.getPlotGenerator(); } else if (worldSection != null) { String secondaryGeneratorName = worldSection.getString("generator.plugin"); - GeneratorWrapper secondaryGenerator = IMP.getGenerator(world, secondaryGeneratorName); + GeneratorWrapper secondaryGenerator = this.IMP.getGenerator(world, secondaryGeneratorName); if (secondaryGenerator != null && secondaryGenerator.isFull()) { pg = secondaryGenerator.getPlotGenerator(); } else { String primaryGeneratorName = worldSection.getString("generator.init"); - GeneratorWrapper primaryGenerator = IMP.getGenerator(world, primaryGeneratorName); + GeneratorWrapper primaryGenerator = this.IMP.getGenerator(world, primaryGeneratorName); if (primaryGenerator != null && primaryGenerator.isFull()) { pg = primaryGenerator.getPlotGenerator(); } else { @@ -1373,15 +1374,15 @@ public class PS { log(C.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + pg); log(C.PREFIX + "&3 - plotworld: &7" + plotArea.getClass().getName()); log(C.PREFIX + "&3 - manager: &7" + plotManager.getClass().getName()); - if (!config.contains(path)) { - config.createSection(path); - worldSection = config.getConfigurationSection(path); + if (!this.config.contains(path)) { + this.config.createSection(path); + worldSection = this.config.getConfigurationSection(path); } plotArea.saveConfiguration(worldSection); plotArea.loadDefaultConfiguration(worldSection); try { - config.save(configFile); - } catch (final IOException e) { + this.config.save(this.configFile); + } catch (IOException e) { e.printStackTrace(); } // Now add it @@ -1394,14 +1395,14 @@ public class PS { } ConfigurationSection areasSection = worldSection.getConfigurationSection("areas"); if (areasSection == null) { - if (plotareamap.containsKey(world)) { + if (this.plotareamap.containsKey(world)) { PS.debug("World possibly already loaded: " + world); return; } log(C.PREFIX + "&aDetected world load for '" + world + "'"); String gen_string = worldSection.getString("generator.plugin", "PlotSquared"); if (type == 2) { - Set clusters = clusters_tmp != null ? clusters_tmp.get(world) : new HashSet(); + Set clusters = this.clusters_tmp != null ? this.clusters_tmp.get(world) : new HashSet(); if (clusters == null) { throw new IllegalArgumentException("No cluster exists for world: " + world); } @@ -1415,7 +1416,7 @@ public class PS { DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE log(C.PREFIX + "&3 - " + name + "-" + pos1 + "-" + pos2); - GeneratorWrapper areaGen = IMP.getGenerator(world, gen_string); + GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } @@ -1423,8 +1424,8 @@ public class PS { pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { - config.save(configFile); - } catch (final IOException e) { + this.config.save(this.configFile); + } catch (IOException e) { e.printStackTrace(); } log(C.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); @@ -1440,7 +1441,7 @@ public class PS { } return; } - GeneratorWrapper areaGen = IMP.getGenerator(world, gen_string); + GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } @@ -1448,8 +1449,8 @@ public class PS { pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { - config.save(configFile); - } catch (final IOException e) { + this.config.save(this.configFile); + } catch (IOException e) { e.printStackTrace(); } log(C.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + areaGen); @@ -1497,7 +1498,7 @@ public class PS { } } String gen_string = clone.getString("generator.plugin", "PlotSquared"); - GeneratorWrapper areaGen = IMP.getGenerator(world, gen_string); + GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } @@ -1519,8 +1520,8 @@ public class PS { } pa.loadDefaultConfiguration(clone); try { - config.save(configFile); - } catch (final IOException e) { + this.config.save(this.configFile); + } catch (IOException e) { e.printStackTrace(); } log(C.PREFIX + "&aDetected area load for '" + world + "'"); @@ -1541,59 +1542,59 @@ public class PS { * @param args The arguments * @return boolean | if valid arguments were provided */ - public boolean setupPlotWorld(final String world, final String args, IndependentPlotGenerator generator) { + public boolean setupPlotWorld(String world, String args, IndependentPlotGenerator generator) { if (args != null && !args.isEmpty()) { // save configuration - final String[] split = args.split(","); - final HybridPlotWorld plotworld = new HybridPlotWorld(world, null, generator, null, null); - for (final String element : split) { - final String[] pair = element.split("="); + String[] split = args.split(","); + HybridPlotWorld plotworld = new HybridPlotWorld(world, null, generator, null, null); + for (String element : split) { + String[] pair = element.split("="); if (pair.length != 2) { log("&cNo value provided for: &7" + element); return false; } - final String key = pair[0].toLowerCase(); - final String value = pair[1]; - final String base = "worlds." + world + "."; + String key = pair[0].toLowerCase(); + String value = pair[1]; + String base = "worlds." + world + "."; try { switch (key) { case "s": case "size": { - config.set(base + "plot.size", Configuration.INTEGER.parseString(value).shortValue()); + this.config.set(base + "plot.size", Configuration.INTEGER.parseString(value).shortValue()); break; } case "g": case "gap": { - config.set(base + "road.width", Configuration.INTEGER.parseString(value).shortValue()); + this.config.set(base + "road.width", Configuration.INTEGER.parseString(value).shortValue()); break; } case "h": case "height": { - config.set(base + "road.height", Configuration.INTEGER.parseString(value).shortValue()); - config.set(base + "plot.height", Configuration.INTEGER.parseString(value).shortValue()); - config.set(base + "wall.height", Configuration.INTEGER.parseString(value).shortValue()); + this.config.set(base + "road.height", Configuration.INTEGER.parseString(value).shortValue()); + this.config.set(base + "plot.height", Configuration.INTEGER.parseString(value).shortValue()); + this.config.set(base + "wall.height", Configuration.INTEGER.parseString(value).shortValue()); break; } case "f": case "floor": { - config.set(base + "plot.floor", + this.config.set(base + "plot.floor", new ArrayList<>(Arrays.asList(StringMan.join(Configuration.BLOCKLIST.parseString(value), ",").split(",")))); break; } case "m": case "main": { - config.set(base + "plot.filling", + this.config.set(base + "plot.filling", new ArrayList<>(Arrays.asList(StringMan.join(Configuration.BLOCKLIST.parseString(value), ",").split(",")))); break; } case "w": case "wall": { - config.set(base + "wall.filling", Configuration.BLOCK.parseString(value).toString()); + this.config.set(base + "wall.filling", Configuration.BLOCK.parseString(value).toString()); break; } case "b": case "border": { - config.set(base + "wall.block", Configuration.BLOCK.parseString(value).toString()); + this.config.set(base + "wall.block", Configuration.BLOCK.parseString(value).toString()); break; } default: { @@ -1601,17 +1602,17 @@ public class PS { return false; } } - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); log("&cInvalid value: &7" + value + " in arg " + element); return false; } } try { - ConfigurationSection section = config.getConfigurationSection("worlds." + world); + ConfigurationSection section = this.config.getConfigurationSection("worlds." + world); plotworld.saveConfiguration(section); plotworld.loadConfiguration(section); - config.save(configFile); + this.config.save(this.configFile); } catch (IOException e) { e.printStackTrace(); } @@ -1619,30 +1620,30 @@ public class PS { return true; } - public boolean canUpdate(final String current, final String other) { - final String s1 = normalisedVersion(current); - final String s2 = normalisedVersion(other); - final int cmp = s1.compareTo(s2); + public boolean canUpdate(String current, String other) { + String s1 = normalisedVersion(current); + String s2 = normalisedVersion(other); + int cmp = s1.compareTo(s2); return cmp < 0; } - public String normalisedVersion(final String version) { - final String[] split = Pattern.compile(".", Pattern.LITERAL).split(version); - final StringBuilder sb = new StringBuilder(); - for (final String s : split) { + public String normalisedVersion(String version) { + String[] split = Pattern.compile(".", Pattern.LITERAL).split(version); + StringBuilder sb = new StringBuilder(); + for (String s : split) { sb.append(String.format("%" + 4 + 's', s)); } return sb.toString(); } - public boolean update(final PlotPlayer sender, final URL url) { + public boolean update(PlotPlayer sender, URL url) { try { - final String name = FILE.getName(); - final File newJar = new File("plugins/update/" + name); + String name = this.file.getName(); + File newJar = new File("plugins/update/" + name); MainUtil.sendMessage(sender, "$1Downloading from provided URL: &7" + url); - final URLConnection con = url.openConnection(); + URLConnection con = url.openConnection(); try (InputStream stream = con.getInputStream()) { - final File parent = newJar.getParentFile(); + File parent = newJar.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } @@ -1671,23 +1672,23 @@ public class PS { * @param file Name of the file inside PlotSquared.jar * @param folder The output location relative to /plugins/PlotSquared/ */ - public void copyFile(final String file, final String folder) { + public void copyFile(String file, String folder) { try { - final File output = IMP.getDirectory(); + File output = this.IMP.getDirectory(); if (!output.exists()) { output.mkdirs(); } - final File newFile = MainUtil.getFile(output, folder + File.separator + file); + File newFile = MainUtil.getFile(output, folder + File.separator + file); if (newFile.exists()) { return; } - try (InputStream stream = IMP.getClass().getResourceAsStream(file)) { - final byte[] buffer = new byte[2048]; + try (InputStream stream = this.IMP.getClass().getResourceAsStream(file)) { + byte[] buffer = new byte[2048]; if (stream == null) { - try (ZipInputStream zis = new ZipInputStream(new FileInputStream(FILE))) { + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(this.file))) { ZipEntry ze = zis.getNextEntry(); while (ze != null) { - final String name = ze.getName(); + String name = ze.getName(); if (name.equals(file)) { new File(newFile.getParent()).mkdirs(); try (FileOutputStream fos = new FileOutputStream(newFile)) { @@ -1721,7 +1722,7 @@ public class PS { private Map> getPlotsRaw() { HashMap> map = new HashMap<>(); - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { Map map2 = map.get(area.toString()); if (map2 == null) { map.put(area.toString(), area.getPlotsRaw()); @@ -1737,8 +1738,8 @@ public class PS { */ public void disable() { try { - TASK = null; - database = null; + this.TASK = null; + this.database = null; // Validate that all data in the db is correct final HashSet plots = new HashSet<>(); foreachPlotRaw(new RunnableVal() { @@ -1752,7 +1753,7 @@ public class PS { // Close the connection DBFunc.close(); UUIDHandler.handleShutdown(); - } catch (final NullPointerException e) { + } catch (NullPointerException e) { log("&cCould not close database connection!"); } } @@ -1765,21 +1766,21 @@ public class PS { if (Settings.DB.USE_MONGO) { log(C.PREFIX + "MongoDB is not yet implemented"); log(C.PREFIX + "&cNo storage type is set!"); - IMP.disable(); + this.IMP.disable(); return; } if (DBFunc.dbManager == null) { if (Settings.DB.USE_MYSQL) { - database = new MySQL(Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); + this.database = new MySQL(Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); } else if (Settings.DB.USE_SQLITE) { - database = new SQLite(IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db"); + this.database = new SQLite(this.IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db"); } else { log(C.PREFIX + "&cNo storage type is set!"); - IMP.disable(); + this.IMP.disable(); return; } } - DBFunc.dbManager = new SQLManager(database, Settings.DB.PREFIX, false); + DBFunc.dbManager = new SQLManager(this.database, Settings.DB.PREFIX, false); this.plots_tmp = DBFunc.getPlots(); if (Settings.ENABLE_CLUSTERS) { this.clusters_tmp = DBFunc.getClusters(); @@ -1797,7 +1798,7 @@ public class PS { e.printStackTrace(); log("&d==== End of stacktrace ===="); log("&6Please go to the PlotSquared 'storage.yml' and configure the database correctly."); - IMP.disable(); + this.IMP.disable(); } } @@ -1807,21 +1808,23 @@ public class PS { * - Register with FlagManager and parse raw flag values */ public void setupDefaultFlags() { - final List booleanFlags = Arrays.asList("notify-enter", "notify-leave", "item-drop", "invincible", "instabreak", "drop-protection", "forcefield", "titles", "pve", "pvp", + List booleanFlags = + Arrays.asList("notify-enter", "notify-leave", "item-drop", "invincible", "instabreak", "drop-protection", "forcefield", "titles", + "pve", "pvp", "no-worldedit", "redstone"); - final List intervalFlags = Arrays.asList("feed", "heal"); - final List stringFlags = Arrays.asList("greeting", "farewell"); - final List intFlags = Arrays.asList("misc-cap", "entity-cap", "mob-cap", "animal-cap", "hostile-cap", "vehicle-cap", "music"); - for (final String flag : stringFlags) { + List intervalFlags = Arrays.asList("feed", "heal"); + List stringFlags = Arrays.asList("greeting", "farewell"); + List intFlags = Arrays.asList("misc-cap", "entity-cap", "mob-cap", "animal-cap", "hostile-cap", "vehicle-cap", "music"); + for (String flag : stringFlags) { FlagManager.addFlag(new AbstractFlag(flag)); } - for (final String flag : intervalFlags) { + for (String flag : intervalFlags) { FlagManager.addFlag(new AbstractFlag(flag, new FlagValue.IntervalValue())); } - for (final String flag : booleanFlags) { + for (String flag : booleanFlags) { FlagManager.addFlag(new AbstractFlag(flag, new FlagValue.BooleanValue())); } - for (final String flag : intFlags) { + for (String flag : intFlags) { FlagManager.addFlag(new AbstractFlag(flag, new FlagValue.UnsignedIntegerValue())); } FlagManager.addFlag(new AbstractFlag("done", new FlagValue.StringValue()), true); @@ -1858,7 +1861,7 @@ public class PS { FlagManager.addFlag(new AbstractFlag("snow-melt", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("keep") { @Override - public Object parseValueRaw(final String value) { + public Object parseValueRaw(String value) { if (MathMan.isInteger(value)) { return Long.parseLong(value); } @@ -1879,23 +1882,23 @@ public class PS { FlagManager.addFlag(new AbstractFlag("gamemode") { @Override - public PlotGamemode parseValueRaw(final String value) { + public PlotGameMode parseValueRaw(String value) { switch (value.toLowerCase()) { case "survival": case "s": case "0": - return PlotGamemode.SURVIVAL; + return PlotGameMode.SURVIVAL; case "creative": case "c": case "1": - return PlotGamemode.CREATIVE; + return PlotGameMode.CREATIVE; case "adventure": case "a": case "2": - return PlotGamemode.ADVENTURE; + return PlotGameMode.ADVENTURE; case "spectator": case "3": - return PlotGamemode.SPECTATOR; + return PlotGameMode.SPECTATOR; default: return null; } @@ -1911,7 +1914,7 @@ public class PS { FlagManager.addFlag(new AbstractFlag("weather") { @Override - public PlotWeather parseValueRaw(final String value) { + public PlotWeather parseValueRaw(String value) { switch (value.toLowerCase()) { case "rain": case "storm": @@ -1940,16 +1943,16 @@ public class PS { * Setup the default configuration (settings.yml) */ public void setupConfig() { - String lastVersionString = config.getString("version"); + String lastVersionString = this.config.getString("version"); if (lastVersionString != null) { String[] split = lastVersionString.split("\\."); - LAST_VERSION = new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]) }; + this.lastVersion = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; } - config.set("version", StringMan.join(VERSION, ".")); - config.set("platform", PLATFORM); + this.config.set("version", StringMan.join(this.version, ".")); + this.config.set("platform", this.platform); - final Map options = new HashMap<>(); + Map options = new HashMap<>(); // Command confirmation options.put("confirmation.setowner", Settings.CONFIRM_SETOWNER); options.put("confirmation.clear", Settings.CONFIRM_CLEAR); @@ -1996,8 +1999,8 @@ public class PS { options.put("clear.auto.calibration.variety_sd", 0); options.put("clear.auto.confirmation", Settings.AUTO_CLEAR_CONFIRMATION); // TODO FIXME - final int keep = config.getInt("clear.keep-if-modified"); - final int ignore = config.getInt("clear.ignore-if-modified"); + int keep = this.config.getInt("clear.keep-if-modified"); + int ignore = this.config.getInt("clear.ignore-if-modified"); if (keep > 0 || ignore > 0) { options.put("clear.auto.threshold", 1); options.put("clear.auto.enabled", false); @@ -2013,8 +2016,8 @@ public class PS { } else { options.put("clear.auto.threshold", Settings.CLEAR_THRESHOLD); } - config.set("clear.keep-if-modified", null); - config.set("clear.ignore-if-modified", null); + this.config.set("clear.keep-if-modified", null); + this.config.set("clear.ignore-if-modified", null); // Done options.put("approval.ratings.require-done", Settings.REQUIRE_DONE); @@ -2023,8 +2026,8 @@ public class PS { options.put("approval.done.required-for-download", Settings.DOWNLOAD_REQUIRES_DONE); // Schematics - if (StringMan.isEqual(config.getString("schematic.save_path"), "plugins/PlotSquared/schematics")) { - config.set("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); + if (StringMan.isEqual(this.config.getString("schematic.save_path"), "plugins/PlotSquared/schematics")) { + this.config.set("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); } options.put("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); options.put("bo3.save_path", Settings.BO3_SAVE_PATH); @@ -2077,133 +2080,133 @@ public class PS { options.put("debug", true); options.put("update-notifications", Settings.UPDATE_NOTIFICATIONS); - for (final Entry node : options.entrySet()) { - if (!config.contains(node.getKey())) { - config.set(node.getKey(), node.getValue()); + for (Entry node : options.entrySet()) { + if (!this.config.contains(node.getKey())) { + this.config.set(node.getKey(), node.getValue()); } } // Command confirmation - Settings.CONFIRM_SETOWNER = config.getBoolean("confirmation.setowner"); - Settings.CONFIRM_CLEAR = config.getBoolean("confirmation.clear"); - Settings.CONFIRM_DELETE = config.getBoolean("confirmation.delete"); - Settings.CONFIRM_UNLINK = config.getBoolean("confirmation.unlink"); + Settings.CONFIRM_SETOWNER = this.config.getBoolean("confirmation.setowner"); + Settings.CONFIRM_CLEAR = this.config.getBoolean("confirmation.clear"); + Settings.CONFIRM_DELETE = this.config.getBoolean("confirmation.delete"); + Settings.CONFIRM_UNLINK = this.config.getBoolean("confirmation.unlink"); // Protection - Settings.REDSTONE_DISABLER = config.getBoolean("protection.redstone.disable-offline"); - Settings.REDSTONE_DISABLER_UNOCCUPIED = config.getBoolean("protection.redstone.disable-unoccupied"); + Settings.REDSTONE_DISABLER = this.config.getBoolean("protection.redstone.disable-offline"); + Settings.REDSTONE_DISABLER_UNOCCUPIED = this.config.getBoolean("protection.redstone.disable-unoccupied"); // Clusters - Settings.ENABLE_CLUSTERS = config.getBoolean("clusters.enabled"); + Settings.ENABLE_CLUSTERS = this.config.getBoolean("clusters.enabled"); // PlotMe - Settings.USE_PLOTME_ALIAS = config.getBoolean("plotme-alias"); - Settings.CONVERT_PLOTME = config.getBoolean("plotme-convert.enabled"); - Settings.CACHE_PLOTME = config.getBoolean("plotme-convert.cache-uuids"); + Settings.USE_PLOTME_ALIAS = this.config.getBoolean("plotme-alias"); + Settings.CONVERT_PLOTME = this.config.getBoolean("plotme-convert.enabled"); + Settings.CACHE_PLOTME = this.config.getBoolean("plotme-convert.cache-uuids"); // UUID - Settings.USE_SQLUUIDHANDLER = config.getBoolean("uuid.use_sqluuidhandler"); - Settings.OFFLINE_MODE = config.getBoolean("UUID.offline"); - Settings.UUID_LOWERCASE = Settings.OFFLINE_MODE && config.getBoolean("UUID.force-lowercase"); - Settings.UUID_FROM_DISK = config.getBoolean("uuid.read-from-disk"); + Settings.USE_SQLUUIDHANDLER = this.config.getBoolean("uuid.use_sqluuidhandler"); + Settings.OFFLINE_MODE = this.config.getBoolean("UUID.offline"); + Settings.UUID_LOWERCASE = Settings.OFFLINE_MODE && this.config.getBoolean("UUID.force-lowercase"); + Settings.UUID_FROM_DISK = this.config.getBoolean("uuid.read-from-disk"); // Mob stuff - Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); - Settings.KILL_ROAD_VEHICLES = config.getBoolean("kill_road_vehicles"); + Settings.KILL_ROAD_MOBS = this.config.getBoolean("kill_road_mobs"); + Settings.KILL_ROAD_VEHICLES = this.config.getBoolean("kill_road_vehicles"); // Clearing + Expiry - Settings.FAST_CLEAR = config.getBoolean("clear.fastmode"); - Settings.DELETE_PLOTS_ON_BAN = config.getBoolean("clear.on.ban"); - Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); - Settings.CLEAR_THRESHOLD = config.getInt("clear.auto.threshold"); - Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); - Settings.CLEAR_INTERVAL = config.getInt("clear.auto.clear-interval-seconds"); + Settings.FAST_CLEAR = this.config.getBoolean("clear.fastmode"); + Settings.DELETE_PLOTS_ON_BAN = this.config.getBoolean("clear.on.ban"); + Settings.AUTO_CLEAR_DAYS = this.config.getInt("clear.auto.days"); + Settings.CLEAR_THRESHOLD = this.config.getInt("clear.auto.threshold"); + Settings.AUTO_CLEAR = this.config.getBoolean("clear.auto.enabled"); + Settings.CLEAR_INTERVAL = this.config.getInt("clear.auto.clear-interval-seconds"); // Clearing modifiers - PlotAnalysis.MODIFIERS.changes = config.getInt("clear.auto.calibration.changes"); - PlotAnalysis.MODIFIERS.faces = config.getInt("clear.auto.calibration.faces"); - PlotAnalysis.MODIFIERS.data = config.getInt("clear.auto.calibration.data"); - PlotAnalysis.MODIFIERS.air = config.getInt("clear.auto.calibration.air"); - PlotAnalysis.MODIFIERS.variety = config.getInt("clear.auto.calibration.variety"); - PlotAnalysis.MODIFIERS.changes_sd = config.getInt("clear.auto.calibration.changes_sd"); - PlotAnalysis.MODIFIERS.faces_sd = config.getInt("clear.auto.calibration.faces_sd"); - PlotAnalysis.MODIFIERS.data_sd = config.getInt("clear.auto.calibration.data_sd"); - PlotAnalysis.MODIFIERS.air_sd = config.getInt("clear.auto.calibration.air_sd"); - PlotAnalysis.MODIFIERS.variety_sd = config.getInt("clear.auto.calibration.variety_sd"); - Settings.AUTO_CLEAR_CONFIRMATION = config.getBoolean("clear.auto.confirmation"); // TODO FIXME + PlotAnalysis.MODIFIERS.changes = this.config.getInt("clear.auto.calibration.changes"); + PlotAnalysis.MODIFIERS.faces = this.config.getInt("clear.auto.calibration.faces"); + PlotAnalysis.MODIFIERS.data = this.config.getInt("clear.auto.calibration.data"); + PlotAnalysis.MODIFIERS.air = this.config.getInt("clear.auto.calibration.air"); + PlotAnalysis.MODIFIERS.variety = this.config.getInt("clear.auto.calibration.variety"); + PlotAnalysis.MODIFIERS.changes_sd = this.config.getInt("clear.auto.calibration.changes_sd"); + PlotAnalysis.MODIFIERS.faces_sd = this.config.getInt("clear.auto.calibration.faces_sd"); + PlotAnalysis.MODIFIERS.data_sd = this.config.getInt("clear.auto.calibration.data_sd"); + PlotAnalysis.MODIFIERS.air_sd = this.config.getInt("clear.auto.calibration.air_sd"); + PlotAnalysis.MODIFIERS.variety_sd = this.config.getInt("clear.auto.calibration.variety_sd"); + Settings.AUTO_CLEAR_CONFIRMATION = this.config.getBoolean("clear.auto.confirmation"); // TODO FIXME // Done - Settings.REQUIRE_DONE = config.getBoolean("approval.ratings.require-done"); - Settings.DONE_COUNTS_TOWARDS_LIMIT = config.getBoolean("approval.done.counts-towards-limit"); - Settings.DONE_RESTRICTS_BUILDING = config.getBoolean("approval.done.restrict-building"); - Settings.DOWNLOAD_REQUIRES_DONE = config.getBoolean("approval.done.required-for-download"); + Settings.REQUIRE_DONE = this.config.getBoolean("approval.ratings.require-done"); + Settings.DONE_COUNTS_TOWARDS_LIMIT = this.config.getBoolean("approval.done.counts-towards-limit"); + Settings.DONE_RESTRICTS_BUILDING = this.config.getBoolean("approval.done.restrict-building"); + Settings.DOWNLOAD_REQUIRES_DONE = this.config.getBoolean("approval.done.required-for-download"); // Schematics - Settings.SCHEMATIC_SAVE_PATH = config.getString("schematics.save_path"); + Settings.SCHEMATIC_SAVE_PATH = this.config.getString("schematics.save_path"); - Settings.BO3_SAVE_PATH = config.getString("bo3.save_path"); + Settings.BO3_SAVE_PATH = this.config.getString("bo3.save_path"); // Web - Settings.WEB_URL = config.getString("web.url"); - Settings.WEB_IP = config.getString("web.server-ip"); + Settings.WEB_URL = this.config.getString("web.url"); + Settings.WEB_IP = this.config.getString("web.server-ip"); // Caching - Settings.PERMISSION_CACHING = config.getBoolean("cache.permissions"); - Settings.CACHE_RATINGS = config.getBoolean("cache.ratings"); + Settings.PERMISSION_CACHING = this.config.getBoolean("cache.permissions"); + Settings.CACHE_RATINGS = this.config.getBoolean("cache.ratings"); // Rating system - Settings.RATING_CATEGORIES = config.getStringList("ratings.categories"); + Settings.RATING_CATEGORIES = this.config.getStringList("ratings.categories"); // Titles - Settings.TITLES = config.getBoolean("titles"); + Settings.TITLES = this.config.getBoolean("titles"); // Teleportation - Settings.TELEPORT_DELAY = config.getInt("teleport.delay"); - Settings.TELEPORT_ON_LOGIN = config.getBoolean("teleport.on_login"); + Settings.TELEPORT_DELAY = this.config.getInt("teleport.delay"); + Settings.TELEPORT_ON_LOGIN = this.config.getBoolean("teleport.on_login"); // WorldEdit - Settings.QUEUE_COMMANDS = config.getBoolean("worldedit.queue-commands"); - Settings.REQUIRE_SELECTION = config.getBoolean("worldedit.require-selection-in-mask"); - Settings.WE_ALLOW_HELPER = config.getBoolean("worldedit.enable-for-helpers"); - Settings.WE_MAX_VOLUME = config.getLong("worldedit.max-volume"); - Settings.WE_MAX_ITERATIONS = config.getLong("worldedit.max-iterations"); - Settings.WE_BLACKLIST = config.getStringList("worldedit.blacklist"); + Settings.QUEUE_COMMANDS = this.config.getBoolean("worldedit.queue-commands"); + Settings.REQUIRE_SELECTION = this.config.getBoolean("worldedit.require-selection-in-mask"); + Settings.WE_ALLOW_HELPER = this.config.getBoolean("worldedit.enable-for-helpers"); + Settings.WE_MAX_VOLUME = this.config.getLong("worldedit.max-volume"); + Settings.WE_MAX_ITERATIONS = this.config.getLong("worldedit.max-iterations"); + Settings.WE_BLACKLIST = this.config.getStringList("worldedit.blacklist"); // Chunk processor - Settings.CHUNK_PROCESSOR = config.getBoolean("chunk-processor.enabled"); - Settings.CHUNK_PROCESSOR_GC = config.getBoolean("chunk-processor.auto-unload"); - Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE = config.getBoolean("chunk-processor.auto-trim"); - Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT = config.getBoolean("chunk-processor.experimental-fast-async-worldedit"); - Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES = config.getInt("chunk-processor.max-blockstates"); - Settings.CHUNK_PROCESSOR_MAX_ENTITIES = config.getInt("chunk-processor.max-entities"); - Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS = config.getBoolean("chunk-processor.disable-physics"); + Settings.CHUNK_PROCESSOR = this.config.getBoolean("chunk-processor.enabled"); + Settings.CHUNK_PROCESSOR_GC = this.config.getBoolean("chunk-processor.auto-unload"); + Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE = this.config.getBoolean("chunk-processor.auto-trim"); + Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT = this.config.getBoolean("chunk-processor.experimental-fast-async-worldedit"); + Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES = this.config.getInt("chunk-processor.max-blockstates"); + Settings.CHUNK_PROCESSOR_MAX_ENTITIES = this.config.getInt("chunk-processor.max-entities"); + Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS = this.config.getBoolean("chunk-processor.disable-physics"); // Comments - Settings.COMMENT_NOTIFICATIONS = config.getBoolean("comments.notifications.enabled"); + Settings.COMMENT_NOTIFICATIONS = this.config.getBoolean("comments.notifications.enabled"); // Plot limits - Settings.MAX_AUTO_SIZE = config.getInt("claim.max-auto-area"); - Settings.MAX_PLOTS = config.getInt("max_plots"); + Settings.MAX_AUTO_SIZE = this.config.getInt("claim.max-auto-area"); + Settings.MAX_PLOTS = this.config.getInt("max_plots"); if (Settings.MAX_PLOTS > 32767) { log("&c`max_plots` Is set too high! This is a per player setting and does not need to be very large."); Settings.MAX_PLOTS = 32767; } - Settings.GLOBAL_LIMIT = config.getBoolean("global_limit"); + Settings.GLOBAL_LIMIT = this.config.getBoolean("global_limit"); // Misc - Settings.DEBUG = config.getBoolean("debug"); + Settings.DEBUG = this.config.getBoolean("debug"); if (Settings.DEBUG) { log(C.PREFIX + "&6Debug Mode Enabled (Default). Edit the config to turn this off."); } - Settings.CONSOLE_COLOR = config.getBoolean("console.color"); - if (!config.getBoolean("chat.fancy") || !checkVersion(IMP.getServerVersion(), 1, 8, 0)) { + Settings.CONSOLE_COLOR = this.config.getBoolean("console.color"); + if (!this.config.getBoolean("chat.fancy") || !checkVersion(this.IMP.getServerVersion(), 1, 8, 0)) { Settings.FANCY_CHAT = false; } - Settings.METRICS = config.getBoolean("metrics"); - Settings.UPDATE_NOTIFICATIONS = config.getBoolean("update-notifications"); - Settings.MERGE_REMOVES_ROADS = config.getBoolean("merge.remove-terrain"); - Settings.AUTO_PURGE = config.getBoolean("auto-purge", false); + Settings.METRICS = this.config.getBoolean("metrics"); + Settings.UPDATE_NOTIFICATIONS = this.config.getBoolean("update-notifications"); + Settings.MERGE_REMOVES_ROADS = this.config.getBoolean("merge.remove-terrain"); + Settings.AUTO_PURGE = this.config.getBoolean("auto-purge", false); } /** @@ -2213,55 +2216,55 @@ public class PS { * - Translation: PlotSquared.use_THIS.yml, style.yml
*/ public void setupConfigs() { - final File folder = new File(IMP.getDirectory() + File.separator + "config"); + File folder = new File(this.IMP.getDirectory() + File.separator + "config"); if (!folder.exists() && !folder.mkdirs()) { log(C.PREFIX + "&cFailed to create the /plugins/config folder. Please create it manually."); } try { - styleFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "style.yml"); - if (!styleFile.exists()) { - if (!styleFile.getParentFile().exists()) { - styleFile.getParentFile().mkdirs(); + this.styleFile = new File(this.IMP.getDirectory() + File.separator + "translations" + File.separator + "style.yml"); + if (!this.styleFile.exists()) { + if (!this.styleFile.getParentFile().exists()) { + this.styleFile.getParentFile().mkdirs(); } - if (!styleFile.createNewFile()) { + if (!this.styleFile.createNewFile()) { log("Could not create the style file, please create \"translations/style.yml\" manually"); } } - style = YamlConfiguration.loadConfiguration(styleFile); + this.style = YamlConfiguration.loadConfiguration(this.styleFile); setupStyle(); } catch (IOException err) { err.printStackTrace(); log("failed to save style.yml"); } try { - configFile = new File(IMP.getDirectory() + File.separator + "config" + File.separator + "settings.yml"); - if (!configFile.exists()) { - if (!configFile.createNewFile()) { + this.configFile = new File(this.IMP.getDirectory() + File.separator + "config" + File.separator + "settings.yml"); + if (!this.configFile.exists()) { + if (!this.configFile.createNewFile()) { log("Could not create the settings file, please create \"settings.yml\" manually."); } } - config = YamlConfiguration.loadConfiguration(configFile); + this.config = YamlConfiguration.loadConfiguration(this.configFile); setupConfig(); } catch (IOException err_trans) { log("Failed to save settings.yml"); } try { - storageFile = new File(IMP.getDirectory() + File.separator + "config" + File.separator + "storage.yml"); - if (!storageFile.exists()) { - if (!storageFile.createNewFile()) { + this.storageFile = new File(this.IMP.getDirectory() + File.separator + "config" + File.separator + "storage.yml"); + if (!this.storageFile.exists()) { + if (!this.storageFile.createNewFile()) { log("Could not the storage settings file, please create \"storage.yml\" manually."); } } - storage = YamlConfiguration.loadConfiguration(storageFile); + this.storage = YamlConfiguration.loadConfiguration(this.storageFile); setupStorage(); } catch (IOException err_trans) { log("Failed to save storage.yml"); } try { - style.save(styleFile); - config.save(configFile); - storage.save(storageFile); - } catch (final IOException e) { + this.style.save(this.styleFile); + this.config.save(this.configFile); + this.storage.save(this.storageFile); + } catch (IOException e) { log("Configuration file saving failed"); e.printStackTrace(); } @@ -2271,8 +2274,8 @@ public class PS { * Setup the storage file (load + save missing nodes) */ private void setupStorage() { - storage.set("version", StringMan.join(VERSION, ".")); - final Map options = new HashMap<>(9); + this.storage.set("version", StringMan.join(this.version, ".")); + Map options = new HashMap<>(9); options.put("mysql.use", false); options.put("sqlite.use", true); options.put("sqlite.db", "storage"); @@ -2282,20 +2285,20 @@ public class PS { options.put("mysql.password", "password"); options.put("mysql.database", "plot_db"); options.put("prefix", ""); - for (final Entry node : options.entrySet()) { - if (!storage.contains(node.getKey())) { - storage.set(node.getKey(), node.getValue()); + for (Entry node : options.entrySet()) { + if (!this.storage.contains(node.getKey())) { + this.storage.set(node.getKey(), node.getValue()); } } - Settings.DB.USE_MYSQL = storage.getBoolean("mysql.use"); - Settings.DB.USER = storage.getString("mysql.user"); - Settings.DB.PASSWORD = storage.getString("mysql.password"); - Settings.DB.HOST_NAME = storage.getString("mysql.host"); - Settings.DB.PORT = storage.getString("mysql.port"); - Settings.DB.DATABASE = storage.getString("mysql.database"); - Settings.DB.USE_SQLITE = storage.getBoolean("sqlite.use"); - Settings.DB.SQLITE_DB = storage.getString("sqlite.db"); - Settings.DB.PREFIX = storage.getString("prefix"); + Settings.DB.USE_MYSQL = this.storage.getBoolean("mysql.use"); + Settings.DB.USER = this.storage.getString("mysql.user"); + Settings.DB.PASSWORD = this.storage.getString("mysql.password"); + Settings.DB.HOST_NAME = this.storage.getString("mysql.host"); + Settings.DB.PORT = this.storage.getString("mysql.port"); + Settings.DB.DATABASE = this.storage.getString("mysql.database"); + Settings.DB.USE_SQLITE = this.storage.getBoolean("sqlite.use"); + Settings.DB.SQLITE_DB = this.storage.getString("sqlite.db"); + Settings.DB.PREFIX = this.storage.getString("prefix"); } /** @@ -2303,7 +2306,7 @@ public class PS { */ private void showDebug() { if (Settings.DEBUG) { - final Map settings = new HashMap<>(9); + Map settings = new HashMap<>(9); settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); settings.put("Use Metrics", "" + Settings.METRICS); settings.put("Delete Plots On Ban", "" + Settings.DELETE_PLOTS_ON_BAN); @@ -2313,7 +2316,7 @@ public class PS { settings.put("Auto Clear Days", "" + Settings.AUTO_CLEAR_DAYS); settings.put("Schematics Save Path", "" + Settings.SCHEMATIC_SAVE_PATH); settings.put("API Location", "" + Settings.API_URL); - for (final Entry setting : settings.entrySet()) { + for (Entry setting : settings.entrySet()) { log(C.PREFIX + String.format("&cKey: &6%s&c, Value: &6%s", setting.getKey(), setting.getValue())); } } @@ -2323,15 +2326,15 @@ public class PS { * Setup the style.yml file */ private void setupStyle() { - style.set("version", StringMan.join(VERSION, ".")); - final Map o = new HashMap<>(); + this.style.set("version", StringMan.join(this.version, ".")); + Map o = new HashMap<>(); o.put("color.1", "6"); o.put("color.2", "7"); o.put("color.3", "8"); o.put("color.4", "3"); - if (!style.contains("color")) { - for (final Entry node : o.entrySet()) { - style.set(node.getKey(), node.getValue()); + if (!this.style.contains("color")) { + for (Entry node : o.entrySet()) { + this.style.set(node.getKey(), node.getValue()); } } } @@ -2345,27 +2348,27 @@ public class PS { } public void foreachPlotArea(RunnableVal runnable) { - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { runnable.run(area); } } - public void foreachPlot(final RunnableVal runnable) { - for (PlotArea area : plotareas) { + public void foreachPlot(RunnableVal runnable) { + for (PlotArea area : this.plotareas) { for (Plot plot : area.getPlots()) { runnable.run(plot); } } } - public void foreachPlotRaw(final RunnableVal runnable) { - for (PlotArea area : plotareas) { + public void foreachPlotRaw(RunnableVal runnable) { + for (PlotArea area : this.plotareas) { for (Plot plot : area.getPlots()) { runnable.run(plot); } } - if (plots_tmp != null) { - for (Entry> entry : plots_tmp.entrySet()) { + if (this.plots_tmp != null) { + for (Entry> entry : this.plots_tmp.entrySet()) { for (Entry entry2 : entry.getValue().entrySet()) { runnable.run(entry2.getValue()); } @@ -2374,13 +2377,13 @@ public class PS { } public void foreachBasePlot(RunnableVal run) { - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { area.foreachBasePlot(run); } } public void foreachPlotArea(String world, RunnableVal runnable) { - PlotArea[] array = plotareamap.get(world); + PlotArea[] array = this.plotareamap.get(world); if (array == null) { return; } @@ -2390,28 +2393,28 @@ public class PS { } public PlotArea getFirstPlotArea() { - return plotareas.length > 0 ? plotareas[0] : null; + return this.plotareas.length > 0 ? this.plotareas[0] : null; } public int getPlotAreaCount() { - return plotareas.length; + return this.plotareas.length; } public int getPlotCount() { int count = 0; - for (PlotArea area : plotareas) { + for (PlotArea area : this.plotareas) { count += area.getPlotCount(); } return count; } public int getPlotAreaCount(String world) { - return plotareamap.size(); + return this.plotareamap.size(); } public Set getPlotAreas() { - HashSet set = new HashSet<>(plotareas.length); - Collections.addAll(set, plotareas); + HashSet set = new HashSet<>(this.plotareas.length); + Collections.addAll(set, this.plotareas); return set; } @@ -2421,15 +2424,15 @@ public class PS { */ @Deprecated public Set getPlotWorldStrings() { - HashSet set = new HashSet<>(plotareamap.size()); - for (Entry entry : plotareamap.entrySet()) { + HashSet set = new HashSet<>(this.plotareamap.size()); + for (Entry entry : this.plotareamap.entrySet()) { set.add(entry.getKey()); } return set; } public boolean isAugmented(String world) { - PlotArea[] areas = plotareamap.get(world); + PlotArea[] areas = this.plotareamap.get(world); if (areas == null) { return false; } @@ -2444,7 +2447,7 @@ public class PS { * @return Collection of PlotArea objects */ public Set getPlotAreas(String world) { - PlotArea[] areas = plotareamap.get(world); + PlotArea[] areas = this.plotareamap.get(world); if (areas == null) { return new HashSet<>(0); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/Updater.java b/Core/src/main/java/com/intellectualcrafters/plot/Updater.java index d996cab74..ec93baca7 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/Updater.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/Updater.java @@ -1,17 +1,17 @@ package com.intellectualcrafters.plot; +import static com.intellectualcrafters.plot.PS.log; + import com.intellectualcrafters.json.JSONArray; import com.intellectualcrafters.json.JSONObject; - import com.intellectualcrafters.plot.util.StringMan; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; -import static com.intellectualcrafters.plot.PS.log; - public class Updater { private static String readUrl(String urlString) { @@ -53,7 +53,12 @@ public class Updater { if (downloadURL.equals(name)) { try { String[] split = release.getString("name").split("\\."); - int[] version = new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), (split.length == 3) ? Integer.parseInt(split[2]) : 0 }; + int[] version; + if (split.length == 3) { + version = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; + } else { + version = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), 0}; + } URL url = new URL(asset.getString("browser_download_url")); // If current version >= update if (PS.get().checkVersion(PS.get().getVersion(), version)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java index 2ab3ab5f8..ca959394b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java @@ -20,8 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.UUID; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Location; @@ -34,24 +32,26 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.UUID; + @CommandDeclaration( -command = "add", -aliases = { "a" }, -description = "Allow a user to build while you are online", -usage = "/plot add ", -category = CommandCategory.SETTINGS, -permission = "plots.add", -requiredType = RequiredType.NONE) + command = "add", + aliases = {"a"}, + description = "Allow a user to build while you are online", + usage = "/plot add ", + category = CommandCategory.SETTINGS, + permission = "plots.add", + requiredType = RequiredType.NONE) public class Add extends SubCommand { - + public Add() { - requiredArguments = new Argument[] { Argument.PlayerName }; + this.requiredArguments = new Argument[]{Argument.PlayerName}; } - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + public boolean onCommand(PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } @@ -78,7 +78,7 @@ public class Add extends SubCommand { MainUtil.sendMessage(plr, C.ALREADY_OWNER); return false; } - + if (plot.getMembers().contains(uuid)) { MainUtil.sendMessage(plr, C.ALREADY_ADDED); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java index 3211c57d4..dd580cc02 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java @@ -31,17 +31,17 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "setalias", -permission = "plots.set.alias", -description = "Set the plot name", -usage = "/plot alias ", -aliases = { "alias", "sa", "name", "rename", "setname", "seta" }, -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + command = "setalias", + permission = "plots.set.alias", + description = "Set the plot name", + usage = "/plot alias ", + aliases = {"alias", "sa", "name", "rename", "setname", "seta"}, + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Alias extends SetCommand { @Override - public boolean set(final PlotPlayer plr, final Plot plot, final String alias) { + public boolean set(PlotPlayer plr, Plot plot, String alias) { if (alias.isEmpty()) { C.COMMAND_SYNTAX.send(plr, getUsage()); return false; @@ -54,7 +54,7 @@ public class Alias extends SetCommand { C.NOT_VALID_VALUE.send(plr); return false; } - for (final Plot p : PS.get().getPlots(plot.getArea())) { + for (Plot p : PS.get().getPlots(plot.getArea())) { if (p.getAlias().equalsIgnoreCase(alias)) { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java index 3a305828c..1684652ec 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java @@ -26,18 +26,19 @@ import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.IOException; import java.util.ArrayList; import java.util.Objects; import java.util.Set; @CommandDeclaration(command = "area", -permission = "plots.area", -category = CommandCategory.ADMINISTRATION, -requiredType = RequiredType.NONE, -description = "Create a new PlotArea", -aliases = "world", -usage = "/plot area ") + permission = "plots.area", + category = CommandCategory.ADMINISTRATION, + requiredType = RequiredType.NONE, + description = "Create a new PlotArea", + aliases = "world", + usage = "/plot area ") public class Area extends SubCommand { @Override @@ -71,7 +72,7 @@ public class Area extends SubCommand { plr.setMeta("area_pos1", loc); C.SET_ATTRIBUTE.send(plr, "area_pos1", loc.getX() + "," + loc.getZ()); MainUtil.sendMessage(plr, "You will now set pos2: /plot area create pos2" - + "\nNote: The chosen plot size may result in the created area not exactly matching your second position."); + + "\nNote: The chosen plot size may result in the created area not exactly matching your second position."); return true; } case "pos2": { // Set position 2 and finish creation for type=2 (partial) @@ -86,8 +87,8 @@ public class Area extends SubCommand { int dz = Math.abs(pos1.getZ() - pos2.getZ()); int numx = Math.max(1, (dx + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); int numz = Math.max(1, (dz + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); - final int ddx = dx - (numx * area.SIZE - area.ROAD_WIDTH); - final int ddz = dz - (numz * area.SIZE - area.ROAD_WIDTH); + int ddx = dx - (numx * area.SIZE - area.ROAD_WIDTH); + int ddz = dz - (numz * area.SIZE - area.ROAD_WIDTH); int bx = Math.min(pos1.getX(), pos2.getX()) + ddx; int bz = Math.min(pos1.getZ(), pos2.getZ()) + ddz; int tx = Math.max(pos1.getX(), pos2.getX()) - ddx; @@ -129,7 +130,7 @@ public class Area extends SubCommand { if (area.TERRAIN != 3) { ChunkManager.largeRegionTask(world, region, new RunnableVal() { @Override - public void run(final ChunkLoc value) { + public void run(ChunkLoc value) { AugmentedUtils.generate(world, value.x, value.z, null); } }, null); @@ -326,13 +327,13 @@ public class Area extends SubCommand { region = "N/A"; } String value = "&r$1NAME: " + name - + "\n$1Type: $2" + area.TYPE - + "\n$1Terrain: $2" + area.TERRAIN - + "\n$1Usage: $2" + String.format("%.2f", percent) + "%" - + "\n$1Claimed: $2" + claimed - + "\n$1Clusters: $2" + clusters - + "\n$1Region: $2" + region - + "\n$1Generator: $2" + generator; + + "\n$1Type: $2" + area.TYPE + + "\n$1Terrain: $2" + area.TERRAIN + + "\n$1Usage: $2" + String.format("%.2f", percent) + "%" + + "\n$1Claimed: $2" + claimed + + "\n$1Clusters: $2" + clusters + + "\n$1Region: $2" + region + + "\n$1Generator: $2" + generator; MainUtil.sendMessage(plr, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); return true; } @@ -379,19 +380,19 @@ public class Area extends SubCommand { region = "N/A"; } PlotMessage tooltip = new PlotMessage() - .text("Claimed=").color("$1").text("" + claimed).color("$2") - .text("\nUsage=").color("$1").text(String.format("%.2f", percent) + "%").color("$2") - .text("\nClusters=").color("$1").text("" + clusters).color("$2") - .text("\nRegion=").color("$1").text(region).color("$2") - .text("\nGenerator=").color("$1").text(generator).color("$2"); + .text("Claimed=").color("$1").text("" + claimed).color("$2") + .text("\nUsage=").color("$1").text(String.format("%.2f", percent) + "%").color("$2") + .text("\nClusters=").color("$1").text("" + clusters).color("$2") + .text("\nRegion=").color("$1").text(region).color("$2") + .text("\nGenerator=").color("$1").text(generator).color("$2"); // type / terrain String visit = "/plot area tp " + area.toString(); message.text("[").color("$3") - .text(i + "").command(visit).tooltip(visit).color("$1") - .text("]").color("$3") - .text(" " + name).tooltip(tooltip).command("/plot area info " + area).color("$1").text(" - ").color("$2") - .text(area.TYPE + ":" + area.TERRAIN).color("$3"); + .text(i + "").command(visit).tooltip(visit).color("$1") + .text("]").color("$3") + .text(" " + name).tooltip(tooltip).command("/plot area info " + area).color("$1").text(" - ").color("$2") + .text(area.TYPE + ":" + area.TERRAIN).color("$3"); } }, "/plot area list", C.AREA_LIST_HEADER_PAGED.s()); return true; @@ -442,7 +443,8 @@ public class Area extends SubCommand { center = WorldUtil.IMP.getSpawn(area.worldname); } else { RegionWrapper region = area.getRegion(); - center = new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, 0, region.minZ + (region.maxZ - region.minZ) / 2); + center = new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, 0, + region.minZ + (region.maxZ - region.minZ) / 2); center.setY(WorldUtil.IMP.getHighestBlock(area.worldname, center.getX(), center.getZ())); } plr.teleport(center); @@ -451,10 +453,10 @@ public class Area extends SubCommand { case "delete": case "remove": { MainUtil.sendMessage(plr, "$1World creation settings may be stored in multiple locations:" - + "\n$3 - $2Bukkit bukkit.yml" - + "\n$3 - $2PlotSquared settings.yml" - + "\n$3 - $2Multiverse worlds.yml (or any world management plugin)" - + "\n$1Stop the server and delete it from these locations."); + + "\n$3 - $2Bukkit bukkit.yml" + + "\n$3 - $2PlotSquared settings.yml" + + "\n$3 - $2Multiverse worlds.yml (or any world management plugin)" + + "\n$1Stop the server and delete it from these locations."); return true; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java index 349e8afd3..9bce97b75 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java @@ -33,17 +33,17 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "auto", -permission = "plots.auto", -category = CommandCategory.CLAIMING, -requiredType = RequiredType.NONE, -description = "Claim the nearest plot", -aliases = "a", -usage = "/plot auto [length,width]") + permission = "plots.auto", + category = CommandCategory.CLAIMING, + requiredType = RequiredType.NONE, + description = "Claim the nearest plot", + aliases = "a", + usage = "/plot auto [length,width]") public class Auto extends SubCommand { - public static PlotId getNextPlotId(final PlotId id, final int step) { - final int absX = Math.abs(id.x); - final int absY = Math.abs(id.y); + public static PlotId getNextPlotId(PlotId id, int step) { + int absX = Math.abs(id.x); + int absY = Math.abs(id.y); if (absX > absY) { if (id.x > 0) { return new PlotId(id.x, id.y + 1); @@ -71,7 +71,7 @@ public class Auto extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { PlotArea plotarea = plr.getApplicablePlotArea(); if (plotarea == null) { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); @@ -83,7 +83,7 @@ public class Auto extends SubCommand { if (args.length > 0) { if (Permissions.hasPermission(plr, "plots.auto.mega")) { try { - final String[] split = args[0].split(",|;"); + String[] split = args[0].split(",|;"); size_x = Integer.parseInt(split[0]); size_z = Integer.parseInt(split[1]); if (size_x < 1 || size_z < 1) { @@ -110,8 +110,8 @@ public class Auto extends SubCommand { MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, Settings.MAX_AUTO_SIZE + ""); return false; } - final int currentPlots = Settings.GLOBAL_LIMIT ? plr.getPlotCount() : plr.getPlotCount(plotarea.worldname); - final int diff = currentPlots - plr.getAllowedPlots(); + int currentPlots = Settings.GLOBAL_LIMIT ? plr.getPlotCount() : plr.getPlotCount(plotarea.worldname); + int diff = currentPlots - plr.getAllowedPlots(); if (diff + size_x * size_z > 0) { if (diff < 0) { MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); @@ -159,15 +159,15 @@ public class Auto extends SubCommand { } // TODO handle type 2 the same as normal worlds! if (plotarea.TYPE == 2) { - final PlotId bot = plotarea.getMin(); - final PlotId top = plotarea.getMax(); - final PlotId origin = new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2); + PlotId bot = plotarea.getMin(); + PlotId top = plotarea.getMax(); + PlotId origin = new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2); PlotId id = new PlotId(0, 0); - final int width = Math.max(top.x - bot.x + 1, top.y - bot.y + 1); - final int max = width * width; + int width = Math.max(top.x - bot.x + 1, top.y - bot.y + 1); + int max = width * width; // for (int i = 0; i <= max; i++) { - final PlotId currentId = new PlotId(origin.x + id.x, origin.y + id.y); + PlotId currentId = new PlotId(origin.x + id.x, origin.y + id.y); Plot current = plotarea.getPlotAbs(currentId); if (current.canClaim(plr)) { current.claim(plr, true, null); @@ -182,14 +182,14 @@ public class Auto extends SubCommand { plotarea.setMeta("lastPlot", new PlotId(0, 0)); boolean br = false; while (true) { - final PlotId start = getNextPlotId(getLastPlotId(plotarea), 1); - final PlotId end = new PlotId(start.x + size_x - 1, start.y + size_z - 1); + PlotId start = getNextPlotId(getLastPlotId(plotarea), 1); + PlotId end = new PlotId(start.x + size_x - 1, start.y + size_z - 1); plotarea.setMeta("lastPlot", start); if (plotarea.canClaim(plr, start, end)) { for (int i = start.x; i <= end.x; i++) { for (int j = start.y; j <= end.y; j++) { Plot plot = plotarea.getPlotAbs(new PlotId(i, j)); - final boolean teleport = i == end.x && j == end.y; + boolean teleport = i == end.x && j == end.y; plot.claim(plr, teleport, null); } } @@ -205,7 +205,7 @@ public class Auto extends SubCommand { return true; } - public PlotId getLastPlotId(final PlotArea area) { + public PlotId getLastPlotId(PlotArea area) { PlotId value = (PlotId) area.getMeta("lastPlot"); if (value == null) { value = new PlotId(0, 0); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java index 35a64bc13..328108b2a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java @@ -30,26 +30,26 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "bo3", -aliases = { "bo2" }, -description = "Mark a plot as done", -permission = "plots.bo3", -category = CommandCategory.SCHEMATIC, -requiredType = RequiredType.NONE) + aliases = {"bo2"}, + description = "Mark a plot as done", + permission = "plots.bo3", + category = CommandCategory.SCHEMATIC, + requiredType = RequiredType.NONE) public class BO3 extends SubCommand { - public void noArgs(final PlotPlayer plr) { + public void noArgs(PlotPlayer plr) { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot bo3 export [category] [alias] [-r]"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot bo3 import "); } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + public boolean onCommand(PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if ((plot == null) || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } - if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.bo3")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.bo3")) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java index 73db810b9..809b3ce00 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java @@ -29,18 +29,18 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "setbiome", -permission = "plots.set.biome", -description = "Set the plot biome", -usage = "/plot biome [biome]", -aliases = { "biome", "sb", "setb", "b" }, -category = CommandCategory.APPEARANCE, -requiredType = RequiredType.NONE) + command = "setbiome", + permission = "plots.set.biome", + description = "Set the plot biome", + usage = "/plot biome [biome]", + aliases = {"biome", "sb", "setb", "b"}, + category = CommandCategory.APPEARANCE, + requiredType = RequiredType.NONE) public class Biome extends SetCommand { @Override public boolean set(final PlotPlayer plr, final Plot plot, final String value) { - final int biome = WorldUtil.IMP.getBiomeFromString(value); + int biome = WorldUtil.IMP.getBiomeFromString(value); if (biome == -1) { String biomes = StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s()); C.NEED_BIOME.send(plr); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java index 1b551c918..71ace6ccb 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java @@ -35,22 +35,22 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.Set; @CommandDeclaration( -command = "buy", -aliases = { "b" }, -description = "Buy the plot you are standing on", -usage = "/plot buy", -permission = "plots.buy", -category = CommandCategory.CLAIMING, -requiredType = RequiredType.NONE) + command = "buy", + aliases = {"b"}, + description = "Buy the plot you are standing on", + usage = "/plot buy", + permission = "plots.buy", + category = CommandCategory.CLAIMING, + requiredType = RequiredType.NONE) public class Buy extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { + public boolean onCommand(PlotPlayer plr, String... args) { if (EconHandler.manager == null) { return sendMessage(plr, C.ECON_DISABLED); } - final Location loc = plr.getLocation(); - final String world = loc.getWorld(); + Location loc = plr.getLocation(); + String world = loc.getWorld(); if (!PS.get().hasPlotArea(world)) { return sendMessage(plr, C.NOT_IN_PLOT_WORLD); } @@ -63,7 +63,7 @@ public class Buy extends SubCommand { return false; } plots = plot.getConnectedPlots(); - } catch (final Exception e) { + } catch (Exception e) { return sendMessage(plr, C.NOT_VALID_PLOT_ID); } } else { @@ -76,11 +76,11 @@ public class Buy extends SubCommand { if (!plot.hasOwner()) { return sendMessage(plr, C.PLOT_UNOWNED); } - final int currentPlots = plr.getPlotCount() + plots.size(); + int currentPlots = plr.getPlotCount() + plots.size(); if (currentPlots > plr.getAllowedPlots()) { return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); } - final Flag flag = FlagManager.getPlotFlagRaw(plot, "price"); + Flag flag = FlagManager.getPlotFlagRaw(plot, "price"); if (flag == null) { return sendMessage(plr, C.NOT_FOR_SALE); } @@ -95,13 +95,13 @@ public class Buy extends SubCommand { EconHandler.manager.withdrawMoney(plr, price); sendMessage(plr, C.REMOVED_BALANCE, price + ""); EconHandler.manager.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price); - final PlotPlayer owner = UUIDHandler.getPlayer(plot.owner); + PlotPlayer owner = UUIDHandler.getPlayer(plot.owner); if (owner != null) { sendMessage(plr, C.PLOT_SOLD, plot.getId() + "", plr.getName(), price + ""); } FlagManager.removePlotFlag(plot, "price"); } - for (final Plot current : plots) { + for (Plot current : plots) { plot.setOwner(plr.getUUID()); } MainUtil.sendMessage(plr, C.CLAIMED); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java index 9874cbf94..8df1fd43a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java @@ -4,16 +4,16 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "chat", -description = "Toggle plot chat on or off", -usage = "/plot chat [on|off]", -permission = "plots.chat", -category = CommandCategory.CHAT, -requiredType = RequiredType.NONE) + command = "chat", + description = "Toggle plot chat on or off", + usage = "/plot chat [on|off]", + permission = "plots.chat", + category = CommandCategory.CHAT, + requiredType = RequiredType.NONE) public class Chat extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer player, final String... args) { + public boolean onCommand(PlotPlayer player, String... args) { return MainCommand.onCommand(player, "plot", "toggle", "chat"); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java index 164bc6438..497bdf240 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java @@ -32,24 +32,25 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "claim", -aliases = "c", -description = "Claim the current plot you're standing on", -category = CommandCategory.CLAIMING, -requiredType = RequiredType.PLAYER, -permission = "plots.claim", usage = "/plot claim") + aliases = "c", + description = "Claim the current plot you're standing on", + category = CommandCategory.CLAIMING, + requiredType = RequiredType.PLAYER, + permission = "plots.claim", usage = "/plot claim") public class Claim extends SubCommand { + @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { + public boolean onCommand(PlotPlayer plr, String... args) { String schematic = ""; if (args.length >= 1) { schematic = args[0]; } - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return sendMessage(plr, C.NOT_IN_PLOT); } - final int currentPlots = Settings.GLOBAL_LIMIT ? plr.getPlotCount() : plr.getPlotCount(loc.getWorld()); + int currentPlots = Settings.GLOBAL_LIMIT ? plr.getPlotCount() : plr.getPlotCount(loc.getWorld()); int grants = 0; if (currentPlots >= plr.getAllowedPlots()) { if (plr.hasPersistentMeta("grantedPlots")) { @@ -65,9 +66,9 @@ public class Claim extends SubCommand { if (!plot.canClaim(plr)) { return sendMessage(plr, C.PLOT_IS_CLAIMED); } - final PlotArea world = plot.getArea(); + PlotArea world = plot.getArea(); if ((EconHandler.manager != null) && world.USE_ECONOMY) { - final double cost = world.PRICES.get("claim"); + double cost = world.PRICES.get("claim"); if (cost > 0d) { if (EconHandler.manager.getMoney(plr) < cost) { return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java index 2a5237448..f1e9264f3 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java @@ -32,19 +32,20 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.Set; @CommandDeclaration(command = "clear", -description = "Clear a plot", -permission = "plots.clear", -category = CommandCategory.APPEARANCE, -usage = "/plot clear [id]", -aliases = "reset") + description = "Clear a plot", + permission = "plots.clear", + category = CommandCategory.APPEARANCE, + usage = "/plot clear [id]", + aliases = "reset") public class Clear extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { - final Location loc = plr.getLocation(); + public boolean onCommand(final PlotPlayer plr, String... args) { + Location loc = plr.getLocation(); final Plot plot; if (args.length == 1) { if (args[0].equalsIgnoreCase("mine")) { @@ -81,15 +82,16 @@ public class Clear extends SubCommand { return false; } if ((FlagManager.getPlotFlagRaw(plot, "done") != null) - && (!Permissions.hasPermission(plr, "plots.continue") || (Settings.DONE_COUNTS_TOWARDS_LIMIT && (plr.getAllowedPlots() >= plr.getPlotCount())))) { + && (!Permissions.hasPermission(plr, "plots.continue") || (Settings.DONE_COUNTS_TOWARDS_LIMIT && (plr.getAllowedPlots() >= plr + .getPlotCount())))) { MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE); return false; } - final Runnable runnable = new Runnable() { + Runnable runnable = new Runnable() { @Override public void run() { final long start = System.currentTimeMillis(); - final boolean result = plot.clear(true, false, new Runnable() { + boolean result = plot.clear(true, false, new Runnable() { @Override public void run() { plot.unlink(); @@ -111,13 +113,12 @@ public class Clear extends SubCommand { }); if (!result) { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); - } - else { + } else { plot.addRunning(); } } }; - if (Settings.CONFIRM_CLEAR && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { + if (Settings.CONFIRM_CLEAR && !Permissions.hasPermission(plr, "plots.confirm.bypass")) { CmdConfirm.addPending(plr, "/plot clear " + plot.getId(), runnable); } else { TaskManager.runTask(runnable); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java index 5581f44fe..c1fdcc155 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java @@ -35,21 +35,22 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.UUID; @CommandDeclaration(command = "cluster", -aliases = "clusters", -category = CommandCategory.ADMINISTRATION, -requiredType = RequiredType.NONE, -permission = "plots.cluster", -description = "Manage a plot cluster") + aliases = "clusters", + category = CommandCategory.ADMINISTRATION, + requiredType = RequiredType.NONE, + permission = "plots.cluster", + description = "Manage a plot cluster") public class Cluster extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { + public boolean onCommand(PlotPlayer plr, String... args) { // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome if (args.length == 0) { @@ -57,7 +58,7 @@ public class Cluster extends SubCommand { MainUtil.sendMessage(plr, C.CLUSTER_AVAILABLE_ARGS); return false; } - final String sub = args[0].toLowerCase(); + String sub = args[0].toLowerCase(); switch (sub) { case "l": case "list": { @@ -70,11 +71,11 @@ public class Cluster extends SubCommand { return false; } PlotArea area = plr.getApplicablePlotArea(); - final Set clusters = area.getClusters(); + Set clusters = area.getClusters(); MainUtil.sendMessage(plr, C.CLUSTER_LIST_HEADING, clusters.size() + ""); - for (final PlotCluster cluster : clusters) { + for (PlotCluster cluster : clusters) { // Ignore unmanaged clusters - final String name = "'" + cluster.getName() + "' : " + cluster.toString(); + String name = "'" + cluster.getName() + "' : " + cluster.toString(); if (plr.getUUID().equals(cluster.owner)) { MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&a" + name); } else if (cluster.helpers.contains(plr.getUUID())) { @@ -110,7 +111,7 @@ public class Cluster extends SubCommand { return false; } // check if name is taken - final String name = args[1]; + String name = args[1]; if (area.getCluster(name) != null) { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); return false; @@ -127,11 +128,11 @@ public class Cluster extends SubCommand { return false; } // Check if it occupies existing plots - final Set plots = area.getPlotSelectionOwned(pos1, pos2); + Set plots = area.getPlotSelectionOwned(pos1, pos2); if (!plots.isEmpty()) { if (!Permissions.hasPermission(plr, "plots.cluster.create.other")) { - final UUID uuid = plr.getUUID(); - for (final Plot plot : plots) { + UUID uuid = plr.getUUID(); + for (Plot plot : plots) { if (!plot.isOwner(uuid)) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create.other"); return false; @@ -147,7 +148,7 @@ public class Cluster extends SubCommand { } else { current = plr.getPlayerClusterCount(plr.getLocation().getWorld()); } - final int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS); + int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS); if (current + cluster.getArea() > allowed) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster." + (current + cluster.getArea())); return false; @@ -157,7 +158,7 @@ public class Cluster extends SubCommand { area.addCluster(cluster); DBFunc.createCluster(cluster); // Add any existing plots to the current cluster - for (final Plot plot : plots) { + for (Plot plot : plots) { if (plot.hasOwner()) { if (!cluster.isAdded(plot.owner)) { cluster.invited.add(plot.owner); @@ -235,7 +236,7 @@ public class Cluster extends SubCommand { C.NOT_IN_PLOT_WORLD.send(plr); return false; } - final PlotCluster cluster = area.getCluster(plr.getLocation()); + PlotCluster cluster = area.getCluster(plr.getLocation()); if (cluster == null) { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; @@ -252,9 +253,9 @@ public class Cluster extends SubCommand { MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, intersect.getName()); return false; } - final HashSet existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); - final HashSet newplots = area.getPlotSelectionOwned(pos1, pos2); - final HashSet removed = (HashSet) existing.clone(); + HashSet existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); + HashSet newplots = area.getPlotSelectionOwned(pos1, pos2); + HashSet removed = (HashSet) existing.clone(); removed.removeAll(newplots); // Check expand / shrink if (!removed.isEmpty()) { @@ -278,7 +279,7 @@ public class Cluster extends SubCommand { current = plr.getPlayerClusterCount(plr.getLocation().getWorld()); } current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); - final int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS); + int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS); if (current + cluster.getArea() > allowed) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster." + (current + cluster.getArea())); return false; @@ -304,7 +305,7 @@ public class Cluster extends SubCommand { if (area == null) { C.NOT_IN_PLOT_WORLD.send(plr); } - final PlotCluster cluster = area.getCluster(plr.getLocation()); + PlotCluster cluster = area.getCluster(plr.getLocation()); if (cluster == null) { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; @@ -316,7 +317,7 @@ public class Cluster extends SubCommand { } } // check uuid - final UUID uuid = UUIDHandler.getUUID(args[1], null); + UUID uuid = UUIDHandler.getUUID(args[1], null); if (uuid == null) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[2]); return false; @@ -325,7 +326,7 @@ public class Cluster extends SubCommand { // add the user if not added cluster.invited.add(uuid); DBFunc.setInvited(cluster, uuid); - final PlotPlayer player = UUIDHandler.getPlayer(uuid); + PlotPlayer player = UUIDHandler.getPlayer(uuid); if (player != null) { MainUtil.sendMessage(player, C.CLUSTER_INVITED, cluster.getName()); } @@ -348,7 +349,7 @@ public class Cluster extends SubCommand { if (area == null) { C.NOT_IN_PLOT_WORLD.send(plr); } - final PlotCluster cluster = area.getCluster(plr.getLocation()); + PlotCluster cluster = area.getCluster(plr.getLocation()); if (cluster == null) { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; @@ -360,7 +361,7 @@ public class Cluster extends SubCommand { } } // check uuid - final UUID uuid = UUIDHandler.getUUID(args[1], null); + UUID uuid = UUIDHandler.getUUID(args[1], null); if (uuid == null) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[1]); return false; @@ -376,12 +377,12 @@ public class Cluster extends SubCommand { } cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); - final PlotPlayer player = UUIDHandler.getPlayer(uuid); + PlotPlayer player = UUIDHandler.getPlayer(uuid); if (player != null) { MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); } - for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { - final PlotCluster current = plot.getCluster(); + for (Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { + PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { plot.unclaim(); } @@ -417,7 +418,7 @@ public class Cluster extends SubCommand { return false; } } - final UUID uuid = plr.getUUID(); + UUID uuid = plr.getUUID(); if (!cluster.isAdded(uuid)) { MainUtil.sendMessage(plr, C.CLUSTER_NOT_ADDED); return false; @@ -433,8 +434,8 @@ public class Cluster extends SubCommand { cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); MainUtil.sendMessage(plr, C.CLUSTER_REMOVED, cluster.getName()); - for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { - final PlotCluster current = plot.getCluster(); + for (Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { + PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { plr.getLocation().getWorld(); plot.unclaim(); @@ -457,12 +458,12 @@ public class Cluster extends SubCommand { if (area == null) { C.NOT_IN_PLOT_WORLD.send(plr); } - final PlotCluster cluster = area.getCluster(plr.getLocation()); + PlotCluster cluster = area.getCluster(plr.getLocation()); if (cluster == null) { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } - final UUID uuid = UUIDHandler.getUUID(args[2], null); + UUID uuid = UUIDHandler.getUUID(args[2], null); if (uuid == null) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[2]); return false; @@ -495,12 +496,12 @@ public class Cluster extends SubCommand { if (area == null) { C.NOT_IN_PLOT_WORLD.send(plr); } - final PlotCluster cluster = area.getCluster(args[1]); + PlotCluster cluster = area.getCluster(args[1]); if (cluster == null) { MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); return false; } - final UUID uuid = plr.getUUID(); + UUID uuid = plr.getUUID(); if (!cluster.isAdded(uuid)) { if (!Permissions.hasPermission(plr, "plots.cluster.tp.other")) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.tp.other"); @@ -540,14 +541,14 @@ public class Cluster extends SubCommand { return false; } } - final String id = cluster.toString(); + String id = cluster.toString(); String owner = UUIDHandler.getName(cluster.owner); if (owner == null) { owner = "unknown"; } - final String name = cluster.getName(); - final String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + (cluster.getP2().y - cluster.getP1().y + 1); - final String rights = cluster.isAdded(plr.getUUID()) + ""; + String name = cluster.getName(); + String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + (cluster.getP2().y - cluster.getP1().y + 1); + String rights = cluster.isAdded(plr.getUUID()) + ""; String message = C.CLUSTER_INFO.s(); message = message.replaceAll("%id%", id); message = message.replaceAll("%owner%", owner); @@ -572,7 +573,7 @@ public class Cluster extends SubCommand { if (area == null) { C.NOT_IN_PLOT_WORLD.send(plr); } - final PlotCluster cluster = area.getCluster(plr.getLocation()); + PlotCluster cluster = area.getCluster(plr.getLocation()); if (cluster == null) { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; @@ -583,9 +584,9 @@ public class Cluster extends SubCommand { return false; } } - final Location base = cluster.getClusterBottom(); - final Location relative = plr.getLocation().subtract(base.getX(), 0, base.getZ()); - final BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ()); + Location base = cluster.getClusterBottom(); + Location relative = plr.getLocation().subtract(base.getX(), 0, base.getZ()); + BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ()); cluster.settings.setPosition(blockloc); DBFunc.setPosition(cluster, relative.getX() + "," + relative.getY() + "," + relative.getZ()); return MainUtil.sendMessage(plr, C.POSITION_SET); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java index 62d1d1280..cdaa6aa55 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java @@ -2,7 +2,9 @@ package com.intellectualcrafters.plot.commands; /** * CommandCategory - * + * + + */ public enum CommandCategory { /** @@ -54,18 +56,18 @@ public enum CommandCategory { * The category name (Readable) */ private final String name; - + /** * Constructor * * @param name readable name */ - CommandCategory(final String name) { + CommandCategory(String name) { this.name = name; } - + @Override public String toString() { - return name; + return this.name; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java index 8c1fecf2e..93e58735a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java @@ -25,27 +25,29 @@ import com.intellectualcrafters.plot.util.Permissions; /** * Created by Citymonstret on 2014-08-03. - * + * + */ public class CommandPermission { + /** * Permission Node */ public final String permission; - + /** * @param permission Command Permission */ - public CommandPermission(final String permission) { + public CommandPermission(String permission) { this.permission = permission.toLowerCase(); } - + /** * @param player Does the player have the permission? * * @return true of player has the required permission node */ - public boolean hasPermission(final PlotPlayer player) { - return Permissions.hasPermission(player, permission); + public boolean hasPermission(PlotPlayer player) { + return Permissions.hasPermission(player, this.permission); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java index 84ce0f413..ce0bca696 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java @@ -32,30 +32,31 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.Arrays; import java.util.Map.Entry; @CommandDeclaration(command = "comment", -aliases = { "msg" }, -description = "Comment on a plot", -category = CommandCategory.CHAT, -requiredType = RequiredType.NONE, -permission = "plots.comment") + aliases = {"msg"}, + description = "Comment on a plot", + category = CommandCategory.CHAT, + requiredType = RequiredType.NONE, + permission = "plots.comment") public class Comment extends SubCommand { @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { + public boolean onCommand(PlotPlayer player, String[] args) { if (args.length < 2) { sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } - final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); + CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); if (inbox == null) { sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } - final Location loc = player.getLocation(); - final PlotId id = PlotId.fromString(args[1]); + Location loc = player.getLocation(); + PlotId id = PlotId.fromString(args[1]); Plot plot = MainUtil.getPlotFromString(player, args[1], false); int index; if (plot == null) { @@ -72,9 +73,9 @@ public class Comment extends SubCommand { sendMessage(player, C.NO_PERM_INBOX, ""); return false; } - final String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " "); - final PlotComment comment = new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), System.currentTimeMillis()); - final boolean result = inbox.addComment(plot, comment); + String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " "); + PlotComment comment = new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), System.currentTimeMillis()); + boolean result = inbox.addComment(plot, comment); if (!result) { sendMessage(player, C.NO_PLOT_INBOX, ""); sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java index 0e36ee235..796f3d864 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java @@ -30,6 +30,7 @@ import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -39,16 +40,16 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; @CommandDeclaration(command = "condense", -permission = "plots.admin", -description = "Condense a plotworld", -category = CommandCategory.ADMINISTRATION, -requiredType = RequiredType.CONSOLE) + permission = "plots.admin", + description = "Condense a plotworld", + category = CommandCategory.ADMINISTRATION, + requiredType = RequiredType.CONSOLE) public class Condense extends SubCommand { public static boolean TASK = false; @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { + public boolean onCommand(final PlotPlayer plr, String... args) { if ((args.length != 2) && (args.length != 3)) { MainUtil.sendMessage(plr, "/plot condense [radius]"); return false; @@ -72,7 +73,7 @@ public class Condense extends SubCommand { MainUtil.sendMessage(plr, "INVALID RADIUS"); return false; } - final int radius = Integer.parseInt(args[2]); + int radius = Integer.parseInt(args[2]); ArrayList plots = new ArrayList<>(PS.get().getPlots(area)); // remove non base plots Iterator iter = plots.iterator(); @@ -109,23 +110,23 @@ public class Condense extends SubCommand { allPlots.addAll(array); } } - final int size = allPlots.size(); - final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); - if (radius < minimum_radius) { + int size = allPlots.size(); + int minimumRadius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); + if (radius < minimumRadius) { MainUtil.sendMessage(plr, "RADIUS TOO SMALL"); return false; } - final List to_move = new ArrayList<>(getPlots(allPlots, radius)); + List toMove = new ArrayList<>(getPlots(allPlots, radius)); final List free = new ArrayList<>(); PlotId start = new PlotId(0, 0); - while ((start.x <= minimum_radius) && (start.y <= minimum_radius)) { + while ((start.x <= minimumRadius) && (start.y <= minimumRadius)) { Plot plot = area.getPlotAbs(start); if (plot != null && !plot.hasOwner()) { free.add(plot.getId()); } start = Auto.getNextPlotId(start, 1); } - if ((free.isEmpty()) || (to_move.isEmpty())) { + if (free.isEmpty() || toMove.isEmpty()) { MainUtil.sendMessage(plr, "NO FREE PLOTS FOUND"); return false; } @@ -197,22 +198,22 @@ public class Condense extends SubCommand { MainUtil.sendMessage(plr, "INVALID RADIUS"); return false; } - final int radius = Integer.parseInt(args[2]); - final Collection plots = area.getPlots(); - final int size = plots.size(); - final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); - if (radius < minimum_radius) { + int radius = Integer.parseInt(args[2]); + Collection plots = area.getPlots(); + int size = plots.size(); + int minimumRadius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); + if (radius < minimumRadius) { MainUtil.sendMessage(plr, "RADIUS TOO SMALL"); return false; } - final int max_move = getPlots(plots, minimum_radius).size(); - final int user_move = getPlots(plots, radius).size(); + int maxMove = getPlots(plots, minimumRadius).size(); + int userMove = getPlots(plots, radius).size(); MainUtil.sendMessage(plr, "=== DEFAULT EVAL ==="); - MainUtil.sendMessage(plr, "MINIMUM RADIUS: " + minimum_radius); - MainUtil.sendMessage(plr, "MAXIMUM MOVES: " + max_move); + MainUtil.sendMessage(plr, "MINIMUM RADIUS: " + minimumRadius); + MainUtil.sendMessage(plr, "MAXIMUM MOVES: " + maxMove); MainUtil.sendMessage(plr, "=== INPUT EVAL ==="); MainUtil.sendMessage(plr, "INPUT RADIUS: " + radius); - MainUtil.sendMessage(plr, "ESTIMATED MOVES: " + user_move); + MainUtil.sendMessage(plr, "ESTIMATED MOVES: " + userMove); MainUtil.sendMessage(plr, "ESTIMATED TIME: " + "No idea, times will drastically change based on the system performance and load"); MainUtil.sendMessage(plr, "&e - Radius is measured in plot width"); return true; @@ -222,9 +223,9 @@ public class Condense extends SubCommand { return false; } - public Set getPlots(final Collection plots, final int radius) { - final HashSet outside = new HashSet<>(); - for (final Plot plot : plots) { + public Set getPlots(Collection plots, int radius) { + HashSet outside = new HashSet<>(); + for (Plot plot : plots) { if ((plot.getId().x > radius) || (plot.getId().x < -radius) || (plot.getId().y > radius) || (plot.getId().y < -radius)) { outside.add(plot.getId()); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java index a0517700b..a692d125c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java @@ -29,14 +29,14 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "confirm", -permission = "plots.use", -description = "Confirm an action", -category = CommandCategory.INFO) + permission = "plots.use", + description = "Confirm an action", + category = CommandCategory.INFO) public class Confirm extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { - final CmdInstance command = CmdConfirm.getPending(plr); + public boolean onCommand(PlotPlayer plr, String... args) { + CmdInstance command = CmdConfirm.getPending(plr); if (command == null) { MainUtil.sendMessage(plr, C.FAILED_CONFIRM); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java index 2114afde1..819d4db12 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java @@ -30,16 +30,16 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "continue", -description = "Continue a plot that was previously marked as done", -permission = "plots.continue", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + command = "continue", + description = "Continue a plot that was previously marked as done", + permission = "plots.continue", + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Continue extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Plot plot = plr.getCurrentPlot(); + public boolean onCommand(PlotPlayer plr, String[] args) { + Plot plot = plr.getCurrentPlot(); if ((plot == null) || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java index bc21211d1..12c557e27 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java @@ -29,19 +29,19 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "copy", -permission = "plots.copy", -aliases = { "copypaste" }, -category = CommandCategory.CLAIMING, -description = "Copy a plot", -usage = "/plot copy ", -requiredType = RequiredType.NONE) + command = "copy", + permission = "plots.copy", + aliases = {"copypaste"}, + category = CommandCategory.CLAIMING, + description = "Copy a plot", + usage = "/plot copy ", + requiredType = RequiredType.NONE) public class Copy extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); - final Plot plot1 = loc.getPlotAbs(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); + Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); } @@ -53,8 +53,8 @@ public class Copy extends SubCommand { C.COMMAND_SYNTAX.send(plr, getUsage()); return false; } - final Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true); - if ((plot2 == null)) { + Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true); + if (plot2 == null) { return false; } if (plot1.equals(plot2)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java index 2da7c2107..032851219 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java @@ -30,19 +30,19 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "createroadschematic", -aliases = { "crs" }, -category = CommandCategory.ADMINISTRATION, -requiredType = RequiredType.NONE, -permission = "plots.createroadschematic", -description = "Add a road schematic to your world using the roads around your current plot", -usage = "/plot createroadschematic") + command = "createroadschematic", + aliases = {"crs"}, + category = CommandCategory.ADMINISTRATION, + requiredType = RequiredType.NONE, + permission = "plots.createroadschematic", + description = "Add a road schematic to your world using the roads around your current plot", + usage = "/plot createroadschematic") public class CreateRoadSchematic extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer player, final String... args) { - final Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + public boolean onCommand(PlotPlayer player, String... args) { + Location loc = player.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return sendMessage(player, C.NOT_IN_PLOT); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java index cb822916e..2e372ce1a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java @@ -12,6 +12,7 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.sql.SQLException; import java.util.ArrayList; @@ -20,13 +21,13 @@ import java.util.HashMap; import java.util.Map.Entry; @CommandDeclaration( -command = "database", -aliases = { "convert" }, -category = CommandCategory.ADMINISTRATION, -permission = "plots.database", -description = "Convert/Backup Storage", -requiredType = RequiredType.CONSOLE, -usage = "/plots database [area] ") + command = "database", + aliases = {"convert"}, + category = CommandCategory.ADMINISTRATION, + permission = "plots.database", + description = "Convert/Backup Storage", + requiredType = RequiredType.CONSOLE, + usage = "/plots database [area] ") public class Database extends SubCommand { public static void insertPlots(final SQLManager manager, final ArrayList plots, final PlotPlayer player) { @@ -34,8 +35,8 @@ public class Database extends SubCommand { @Override public void run() { try { - final ArrayList ps = new ArrayList<>(); - for (final Plot p : plots) { + ArrayList ps = new ArrayList<>(); + for (Plot p : plots) { ps.add(p); } MainUtil.sendMessage(player, "&6Starting..."); @@ -46,7 +47,7 @@ public class Database extends SubCommand { manager.close(); } }); - } catch (final Exception e) { + } catch (Exception e) { MainUtil.sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); e.printStackTrace(); } @@ -89,15 +90,15 @@ public class Database extends SubCommand { } MainUtil.sendMessage(player, "&6Starting..."); implementation = new SQLite(file.getPath()); - final SQLManager manager = new SQLManager(implementation, (args.length == 3) ? args[2] : "", true); - final HashMap> map = manager.getPlots(); + SQLManager manager = new SQLManager(implementation, (args.length == 3) ? args[2] : "", true); + HashMap> map = manager.getPlots(); plots = new ArrayList<>(); - for (final Entry> entry : map.entrySet()) { + for (Entry> entry : map.entrySet()) { String areaname = entry.getKey(); PlotArea pa = PS.get().getPlotAreaByString(areaname); if (pa != null) { - for (final Entry entry2 : entry.getValue().entrySet()) { - final Plot plot = entry2.getValue(); + for (Entry entry2 : entry.getValue().entrySet()) { + Plot plot = entry2.getValue(); if (pa.getOwnedPlotAbs(plot.getId()) != null) { MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp); continue; @@ -126,11 +127,11 @@ public class Database extends SubCommand { if (args.length < 6) { return MainUtil.sendMessage(player, "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); } - final String host = args[1]; - final String port = args[2]; - final String username = args[3]; - final String password = args[4]; - final String database = args[5]; + String host = args[1]; + String port = args[2]; + String username = args[3]; + String password = args[4]; + String database = args[5]; if (args.length > 6) { prefix = args[6]; } @@ -146,7 +147,7 @@ public class Database extends SubCommand { return MainUtil.sendMessage(player, "/plot database [sqlite/mysql]"); } try { - final SQLManager manager = new SQLManager(implementation, prefix, true); + SQLManager manager = new SQLManager(implementation, prefix, true); insertPlots(manager, plots, player); return true; } catch (ClassNotFoundException | SQLException e) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java index 34d40e38d..f7eccfa98 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java @@ -29,17 +29,17 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "debug", -category = CommandCategory.DEBUG, -description = "Show debug information", -usage = "/plot debug [msg]", -permission = "plots.admin") + category = CommandCategory.DEBUG, + description = "Show debug information", + usage = "/plot debug [msg]", + permission = "plots.admin") public class Debug extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { - final StringBuilder msg = new StringBuilder(); - for (final C c : C.values()) { + StringBuilder msg = new StringBuilder(); + for (C c : C.values()) { msg.append(c.s()).append("\n"); } MainUtil.sendMessage(plr, msg.toString()); @@ -75,11 +75,11 @@ public class Debug extends SubCommand { return true; } - private String getSection(final String line, final String val) { + private String getSection(String line, String val) { return line.replaceAll("%val%", val) + "\n"; } - private String getLine(final String line, final String var, final Object val) { + private String getLine(String line, String var, Object val) { return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java index 90bc2155d..0ad6e1a22 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java @@ -1,27 +1,27 @@ package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + @CommandDeclaration( -command = "debugallowunsafe", -description = "Allow unsafe actions until toggled off", -usage = "/plot debugallowunsafe", -category = CommandCategory.DEBUG, -requiredType = RequiredType.NONE, -permission = "plots.debugallowunsafe") + command = "debugallowunsafe", + description = "Allow unsafe actions until toggled off", + usage = "/plot debugallowunsafe", + category = CommandCategory.DEBUG, + requiredType = RequiredType.NONE, + permission = "plots.debugallowunsafe") public class DebugAllowUnsafe extends SubCommand { - + public static final List unsafeAllowed = new ArrayList<>(); - + @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { - + public boolean onCommand(PlotPlayer plr, String... args) { + if (unsafeAllowed.contains(plr.getUUID())) { unsafeAllowed.remove(plr.getUUID()); sendMessage(plr, C.DEBUGALLOWUNSAFE_OFF); @@ -31,5 +31,5 @@ public class DebugAllowUnsafe extends SubCommand { } return true; } - + } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java index 63c4e992b..169d814a8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java @@ -24,7 +24,14 @@ import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.UUIDHandler; @@ -36,20 +43,22 @@ import java.util.Map; import java.util.UUID; @CommandDeclaration( -command = "debugclaimtest", -description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. Execution time may vary", -category = CommandCategory.DEBUG, -requiredType = RequiredType.CONSOLE, -permission = "plots.debugclaimtest") + command = "debugclaimtest", + description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. " + + "Execution time may vary", + category = CommandCategory.DEBUG, + requiredType = RequiredType.CONSOLE, + permission = "plots.debugclaimtest") public class DebugClaimTest extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, String[] args) { if (args.length < 3) { return !MainUtil - .sendMessage( - null, - "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); + .sendMessage( + null, + "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the " + + "plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); } PlotArea area = PS.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { @@ -62,35 +71,36 @@ public class DebugClaimTest extends SubCommand { args[2].split(";"); min = PlotId.fromString(args[1]); max = PlotId.fromString(args[2]); - } catch (final Exception e) { + } catch (Exception e) { return !MainUtil.sendMessage(plr, - "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion will only check the plots in the selected area."); + "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion " + + "will only check the plots in the selected area."); } MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while..."); MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); - final PlotManager manager = area.getPlotManager(); - final ArrayList plots = new ArrayList<>(); - for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) { - final Plot plot = area.getPlotAbs(id); + PlotManager manager = area.getPlotManager(); + ArrayList plots = new ArrayList<>(); + for (PlotId id : MainUtil.getPlotSelectionIds(min, max)) { + Plot plot = area.getPlotAbs(id); if (plot.hasOwner()) { MainUtil.sendMessage(plr, " - &cDB Already contains: " + plot.getId()); continue; } - final Location loc = manager.getSignLoc(area, plot); - final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); - final boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false); + Location loc = manager.getSignLoc(area, plot); + ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); + boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false); if (!result) { continue; } - final String[] lines = WorldUtil.IMP.getSign(loc); + String[] lines = WorldUtil.IMP.getSign(loc); if (lines != null) { String line = lines[2]; if (line != null && line.length() > 2) { line = line.substring(2); - final BiMap map = UUIDHandler.getUuidMap(); + BiMap map = UUIDHandler.getUuidMap(); UUID uuid = map.get(new StringWrapper(line)); if (uuid == null) { - for (final Map.Entry stringWrapperUUIDEntry : map.entrySet()) { + for (Map.Entry stringWrapperUUIDEntry : map.entrySet()) { if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) { uuid = stringWrapperUUIDEntry.getValue(); break; @@ -118,7 +128,7 @@ public class DebugClaimTest extends SubCommand { MainUtil.sendMessage(plr, "&6Database update finished!"); } }); - for (final Plot plot : plots) { + for (Plot plot : plots) { plot.create(); } MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java index 77e978cef..3674dd8a6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java @@ -54,6 +54,7 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.listener.WEManager; + import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -62,6 +63,7 @@ import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.UUID; + import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; @@ -70,111 +72,114 @@ import javax.script.ScriptException; import javax.script.SimpleScriptContext; @CommandDeclaration(command = "debugexec", -permission = "plots.admin", -description = "Mutli-purpose debug command", -aliases = "exec", -category = CommandCategory.DEBUG) + permission = "plots.admin", + description = "Mutli-purpose debug command", + aliases = "exec", + category = CommandCategory.DEBUG) public class DebugExec extends SubCommand { + private ScriptEngine engine; private Bindings scope; public DebugExec() { try { if (PS.get() != null) { - final File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js"); + File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js"); if (file.exists()) { init(); - final String script = StringMan.join(Files + String script = StringMan.join(Files .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"), StandardCharsets.UTF_8), System.getProperty("line.separator")); - scope.put("THIS", this); - scope.put("PlotPlayer", ConsolePlayer.getConsole()); - engine.eval(script, scope); + this.scope.put("THIS", this); + this.scope.put("PlotPlayer", ConsolePlayer.getConsole()); + this.engine.eval(script, this.scope); } } - } catch (IOException | ScriptException e) {} + } catch (IOException | ScriptException e) { + } } public ScriptEngine getEngine() { - return engine; + return this.engine; } public Bindings getScope() { - return scope; + return this.scope; } public void init() { - if (engine != null) { + if (this.engine != null) { return; } - engine = new ScriptEngineManager(null).getEngineByName("nashorn"); - if (engine == null) { - engine = new ScriptEngineManager(null).getEngineByName("JavaScript"); + this.engine = new ScriptEngineManager(null).getEngineByName("nashorn"); + if (this.engine == null) { + this.engine = new ScriptEngineManager(null).getEngineByName("JavaScript"); } - final ScriptContext context = new SimpleScriptContext(); - scope = context.getBindings(ScriptContext.ENGINE_SCOPE); + ScriptContext context = new SimpleScriptContext(); + this.scope = context.getBindings(ScriptContext.ENGINE_SCOPE); // stuff - scope.put("MainUtil", new MainUtil()); - scope.put("Settings", new Settings()); - scope.put("StringMan", new StringMan()); - scope.put("MathMan", new MathMan()); - scope.put("FlagManager", new FlagManager()); + this.scope.put("MainUtil", new MainUtil()); + this.scope.put("Settings", new Settings()); + this.scope.put("StringMan", new StringMan()); + this.scope.put("MathMan", new MathMan()); + this.scope.put("FlagManager", new FlagManager()); // Classes - scope.put("Location", Location.class); - scope.put("PlotBlock", PlotBlock.class); - scope.put("Plot", Plot.class); - scope.put("PlotId", PlotId.class); - scope.put("Runnable", Runnable.class); - scope.put("RunnableVal", RunnableVal.class); + this.scope.put("Location", Location.class); + this.scope.put("PlotBlock", PlotBlock.class); + this.scope.put("Plot", Plot.class); + this.scope.put("PlotId", PlotId.class); + this.scope.put("Runnable", Runnable.class); + this.scope.put("RunnableVal", RunnableVal.class); // Instances - scope.put("PS", PS.get()); - scope.put("SetQueue", SetQueue.IMP); - scope.put("ExpireManager", ExpireManager.IMP); + this.scope.put("PS", PS.get()); + this.scope.put("SetQueue", SetQueue.IMP); + this.scope.put("ExpireManager", ExpireManager.IMP); if (PS.get().worldedit != null) { - scope.put("WEManager", new WEManager()); + this.scope.put("WEManager", new WEManager()); } - scope.put("TaskManager", PS.get().TASK); - scope.put("TitleManager", AbstractTitle.TITLE_CLASS); - scope.put("ConsolePlayer", ConsolePlayer.getConsole()); - scope.put("SchematicHandler", SchematicHandler.manager); - scope.put("ChunkManager", ChunkManager.manager); - scope.put("BlockManager", WorldUtil.IMP); - scope.put("SetupUtils", SetupUtils.manager); - scope.put("EventUtil", EventUtil.manager); - scope.put("EconHandler", EconHandler.manager); - scope.put("UUIDHandler", UUIDHandler.implementation); - scope.put("DBFunc", DBFunc.dbManager); - scope.put("HybridUtils", HybridUtils.manager); - scope.put("IMP", PS.get().IMP); - scope.put("MainCommand", MainCommand.getInstance()); + this.scope.put("TaskManager", PS.get().TASK); + this.scope.put("TitleManager", AbstractTitle.TITLE_CLASS); + this.scope.put("ConsolePlayer", ConsolePlayer.getConsole()); + this.scope.put("SchematicHandler", SchematicHandler.manager); + this.scope.put("ChunkManager", ChunkManager.manager); + this.scope.put("BlockManager", WorldUtil.IMP); + this.scope.put("SetupUtils", SetupUtils.manager); + this.scope.put("EventUtil", EventUtil.manager); + this.scope.put("EconHandler", EconHandler.manager); + this.scope.put("UUIDHandler", UUIDHandler.implementation); + this.scope.put("DBFunc", DBFunc.dbManager); + this.scope.put("HybridUtils", HybridUtils.manager); + this.scope.put("IMP", PS.get().IMP); + this.scope.put("MainCommand", MainCommand.getInstance()); // enums - for (final Enum value : C.values()) { - scope.put("C_" + value.name(), value); + for (Enum value : C.values()) { + this.scope.put("C_" + value.name(), value); } } @Override - public boolean onCommand(final PlotPlayer player, final String... args) { - final java.util.List allowed_params = Arrays.asList("calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "show-expired", "update-expired", "seen"); + public boolean onCommand(final PlotPlayer player, String... args) { + java.util.List allowed_params = + Arrays.asList("calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "show-expired", "update-expired", "seen"); if (args.length > 0) { - final String arg = args[0].toLowerCase(); + String arg = args[0].toLowerCase(); String script; boolean async = false; switch (arg) { case "analyze": { - final Plot plot = player.getCurrentPlot(); + Plot plot = player.getCurrentPlot(); if (plot == null) { MainUtil.sendMessage(player, C.NOT_IN_PLOT); return false; } - final PlotAnalysis analysis = plot.getComplexity(); + PlotAnalysis analysis = plot.getComplexity(); if (analysis != null) { - final int complexity = analysis.getComplexity(); + int complexity = analysis.getComplexity(); MainUtil.sendMessage(player, "Changes/column: " + analysis.changes / 1.0); MainUtil.sendMessage(player, "Complexity: " + complexity); return true; @@ -191,13 +196,15 @@ public class DebugExec extends SubCommand { case "calibrate-analysis": if (args.length != 2) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze "); - MainUtil.sendMessage(player, "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating it)"); + MainUtil.sendMessage(player, + "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating " + + "it)"); return false; } double threshold; try { threshold = Integer.parseInt(args[1]) / 100d; - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { MainUtil.sendMessage(player, "$2Invalid threshold: " + args[1]); MainUtil.sendMessage(player, "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); return false; @@ -219,8 +226,8 @@ public class DebugExec extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag "); return false; } - final String flag = args[1]; - for (final Plot plot : PS.get().getBasePlots()) { + String flag = args[1]; + for (Plot plot : PS.get().getBasePlots()) { if (FlagManager.getPlotFlagRaw(plot, flag) != null) { FlagManager.removePlotFlag(plot, flag); } @@ -275,16 +282,16 @@ public class DebugExec extends SubCommand { if (args.length != 2) { return MainUtil.sendMessage(player, "Use /plot debugexec seen "); } - final UUID uuid = UUIDHandler.getUUID(args[1], null); + UUID uuid = UUIDHandler.getUUID(args[1], null); if (uuid == null) { return MainUtil.sendMessage(player, "Player not found: " + args[1]); } - final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); + OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); if (op == null || op.getLastPlayed() == 0) { return MainUtil.sendMessage(player, "Player hasn't connected before: " + args[1]); } - final Timestamp stamp = new Timestamp(op.getLastPlayed()); - final Date date = new Date(stamp.getTime()); + Timestamp stamp = new Timestamp(op.getLastPlayed()); + Date date = new Date(stamp.getTime()); MainUtil.sendMessage(player, "PLAYER: " + args[1]); MainUtil.sendMessage(player, "UUID: " + uuid); MainUtil.sendMessage(player, "Object: " + date.toGMTString()); @@ -300,17 +307,18 @@ public class DebugExec extends SubCommand { case "addcmd": try { final String cmd = StringMan.join(Files - .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), + .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), + StandardCharsets.UTF_8), System.getProperty("line.separator")); - final Command subcommand = new Command(args[1].split("\\.")[0]) { + Command subcommand = new Command(args[1].split("\\.")[0]) { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { try { - scope.put("PlotPlayer", plr); - scope.put("args", args); - engine.eval(cmd, scope); + DebugExec.this.scope.put("PlotPlayer", plr); + DebugExec.this.scope.put("args", args); + DebugExec.this.engine.eval(cmd, DebugExec.this.scope); return true; - } catch (final ScriptException e) { + } catch (ScriptException e) { e.printStackTrace(); MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG); return false; @@ -328,16 +336,18 @@ public class DebugExec extends SubCommand { async = true; case "run": try { - script = StringMan.join(Files.readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), - System.getProperty("line.separator")); + script = StringMan.join(Files + .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), + StandardCharsets.UTF_8), + System.getProperty("line.separator")); if (args.length > 2) { - final HashMap replacements = new HashMap<>(); + HashMap replacements = new HashMap<>(); for (int i = 2; i < args.length; i++) { replacements.put("%s" + (i - 2), args[i]); } script = StringMan.replaceFromMap(script, replacements); } - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); return false; } @@ -372,9 +382,11 @@ public class DebugExec extends SubCommand { return true; } init(); - scope.put("_2", params); - scope.put("_3", cmd); - script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand(PlotPlayer,_2)}}"; + this.scope.put("_2", params); + this.scope.put("_3", cmd); + script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand" + + "(PlotPlayer,_2)}}"; break; case "all": @@ -395,7 +407,7 @@ public class DebugExec extends SubCommand { return false; } init(); - scope.put("PlotPlayer", player); + this.scope.put("PlotPlayer", player); PS.debug("> " + script); try { if (async) { @@ -403,23 +415,23 @@ public class DebugExec extends SubCommand { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); Object result = null; try { - result = engine.eval(toExec, scope); - } catch (final ScriptException e) { + result = DebugExec.this.engine.eval(toExec, DebugExec.this.scope); + } catch (ScriptException e) { e.printStackTrace(); } ConsolePlayer.getConsole().sendMessage("> " + (System.currentTimeMillis() - start) + "ms -> " + result); } }); } else { - final long start = System.currentTimeMillis(); - Object result = engine.eval(script, scope); + long start = System.currentTimeMillis(); + Object result = this.engine.eval(script, this.scope); ConsolePlayer.getConsole().sendMessage("> " + (System.currentTimeMillis() - start) + "ms -> " + result); } return true; - } catch (final ScriptException e) { + } catch (ScriptException e) { e.printStackTrace(); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java index c90d59307..117860494 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java @@ -20,10 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; @@ -37,30 +33,34 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + @CommandDeclaration( -command = "debugfixflags", -usage = "/plot debugfixflags ", -permission = "plots.debugfixflags", -description = "Attempt to fix all flags for a world", -requiredType = RequiredType.CONSOLE, -category = CommandCategory.DEBUG) + command = "debugfixflags", + usage = "/plot debugfixflags ", + permission = "plots.debugfixflags", + description = "Attempt to fix all flags for a world", + requiredType = RequiredType.CONSOLE, + category = CommandCategory.DEBUG) public class DebugFixFlags extends SubCommand { - + public DebugFixFlags() { - requiredArguments = new Argument[] { Argument.String }; + this.requiredArguments = new Argument[]{Argument.String}; } - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { PlotArea area = PS.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD, args[0]); return false; } MainUtil.sendMessage(plr, "&8--- &6Starting task &8 ---"); - for (final Plot plot : area.getPlots()) { - final HashMap flags = plot.getFlags(); - final Iterator> i = flags.entrySet().iterator(); + for (Plot plot : area.getPlots()) { + HashMap flags = plot.getFlags(); + Iterator> i = flags.entrySet().iterator(); boolean changed = false; while (i.hasNext()) { if (FlagManager.getFlag(i.next().getKey()) == null) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java index 7861d57ac..6e88149d4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java @@ -20,29 +20,29 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.lang.reflect.Field; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; +import java.lang.reflect.Field; + @CommandDeclaration( -command = "debugloadtest", -permission = "plots.debugloadtest", -description = "This debug command will force the reload of all plots in the DB", -usage = "/plot debugloadtest", -category = CommandCategory.DEBUG, -requiredType = RequiredType.CONSOLE) + command = "debugloadtest", + permission = "plots.debugloadtest", + description = "This debug command will force the reload of all plots in the DB", + usage = "/plot debugloadtest", + category = CommandCategory.DEBUG, + requiredType = RequiredType.CONSOLE) public class DebugLoadTest extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { try { - final Field fPlots = PS.class.getDeclaredField("plots"); + Field fPlots = PS.class.getDeclaredField("plots"); fPlots.setAccessible(true); fPlots.set(null, DBFunc.getPlots()); - } catch (final Exception e) { + } catch (Exception e) { PS.debug("&3===FAILED&3==="); e.printStackTrace(); PS.debug("&3===END OF STACKTRACE==="); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java index b5db5b061..87f2cddfb 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java @@ -9,23 +9,24 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.io.IOException; @CommandDeclaration(command = "debugpaste", -aliases = "dp", usage = "/plot debugpaste", -description = "Upload settings.yml & latest.log to HasteBin", -permission = "plots.debugpaste", -category = CommandCategory.DEBUG) + aliases = "dp", usage = "/plot debugpaste", + description = "Upload settings.yml & latest.log to HasteBin", + permission = "plots.debugpaste", + category = CommandCategory.DEBUG) public class DebugPaste extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, String[] args) { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { try { - final String settingsYML = HastebinUtility.upload(PS.get().configFile); + String settingsYML = HastebinUtility.upload(PS.get().configFile); String latestLOG; try { latestLOG = HastebinUtility.upload(new File(PS.get().IMP.getDirectory(), "../../logs/latest.log")); @@ -33,8 +34,10 @@ public class DebugPaste extends SubCommand { MainUtil.sendMessage(plr, "&clatest.log is too big to be pasted, will ignore"); latestLOG = "too big :("; } - final StringBuilder b = new StringBuilder(); - b.append("# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your problem\n\n# We will start with some informational files\n"); + StringBuilder b = new StringBuilder(); + b.append( + "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " + + "problem\n\n# We will start with some informational files\n"); b.append("links.settings_yml: ").append(settingsYML).append("\n"); b.append("links.latest_log: ").append(latestLOG).append("\n"); b.append("\n# Server Information\n"); @@ -48,10 +51,11 @@ public class DebugPaste extends SubCommand { String enabled = split.length == 2 ? split[1] : "unknown"; String name = split2[0]; String version = split2.length == 2 ? split2[1] : "unknown"; - b.append("\n ").append(name).append(":\n ").append("version: '").append(version).append("'").append("\n enabled: ").append(enabled); + b.append("\n ").append(name).append(":\n ").append("version: '").append(version).append("'").append("\n enabled: ") + .append(enabled); } b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); - final Runtime runtime = Runtime.getRuntime(); + Runtime runtime = Runtime.getRuntime(); b.append("memory.free: ").append(runtime.freeMemory()).append("\n"); b.append("memory.max: ").append(runtime.maxMemory()).append("\n"); b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n"); @@ -63,9 +67,9 @@ public class DebugPaste extends SubCommand { b.append("# Okay :D Great. You are now ready to create your bug report!"); b.append("\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); - final String link = HastebinUtility.upload(b.toString()); + String link = HastebinUtility.upload(b.toString()); plr.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); - } catch (final IOException e) { + } catch (IOException e) { e.printStackTrace(); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java index 843c56f97..345939f52 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java @@ -34,40 +34,41 @@ import com.intellectualcrafters.plot.util.MathMan; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "debugroadregen", -usage = "/plot debugroadregen", -requiredType = RequiredType.NONE, -description = "Regenerate all roads based on the road schematic", -category = CommandCategory.DEBUG, -permission = "plots.debugroadregen") + command = "debugroadregen", + usage = "/plot debugroadregen", + requiredType = RequiredType.NONE, + description = "Regenerate all roads based on the road schematic", + category = CommandCategory.DEBUG, + permission = "plots.debugroadregen") public class DebugRoadRegen extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer player, final String... args) { - final Location loc = player.getLocation(); - final PlotArea plotworld = loc.getPlotArea(); + public boolean onCommand(PlotPlayer player, String... args) { + Location loc = player.getLocation(); + PlotArea plotworld = loc.getPlotArea(); if (!(plotworld instanceof HybridPlotWorld)) { return sendMessage(player, C.NOT_IN_PLOT_WORLD); } - final Plot plot = player.getCurrentPlot(); + Plot plot = player.getCurrentPlot(); if (plot == null) { - final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); + ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); int extend = 0; if (args.length == 1) { if (MathMan.isInteger(args[0])) { try { extend = Integer.parseInt(args[0]); - } catch (final Exception e) { + } catch (Exception e) { C.NOT_VALID_NUMBER.send(player, "(0, )"); return false; } } } - final boolean result = HybridUtils.manager.regenerateRoad(plotworld, chunk, extend); - MainUtil.sendMessage(player, "&6Regenerating chunk: " + chunk.x + "," + chunk.z + "\n&6 - Result: " + (result ? "&aSuccess" : "&cFailed")); + boolean result = HybridUtils.manager.regenerateRoad(plotworld, chunk, extend); + MainUtil.sendMessage(player, + "&6Regenerating chunk: " + chunk.x + "," + chunk.z + "\n&6 - Result: " + (result ? "&aSuccess" : "&cFailed")); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } else { - final HybridPlotManager manager = (HybridPlotManager) plotworld.getPlotManager(); + HybridPlotManager manager = (HybridPlotManager) plotworld.getPlotManager(); manager.createRoadEast(plotworld, plot); manager.createRoadSouth(plotworld, plot); manager.createRoadSouthEast(plotworld, plot); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java index 67148e362..616039e23 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java @@ -20,8 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Plot; @@ -29,18 +27,20 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; + @CommandDeclaration( -command = "debugsavetest", -permission = "plots.debugsavetest", -category = CommandCategory.DEBUG, -requiredType = RequiredType.CONSOLE, -usage = "/plot debugsavetest", -description = "This command will force the recreation of all plots in the DB") + command = "debugsavetest", + permission = "plots.debugsavetest", + category = CommandCategory.DEBUG, + requiredType = RequiredType.CONSOLE, + usage = "/plot debugsavetest", + description = "This command will force the recreation of all plots in the DB") public class DebugSaveTest extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final ArrayList plots = new ArrayList(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + ArrayList plots = new ArrayList(); plots.addAll(PS.get().getPlots()); MainUtil.sendMessage(plr, "&6Starting `DEBUGSAVETEST`"); DBFunc.createPlotsAndData(plots, new Runnable() { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java index 3cd2f4828..d47181e85 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java @@ -36,19 +36,19 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.HashSet; @CommandDeclaration( -command = "delete", -permission = "plots.delete", -description = "Delete a plot", -usage = "/plot delete", -aliases = { "dispose", "del" }, -category = CommandCategory.CLAIMING, -requiredType = RequiredType.NONE) + command = "delete", + permission = "plots.delete", + description = "Delete a plot", + usage = "/plot delete", + aliases = {"dispose", "del"}, + category = CommandCategory.CLAIMING, + requiredType = RequiredType.NONE) public class Delete extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - - final Location loc = plr.getLocation(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + + Location loc = plr.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); @@ -61,7 +61,7 @@ public class Delete extends SubCommand { } final PlotArea plotworld = plot.getArea(); final HashSet plots = plot.getConnectedPlots(); - final Runnable run = new Runnable() { + Runnable run = new Runnable() { @Override public void run() { if (plot.getRunning() > 0) { @@ -74,7 +74,7 @@ public class Delete extends SubCommand { public void run() { plot.removeRunning(); if ((EconHandler.manager != null) && plotworld.USE_ECONOMY) { - final double value = plotworld.PRICES.get("sell") * plots.size(); + double value = plotworld.PRICES.get("sell") * plots.size(); if (value > 0d) { EconHandler.manager.depositMoney(plr, value); sendMessage(plr, C.ADDED_BALANCE, value + ""); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java index 617212d8c..99c242416 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java @@ -28,30 +28,31 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.PlotGamemode; +import com.intellectualcrafters.plot.util.PlotGameMode; import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.UUID; @CommandDeclaration(command = "deny", -aliases = { "d", "ban" }, -description = "Deny a user from a plot", -usage = "/plot deny ", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + aliases = {"d", "ban"}, + description = "Deny a user from a plot", + usage = "/plot deny ", + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Deny extends SubCommand { public Deny() { - requiredArguments = new Argument[] { Argument.PlayerName }; + this.requiredArguments = new Argument[]{Argument.PlayerName}; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } @@ -97,7 +98,7 @@ public class Deny extends SubCommand { return true; } - private void handleKick(final PlotPlayer pp, final Plot plot) { + private void handleKick(PlotPlayer pp, Plot plot) { if (pp == null) { return; } @@ -107,7 +108,7 @@ public class Deny extends SubCommand { if (pp.hasPermission("plots.admin.entry.denied")) { return; } - if (pp.getGamemode() == PlotGamemode.SPECTATOR) { + if (pp.getGameMode() == PlotGameMode.SPECTATOR) { pp.stopSpectating(); } pp.teleport(WorldUtil.IMP.getSpawn(pp.getLocation().getWorld())); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java index a6ab5965e..03dcb294f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java @@ -29,13 +29,13 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "setdescription", -permission = "plots.set.desc", -description = "Set the plot description", -usage = "/plot desc ", -aliases = { "desc", "setdesc", "setd", "description" }, -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + command = "setdescription", + permission = "plots.set.desc", + description = "Set the plot description", + usage = "/plot desc ", + aliases = {"desc", "setdesc", "setd", "description"}, + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Desc extends SetCommand { @Override @@ -45,8 +45,8 @@ public class Desc extends SetCommand { MainUtil.sendMessage(plr, C.DESC_UNSET); return true; } - final Flag flag = new Flag(FlagManager.getFlag("description"), desc); - final boolean result = FlagManager.addPlotFlag(plot, flag); + Flag flag = new Flag(FlagManager.getFlag("description"), desc); + boolean result = FlagManager.addPlotFlag(plot, flag); if (!result) { MainUtil.sendMessage(plr, C.FLAG_NOT_ADDED); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java index 7156180e7..bcc328c15 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java @@ -35,21 +35,21 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "done", -aliases = { "submit" }, -description = "Mark a plot as done", -permission = "plots.done", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + aliases = {"submit"}, + description = "Mark a plot as done", + permission = "plots.done", + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Done extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); final Plot plot = loc.getPlotAbs(); if ((plot == null) || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } - if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.done")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.done")) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } @@ -68,7 +68,7 @@ public class Done extends SubCommand { public void run(PlotAnalysis value) { plot.removeRunning(); if ((value == null) || (value.getComplexity() >= Settings.CLEAR_THRESHOLD)) { - final Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000)); + Flag flag = new Flag(FlagManager.getFlag("done"), System.currentTimeMillis() / 1000); FlagManager.addPlotFlag(plot, flag); MainUtil.sendMessage(plr, C.DONE_SUCCESS); } else { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java index c5a852d50..7a42a944c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java @@ -15,20 +15,21 @@ import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.net.URL; @CommandDeclaration(usage = "/plot download [schematic|bo3|world]", -command = "download", -aliases = { "dl" }, -category = CommandCategory.SCHEMATIC, -requiredType = RequiredType.NONE, -description = "Download your plot", -permission = "plots.download") + command = "download", + aliases = {"dl"}, + category = CommandCategory.SCHEMATIC, + requiredType = RequiredType.NONE, + description = "Download your plot", + permission = "plots.download") public class Download extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final String world = plr.getLocation().getWorld(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + String world = plr.getLocation().getWorld(); if (!PS.get().hasPlotArea(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } @@ -40,7 +41,8 @@ public class Download extends SubCommand { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if ((!plot.isOwner(plr.getUUID()) || (Settings.DOWNLOAD_REQUIRES_DONE && (FlagManager.getPlotFlagRaw(plot, "done") != null))) && !Permissions.hasPermission(plr, "plots.admin.command.download")) { + if ((!plot.isOwner(plr.getUUID()) || (Settings.DOWNLOAD_REQUIRES_DONE && (FlagManager.getPlotFlagRaw(plot, "done") != null))) && !Permissions + .hasPermission(plr, "plots.admin.command.download")) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } @@ -52,7 +54,7 @@ public class Download extends SubCommand { plot.addRunning(); SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { @Override - public void run(final CompoundTag value) { + public void run(CompoundTag value) { plot.removeRunning(); SchematicHandler.manager.upload(value, null, null, new RunnableVal() { @Override @@ -99,8 +101,7 @@ public class Download extends SubCommand { MainUtil.sendMessage(plr, url.toString()); } }); - } - else { + } else { C.COMMAND_SYNTAX.send(plr, getUsage()); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java index eeeeb4aaf..3c5e53656 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java @@ -40,22 +40,22 @@ import java.util.HashMap; import java.util.Map; @CommandDeclaration( -command = "setflag", -aliases = { "f", "flag", "setf", "setflag" }, -usage = "/plot flag ", -description = "Set plot flags", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE, -permission = "plots.flag") + command = "setflag", + aliases = {"f", "flag", "setf", "setflag"}, + usage = "/plot flag ", + description = "Set plot flags", + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE, + permission = "plots.flag") public class FlagCmd extends SubCommand { - + @Override public String getUsage() { return super.getUsage().replaceAll("", StringMan.join(FlagManager.getFlags(), "|")); } - + @Override - public boolean onCommand(final PlotPlayer player, final String... args) { + public boolean onCommand(PlotPlayer player, String... args) { /* * plot flag set fly true @@ -68,8 +68,8 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag "); return false; } - final Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location loc = player.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { MainUtil.sendMessage(player, C.NOT_IN_PLOT); return false; @@ -96,7 +96,7 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info "); return false; } - final AbstractFlag af = FlagManager.getFlag(args[1]); + AbstractFlag af = FlagManager.getFlag(args[1]); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info "); @@ -119,23 +119,23 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag set "); return false; } - final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); + AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } - final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); + String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + value.toLowerCase())) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + value.toLowerCase()); return false; } - final Object parsed = af.parseValueRaw(value); + Object parsed = af.parseValueRaw(value); if (parsed == null) { MainUtil.sendMessage(player, "&c" + af.getValueDesc()); return false; } - final Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed); - final boolean result = FlagManager.addPlotFlag(plot, flag); + Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed); + boolean result = FlagManager.addPlotFlag(plot, flag); if (!result) { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; @@ -152,18 +152,18 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); return false; } - final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); + AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } - final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()); + Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()); if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { if (args.length != 2) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase()); return false; } - for (final String entry : args[2].split(",")) { + for (String entry : args[2].split(",")) { if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + entry); return false; @@ -175,11 +175,11 @@ public class FlagCmd extends SubCommand { return false; } if (args.length == 3 && flag.getAbstractFlag().isList()) { - final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); + String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); ((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value); DBFunc.setFlags(plot, plot.getFlags().values()); } else { - final boolean result = FlagManager.removePlotFlag(plot, flag.getKey()); + boolean result = FlagManager.removePlotFlag(plot, flag.getKey()); if (!result) { MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED); return false; @@ -197,19 +197,19 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); return false; } - final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); + AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } - for (final String entry : args[2].split(",")) { + for (String entry : args[2].split(",")) { if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + entry); return false; } } - final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); - final Object parsed = af.parseValueRaw(value); + String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); + Object parsed = af.parseValueRaw(value); if (parsed == null) { MainUtil.sendMessage(player, "&c" + af.getValueDesc()); return false; @@ -220,7 +220,7 @@ public class FlagCmd extends SubCommand { } else { ((FlagValue.ListValue) flag.getAbstractFlag().value).add(flag.getValue(), value); } - final boolean result = FlagManager.addPlotFlag(plot, flag); + boolean result = FlagManager.addPlotFlag(plot, flag); if (!result) { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; @@ -238,9 +238,9 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag list"); return false; } - final HashMap> flags = new HashMap<>(); - for (final AbstractFlag af : FlagManager.getFlags()) { - final String type = af.value.getClass().getSimpleName().replaceAll("Value", ""); + HashMap> flags = new HashMap<>(); + for (AbstractFlag af : FlagManager.getFlags()) { + String type = af.value.getClass().getSimpleName().replaceAll("Value", ""); if (!flags.containsKey(type)) { flags.put(type, new ArrayList()); } @@ -248,7 +248,7 @@ public class FlagCmd extends SubCommand { } String message = ""; String prefix = ""; - for (final Map.Entry> stringArrayListEntry : flags.entrySet()) { + for (Map.Entry> stringArrayListEntry : flags.entrySet()) { message += prefix + "&6" + stringArrayListEntry.getKey() + ": &7" + StringMan.join(stringArrayListEntry.getValue(), ", "); prefix = "\n"; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java index f232baa7f..8cbbfd291 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java @@ -4,6 +4,7 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.Command; + import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -20,40 +21,43 @@ public class GenerateDocs { public static void main(String[] args) { MainCommand.getInstance().addCommand(new WE_Anywhere()); MainCommand.getInstance().addCommand(new Cluster()); - final ArrayList> commands = MainCommand.getInstance().getCommands(); + ArrayList> commands = MainCommand.getInstance().getCommands(); log("### Want to document some commands?"); log(" - This page is automatically generated"); log(" - Fork the project and add a javadoc comment to one of the command classes"); log(" - Then do a pull request and it will be added to this page"); log(""); log("# Contents"); - for (final CommandCategory category : CommandCategory.values()) { + for (CommandCategory category : CommandCategory.values()) { log("###### " + category.name()); - for (final Command command : MainCommand.getCommands(category, null)) { - log(" - [/plot " + command.getCommand() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getCommand() + ") "); + for (Command command : MainCommand.getCommands(category, null)) { + log(" - [/plot " + command.getCommand() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getCommand() + + ") "); } log(""); } log("# Commands"); - for (final Command command : commands) { + for (Command command : commands) { printCommand(command); } } public static void printCommand(Command command) { try { - final String clazz = command.getClass().getSimpleName(); - final String name = command.getCommand(); + String clazz = command.getClass().getSimpleName(); + String name = command.getCommand(); // Header - final String source = "https://github.com/IntellectualSites/PlotSquared/tree/master/Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"; + String source = + "https://github.com/IntellectualSites/PlotSquared/tree/master/Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + + ".java"; log("## [" + name.toUpperCase() + "](" + source + ") "); - final File file = new File("Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); - final List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - final List perms = getPerms(name, lines); - final List usages = getUsage(name, lines); - final String comment = getComments(lines); + File file = new File("Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); + List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + List perms = getPerms(name, lines); + List usages = getUsage(name, lines); + String comment = getComments(lines); log("#### Description"); log("`" + command.getDescription() + "`"); @@ -84,7 +88,7 @@ public class GenerateDocs { log("`" + command.getRequiredType().name() + "`"); } - final Set aliases = command.getAliases(); + Set aliases = command.getAliases(); if (!aliases.isEmpty()) { log("#### Aliases"); log("`" + StringMan.getString(command.getAliases()) + "`"); @@ -103,17 +107,17 @@ public class GenerateDocs { } log("***"); log(""); - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); } } public static List getUsage(String cmd, List lines) { - final Pattern p = Pattern.compile("\"([^\"]*)\""); + Pattern p = Pattern.compile("\"([^\"]*)\""); HashSet usages = new HashSet(); - for (final String line : lines) { + for (String line : lines) { if (line.contains("COMMAND_SYNTAX") && !line.contains("getUsage()")) { - final Matcher m = p.matcher(line); + Matcher m = p.matcher(line); String prefix = ""; StringBuilder usage = new StringBuilder(); while (m.find()) { @@ -130,11 +134,11 @@ public class GenerateDocs { } public static List getPerms(String cmd, List lines) { - final HashSet perms = new HashSet<>(); - final Pattern p = Pattern.compile("\"([^\"]*)\""); - final Pattern p2 = Pattern.compile("C.PERMISSION_\\s*(\\w+)"); + HashSet perms = new HashSet<>(); + Pattern p = Pattern.compile("\"([^\"]*)\""); + Pattern p2 = Pattern.compile("C.PERMISSION_\\s*(\\w+)"); String last = null; - for (final String line : lines) { + for (String line : lines) { Matcher m2 = p2.matcher(line); while (m2.find()) { @@ -148,17 +152,15 @@ public class GenerateDocs { if (!perm.equalsIgnoreCase(perm)) { if (perm.startsWith("C.")) { perm = C.valueOf(perm.split("\\.")[1]).s(); - } - else { + } else { continue; } - } - else { + } else { perm = perm.substring(1, perm.length() - 1); } perms.add(perm); } - final Matcher m = p.matcher(line); + Matcher m = p.matcher(line); while (m.find()) { String perm = m.group(1); if (perm.endsWith(".")) { @@ -172,8 +174,7 @@ public class GenerateDocs { perms.add(perm); } } - } - else if (line.contains("Permissions.hasPermissionRange")) { + } else if (line.contains("Permissions.hasPermissionRange")) { String[] split = line.split("Permissions.hasPermissionRange"); split = Arrays.copyOfRange(split, 1, split.length); for (String method : split) { @@ -181,12 +182,10 @@ public class GenerateDocs { if (!perm.equalsIgnoreCase(perm)) { if (perm.startsWith("C.")) { perm = C.valueOf(perm.split("\\.")[1]).s(); - } - else { + } else { continue; } - } - else { + } else { perm = perm.substring(1, perm.length() - 1); } perms.add(perm + ".<#>"); @@ -204,7 +203,7 @@ public class GenerateDocs { } public static String getComments(List lines) { - final StringBuilder result = new StringBuilder(); + StringBuilder result = new StringBuilder(); for (String line : lines) { line = line.trim(); if (line.startsWith("/** ") || line.startsWith("*/ ") || line.startsWith("* ")) { @@ -215,7 +214,7 @@ public class GenerateDocs { return result.toString().trim(); } - public static void log(final String s) { + public static void log(String s) { System.out.println(s); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java index 060691cc9..c479f86b5 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java @@ -9,17 +9,19 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.UUID; @CommandDeclaration( -command = "grant", -category = CommandCategory.CLAIMING, -usage = "/plot grant [player]", -permission = "plots.grant", -requiredType = RequiredType.NONE) + command = "grant", + category = CommandCategory.CLAIMING, + usage = "/plot grant [player]", + permission = "plots.grant", + requiredType = RequiredType.NONE) public class Grant extends SubCommand { + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, String[] args) { final String arg0 = args[0].toLowerCase(); switch (arg0) { case "add": diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java index bc5f430aa..5406712f2 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java @@ -4,13 +4,13 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "help", -description = "Get this help menu", -aliases = { "he" }, -category = CommandCategory.INFO) + description = "Get this help menu", + aliases = {"he"}, + category = CommandCategory.INFO) public class Help extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { return true; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Home.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Home.java index 8ebb68525..d9a5197c0 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Home.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Home.java @@ -24,15 +24,15 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "home", -aliases = { "h" }, -description = "Go to your plot", -usage = "/plot home [id|alias]", -category = CommandCategory.TELEPORT, -requiredType = RequiredType.NONE) + aliases = {"h"}, + description = "Go to your plot", + usage = "/plot home [id|alias]", + category = CommandCategory.TELEPORT, + requiredType = RequiredType.NONE) public class Home extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { return MainCommand.getInstance().getCommand("visit").onCommand(plr, args); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java index b583af95a..441a641bf 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java @@ -35,26 +35,26 @@ import java.util.ArrayList; import java.util.List; @CommandDeclaration( -command = "inbox", -description = "Review the comments for a plot", -usage = "/plot inbox [inbox] [delete |clear|page]", -permission = "plots.inbox", -category = CommandCategory.CHAT, -requiredType = RequiredType.NONE) + command = "inbox", + description = "Review the comments for a plot", + usage = "/plot inbox [inbox] [delete |clear|page]", + permission = "plots.inbox", + category = CommandCategory.CHAT, + requiredType = RequiredType.NONE) public class Inbox extends SubCommand { - - public void displayComments(final PlotPlayer player, final List oldComments, int page) { + + public void displayComments(PlotPlayer player, List oldComments, int page) { if ((oldComments == null) || oldComments.isEmpty()) { MainUtil.sendMessage(player, C.INBOX_EMPTY); return; } - final PlotComment[] comments = oldComments.toArray(new PlotComment[oldComments.size()]); + PlotComment[] comments = oldComments.toArray(new PlotComment[oldComments.size()]); if (page < 0) { page = 0; } // Get the total pages // int totalPages = ((int) Math.ceil(12 * - final int totalPages = (int) Math.ceil(comments.length / 12); + int totalPages = (int) Math.ceil(comments.length / 12); if (page > totalPages) { page = totalPages; } @@ -63,8 +63,10 @@ public class Inbox extends SubCommand { if (max > comments.length) { max = comments.length; } - final StringBuilder string = new StringBuilder(); - string.append(StringMan.replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", page + 1, "%max", totalPages + 1, "%word", "all") + "\n"); + StringBuilder string = new StringBuilder(); + string.append(StringMan + .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", page + 1, "%max", totalPages + 1, "%word", "all") + + "\n"); // This might work xD for (int x = page * 12; x < max; x++) { @@ -79,10 +81,10 @@ public class Inbox extends SubCommand { } MainUtil.sendMessage(player, string.toString()); } - + @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { - + public boolean onCommand(final PlotPlayer player, String[] args) { + final Plot plot = player.getCurrentPlot(); if (args.length == 0) { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); @@ -94,7 +96,7 @@ public class Inbox extends SubCommand { if (value != null) { int total = 0; int unread = 0; - for (final PlotComment comment : value) { + for (PlotComment comment : value) { total++; if (comment.timestamp > CommentManager.getTimestamp(player, inbox.toString())) { unread++; @@ -144,11 +146,11 @@ public class Inbox extends SubCommand { sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); return false; } - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); return false; } - + if (!inbox.getComments(plot, new RunnableVal>() { @Override public void run(List value) { @@ -156,7 +158,7 @@ public class Inbox extends SubCommand { sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); return; } - final PlotComment comment = value.get(index - 1); + PlotComment comment = value.get(index - 1); inbox.removeComment(plot, comment); plot.getSettings().removeComment(comment); MainUtil.sendMessage(player, C.COMMENT_REMOVED, comment.comment); @@ -172,7 +174,7 @@ public class Inbox extends SubCommand { sendMessage(player, C.NO_PERM_INBOX_MODIFY); } inbox.clearInbox(plot); - final ArrayList comments = plot.getSettings().getComments(inbox.toString()); + ArrayList comments = plot.getSettings().getComments(inbox.toString()); if (comments != null) { plot.getSettings().removeComments(comments); } @@ -182,7 +184,7 @@ public class Inbox extends SubCommand { default: { try { page = Integer.parseInt(args[1]); - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java index 1be555389..2536810cd 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java @@ -29,13 +29,14 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.UUID; @CommandDeclaration(command = "info", -aliases = "i", -description = "Display plot info", -usage = "/plot info ", -category = CommandCategory.INFO) + aliases = "i", + description = "Display plot info", + usage = "/plot info ", + category = CommandCategory.INFO) public class Info extends SubCommand { @Override @@ -82,20 +83,20 @@ public class Info extends SubCommand { if (args.length == 1) { args = new String[0]; } else { - args = new String[] { args[1] }; + args = new String[]{args[1]}; } } if ((args.length == 1) && args[0].equalsIgnoreCase("inv")) { - final PlotInventory inv = new PlotInventory(player) { + PlotInventory inv = new PlotInventory(player) { @Override - public boolean onClick(final int index) { + public boolean onClick(int index) { // TODO InfoInventory not implemented yet!!!!!!!! // See plot rating or musicsubcommand on examples return false; } }; - final UUID uuid = player.getUUID(); - final String name = MainUtil.getName(plot.owner); + UUID uuid = player.getUUID(); + String name = MainUtil.getName(plot.owner); inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, "&cAlias: &6" + plot.getAlias(), @@ -113,7 +114,7 @@ public class Info extends SubCommand { inv.openInventory(); return true; } - final boolean hasOwner = plot.hasOwner(); + boolean hasOwner = plot.hasOwner(); boolean containsEveryone; boolean trustedEveryone; // Wildcard player {added} @@ -123,7 +124,7 @@ public class Info extends SubCommand { } // Unclaimed? if (!hasOwner && !containsEveryone && !trustedEveryone) { - MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.getId().x + ";" + plot.getId().y)); + MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.getId().x + ";" + plot.getId().y); return true; } String info = C.PLOT_INFO.s(); @@ -131,7 +132,9 @@ public class Info extends SubCommand { if (arg != null) { info = getCaption(arg); if (info == null) { - MainUtil.sendMessage(player, "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating"); + MainUtil.sendMessage(player, + "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, " + + "&arating"); return false; } full = true; @@ -147,7 +150,7 @@ public class Info extends SubCommand { return true; } - private String getCaption(final String string) { + private String getCaption(String string) { switch (string) { case "trusted": return C.PLOT_INFO_TRUSTED.s(); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java index 4b35ea0bf..5636d9111 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java @@ -31,21 +31,21 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(command = "kick", -aliases = { "k" }, -description = "Kick a player from your plot", -permission = "plots.kick", -category = CommandCategory.TELEPORT, -requiredType = RequiredType.NONE) + aliases = {"k"}, + description = "Kick a player from your plot", + permission = "plots.kick", + category = CommandCategory.TELEPORT, + requiredType = RequiredType.NONE) public class Kick extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlot(); + public boolean onCommand(PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); + Plot plot = loc.getPlot(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } - if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.kick"))) { + if ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.kick")) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } @@ -53,12 +53,12 @@ public class Kick extends SubCommand { MainUtil.sendMessage(plr, "&c/plot kick "); return false; } - final PlotPlayer player = UUIDHandler.getPlayer(args[0]); + PlotPlayer player = UUIDHandler.getPlayer(args[0]); if (player == null) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - final Location otherLoc = player.getLocation(); + Location otherLoc = player.getLocation(); if (!plr.getLocation().getWorld().equals(otherLoc.getWorld()) || !plot.equals(otherLoc.getPlot())) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; 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 ad00530e8..a80686607 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java @@ -19,23 +19,24 @@ import java.net.URL; import java.util.List; @CommandDeclaration( -command = "load", -aliases = { "restore" }, -category = CommandCategory.SCHEMATIC, -requiredType = RequiredType.NONE, -description = "Load your plot", -permission = "plots.load", -usage = "/plot restore") + command = "load", + aliases = {"restore"}, + category = CommandCategory.SCHEMATIC, + requiredType = RequiredType.NONE, + description = "Load your plot", + permission = "plots.load", + usage = "/plot restore") public class Load extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, String[] args) { + if (!Settings.METRICS) { - MainUtil.sendMessage(plr, "&cPlease enable metrics in order to use this command.\n&7 - Or host it yourself if you don't like the free service"); + MainUtil.sendMessage(plr, + "&cPlease enable metrics in order to use this command.\n&7 - Or host it yourself if you don't like the free service"); return false; } - final String world = plr.getLocation().getWorld(); + String world = plr.getLocation().getWorld(); if (!PS.get().hasPlotArea(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } @@ -55,10 +56,10 @@ public class Load extends SubCommand { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } - + if (args.length != 0) { if (args.length == 1) { - final List schematics = plr.getMeta("plot_schematics"); + List schematics = plr.getMeta("plot_schematics"); if (schematics == null) { // No schematics found: MainUtil.sendMessage(plr, C.LOAD_NULL); @@ -67,7 +68,7 @@ public class Load extends SubCommand { String schem; try { schem = schematics.get(Integer.parseInt(args[0]) - 1); - } catch (final Exception e) { + } catch (Exception e) { // use /plot load MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ")"); return false; @@ -75,7 +76,7 @@ public class Load extends SubCommand { final URL url; try { url = new URL(Settings.WEB_URL + "saves/" + plr.getUUID() + "/" + schem + ".schematic"); - } catch (final MalformedURLException e) { + } catch (MalformedURLException e) { e.printStackTrace(); MainUtil.sendMessage(plr, C.LOAD_FAILED); return false; @@ -85,7 +86,7 @@ public class Load extends SubCommand { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final Schematic schematic = SchematicHandler.manager.getSchematic(url); + Schematic schematic = SchematicHandler.manager.getSchematic(url); if (schematic == null) { plot.removeRunning(); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); @@ -110,18 +111,18 @@ public class Load extends SubCommand { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot load "); return false; } - + // list schematics - - final List schematics = plr.getMeta("plot_schematics"); + + List schematics = plr.getMeta("plot_schematics"); if (schematics == null) { plot.addRunning(); TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final List schematics = SchematicHandler.manager.getSaves(plr.getUUID()); + List schematics = SchematicHandler.manager.getSaves(plr.getUUID()); plot.removeRunning(); - if ((schematics == null) || (schematics.isEmpty())) { + if ((schematics == null) || schematics.isEmpty()) { MainUtil.sendMessage(plr, C.LOAD_FAILED); return; } @@ -134,37 +135,38 @@ public class Load extends SubCommand { } return true; } - - public void displaySaves(final PlotPlayer player, final int page) { - final List schematics = player.getMeta("plot_schematics"); + + public void displaySaves(PlotPlayer player, int page) { + List schematics = player.getMeta("plot_schematics"); for (int i = 0; i < Math.min(schematics.size(), 32); i++) { try { - final String schem = schematics.get(i); - final String[] split = schem.split("_"); + String schem = schematics.get(i); + String[] split = schem.split("_"); if (split.length != 6) { continue; } - final String time = secToTime((System.currentTimeMillis() / 1000) - (Long.parseLong(split[0]))); - final String world = split[1]; - final PlotId id = PlotId.fromString(split[2] + ";" + split[3]); - final String size = split[4]; - final String server = split[5].replaceAll(".schematic", ""); + String time = secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); + String world = split[1]; + PlotId id = PlotId.fromString(split[2] + ";" + split[3]); + String size = split[4]; + String server = split[5].replaceAll(".schematic", ""); String color; if (PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "").equals(server)) { color = "$4"; } else { color = "$1"; } - MainUtil.sendMessage(player, "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ";" + id + "$3 | " + color + size + "x" + size); - } catch (final Exception e) { + MainUtil.sendMessage(player, + "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ";" + id + "$3 | " + color + size + "x" + size); + } catch (Exception e) { e.printStackTrace(); } } MainUtil.sendMessage(player, C.LOAD_LIST); } - + public String secToTime(long time) { - final StringBuilder toreturn = new StringBuilder(); + StringBuilder toreturn = new StringBuilder(); if (time >= 33868800) { int years = (int) (time / 33868800); time -= years * 33868800; @@ -191,7 +193,7 @@ public class Load extends SubCommand { toreturn.append(minutes + "m "); } if (toreturn.equals("") || (time > 0)) { - toreturn.append((time) + "s "); + toreturn.append(time + "s "); } return toreturn.toString().trim(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index 6b9feb7b4..29ff2e7df 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -37,6 +37,7 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandHandlingOutput; import com.plotsquared.general.commands.CommandManager; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -44,11 +45,10 @@ import java.util.HashSet; import java.util.List; /** - * PlotSquared command class - * - + * PlotSquared command class. */ public class MainCommand extends CommandManager { + private static MainCommand instance; private MainCommand() { @@ -137,14 +137,14 @@ public class MainCommand extends CommandManager { return instance; } - public static boolean no_permission(final PlotPlayer player, final String permission) { + public static boolean no_permission(PlotPlayer player, String permission) { MainUtil.sendMessage(player, C.NO_PERMISSION, permission); return false; } - public static List> getCommandAndAliases(final CommandCategory category, final PlotPlayer player) { - final List> commands = new ArrayList<>(); - for (final Command command : getInstance().getCommands()) { + public static List> getCommandAndAliases(CommandCategory category, PlotPlayer player) { + List> commands = new ArrayList<>(); + for (Command command : getInstance().getCommands()) { if ((category != null) && !command.getCategory().equals(category)) { continue; } @@ -156,9 +156,9 @@ public class MainCommand extends CommandManager { return commands; } - public static List> getCommands(final CommandCategory category, final PlotPlayer player) { - final List> commands = new ArrayList<>(); - for (final Command command : new HashSet<>(getInstance().getCommands())) { + public static List> getCommands(CommandCategory category, PlotPlayer player) { + List> commands = new ArrayList<>(); + for (Command command : new HashSet<>(getInstance().getCommands())) { if ((category != null) && !command.getCategory().equals(category)) { continue; } @@ -170,13 +170,13 @@ public class MainCommand extends CommandManager { return commands; } - public static void displayHelp(final PlotPlayer player, String cat, int page, final String label) { + public static void displayHelp(PlotPlayer player, String cat, int page, String label) { CommandCategory catEnum = null; if (cat != null) { if (StringMan.isEqualIgnoreCase(cat, "all")) { catEnum = null; } else { - for (final CommandCategory c : CommandCategory.values()) { + for (CommandCategory c : CommandCategory.values()) { if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { catEnum = c; cat = c.name(); @@ -188,11 +188,12 @@ public class MainCommand extends CommandManager { } } } - if ((cat == null) && (page == 0)) { - final StringBuilder builder = new StringBuilder(); + if (cat == null && page == 0) { + StringBuilder builder = new StringBuilder(); builder.append(C.HELP_HEADER.s()); - for (final CommandCategory c : CommandCategory.values()) { - builder.append("\n" + StringMan.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); + for (CommandCategory c : CommandCategory.values()) { + builder.append( + "\n" + StringMan.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); } builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all").replaceAll("%category_desc%", "Display all commands")); builder.append("\n" + C.HELP_FOOTER.s()); @@ -203,7 +204,7 @@ public class MainCommand extends CommandManager { new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages().generatePage(page, label).render(); } - public static boolean onCommand(final PlotPlayer player, final String cmd, String... args) { + public static boolean onCommand(PlotPlayer player, String cmd, String... args) { // Clear perm caching // player.deleteMeta("perm"); //////////////////////// @@ -221,7 +222,8 @@ public class MainCommand extends CommandManager { if (MathMan.isInteger(args[0])) { try { help_index = Integer.parseInt(args[args.length - 1]); - } catch (final NumberFormatException e) {} + } catch (NumberFormatException e) { + } break; } } @@ -240,7 +242,7 @@ public class MainCommand extends CommandManager { category = null; try { help_index = Integer.parseInt(args[1]); - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { help_index = 1; } } else { @@ -254,7 +256,7 @@ public class MainCommand extends CommandManager { if (MathMan.isInteger(args[2])) { try { help_index = Integer.parseInt(args[2]); - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { help_index = 1; } } @@ -274,7 +276,8 @@ public class MainCommand extends CommandManager { if (newPlot == null) { break; } - if (!ConsolePlayer.isConsole(player) && (!newPlot.getArea().equals(area) || newPlot.isDenied(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN)) { + if (!ConsolePlayer.isConsole(player) && (!newPlot.getArea().equals(area) || newPlot.isDenied(player.getUUID())) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN)) { break; } // Save meta @@ -332,7 +335,7 @@ public class MainCommand extends CommandManager { } } String[] usage = cmd.getUsage().split(" "); - for (int i = 0; i < Math.min(4 , usage.length); i++) { + for (int i = 0; i < Math.min(4, usage.length); i++) { int require; if (usage[i].startsWith("<")) { require = 1; @@ -353,8 +356,8 @@ public class MainCommand extends CommandManager { } @Override - public int handle(final PlotPlayer plr, final String input) { - final String[] parts = input.split(" "); + public int handle(PlotPlayer plr, String input) { + String[] parts = input.split(" "); String[] args; String label; if (parts.length == 1) { @@ -387,18 +390,18 @@ public class MainCommand extends CommandManager { if (cmd == null) { MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); { - final List> cmds = getCommands(null, plr); - if ((label == null) || (cmds.isEmpty())) { + List> cmds = getCommands(null, plr); + if ((label == null) || cmds.isEmpty()) { MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); } else { - final HashSet setargs = new HashSet<>(args.length + 1); - for (final String arg : args) { + HashSet setargs = new HashSet<>(args.length + 1); + for (String arg : args) { setargs.add(arg.toLowerCase()); } setargs.add(label); - final String[] allargs = setargs.toArray(new String[setargs.size()]); + String[] allargs = setargs.toArray(new String[setargs.size()]); int best = 0; - for (final Command current : cmds) { + for (Command current : cmds) { int match = getMatch(allargs, current); if (match > best) { cmd = current; @@ -424,7 +427,7 @@ public class MainCommand extends CommandManager { MainUtil.sendMessage(plr, C.NO_PERMISSION, cmd.getPermission()); return CommandHandlingOutput.NOT_PERMITTED; } - final Argument[] requiredArguments = cmd.getRequiredArguments(); + Argument[] requiredArguments = cmd.getRequiredArguments(); if ((requiredArguments != null) && (requiredArguments.length > 0)) { boolean success = true; if (args.length < requiredArguments.length) { @@ -443,12 +446,12 @@ public class MainCommand extends CommandManager { } } try { - final boolean result = cmd.onCommand(plr, args); + boolean result = cmd.onCommand(plr, args); if (!result) { cmd.getUsage(); return CommandHandlingOutput.WRONG_USAGE; } - } catch (final Throwable t) { + } catch (Throwable t) { t.printStackTrace(); return CommandHandlingOutput.ERROR; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java index d44b57f24..47bd1a416 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java @@ -33,22 +33,24 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.HashSet; import java.util.UUID; @CommandDeclaration(command = "merge", -aliases = "m", -description = "Merge the plot you are standing on, with another plot", -permission = "plots.merge", usage = "/plot merge [removeroads]", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + aliases = "m", + description = "Merge the plot you are standing on, with another plot", + permission = "plots.merge", usage = "/plot merge [removeroads]", + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Merge extends SubCommand { - public final static String[] values = new String[] { "north", "east", "south", "west", "auto" }; - public final static String[] aliases = new String[] { "n", "e", "s", "w", "all" }; + + public final static String[] values = new String[]{"north", "east", "south", "west", "auto"}; + public final static String[] aliases = new String[]{"n", "e", "s", "w", "all"}; public static String direction(float yaw) { yaw = yaw / 90; - final int i = Math.round(yaw); + int i = Math.round(yaw); switch (i) { case -4: case 0: @@ -69,8 +71,8 @@ public class Merge extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocationFull(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + Location loc = plr.getLocationFull(); final Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); @@ -84,8 +86,7 @@ public class Merge extends SubCommand { if (!Permissions.hasPermission(plr, "plots.admin.command.merge")) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; - } - else { + } else { uuid = plot.owner; } } @@ -97,26 +98,26 @@ public class Merge extends SubCommand { } final int size = plot.getConnectedPlots().size(); final int maxSize = Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS); - if (size - 1> maxSize) { + if (size - 1 > maxSize) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.merge." + (size + 1)); return false; } int direction = -1; if (args.length == 0) { -// switch (direction(plr.getLocationFull().getYaw())) { -// case "NORTH": -// direction = 0; -// break; -// case "EAST": -// direction = 1; -// break; -// case "SOUTH": -// direction = 2; -// break; -// case "WEST": -// direction = 3; -// break; -// } + // switch (direction(plr.getLocationFull().getYaw())) { + // case "NORTH": + // direction = 0; + // break; + // case "EAST": + // direction = 1; + // break; + // case "SOUTH": + // direction = 2; + // break; + // case "WEST": + // direction = 3; + // break; + // } } else { if ("all".equalsIgnoreCase(args[0]) || "auto".equalsIgnoreCase(args[0])) { boolean terrain = Settings.MERGE_REMOVES_ROADS; @@ -184,7 +185,7 @@ public class Merge extends SubCommand { public void run() { MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); plot.autoMerge(dir, maxSize - size, owner, terrain); - final PlotPlayer pp = UUIDHandler.getPlayer(plr.getUUID()); + PlotPlayer pp = UUIDHandler.getPlayer(plr.getUUID()); if (pp == null) { sendMessage(accepter, C.MERGE_NOT_VALID); return; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java index 42d262edf..771b249cc 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java @@ -12,18 +12,18 @@ import com.plotsquared.general.commands.CommandDeclaration; * @author manuelgu, altered by Citymonstret */ @CommandDeclaration( -command = "middle", -aliases = { "center" }, -description = "Teleports you to the center of the current plot", -usage = "/plot middle", -category = CommandCategory.TELEPORT, -requiredType = RequiredType.PLAYER) + command = "middle", + aliases = {"center"}, + description = "Teleports you to the center of the current plot", + usage = "/plot middle", + category = CommandCategory.TELEPORT, + requiredType = RequiredType.PLAYER) public class Middle extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] arguments) { - final Location location = player.getLocation(); - final Plot plot = location.getPlot(); + Location location = player.getLocation(); + Plot plot = location.getPlot(); if (plot == null) { return sendMessage(player, C.NOT_IN_PLOT); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java index 261c3ff5f..13ab2c83d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java @@ -29,19 +29,19 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -usage = "/plot move ", -command = "move", -description = "Move a plot", -aliases = { "debugmove" }, -permission = "plots.move", -category = CommandCategory.CLAIMING, -requiredType = RequiredType.NONE) + usage = "/plot move ", + command = "move", + description = "Move a plot", + aliases = {"debugmove"}, + permission = "plots.move", + category = CommandCategory.CLAIMING, + requiredType = RequiredType.NONE) public class Move extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); - final Plot plot1 = loc.getPlotAbs(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); + Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); } @@ -53,8 +53,8 @@ public class Move extends SubCommand { C.COMMAND_SYNTAX.send(plr, getUsage()); return false; } - final Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true); - if ((plot2 == null)) { + Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true); + if (plot2 == null) { return false; } if (plot1.equals(plot2)) { @@ -78,5 +78,5 @@ public class Move extends SubCommand { return false; } } - + } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java index 81822fbbf..3ca50ba70 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java @@ -33,17 +33,17 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "music", -permission = "plots.music", -description = "Player music in a plot", -usage = "/plot music", -category = CommandCategory.APPEARANCE, -requiredType = RequiredType.NONE) + command = "music", + permission = "plots.music", + description = "Player music in a plot", + usage = "/plot music", + category = CommandCategory.APPEARANCE, + requiredType = RequiredType.NONE) public class Music extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { - final Location loc = player.getLocation(); + public boolean onCommand(PlotPlayer player, String[] args) { + Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); @@ -52,14 +52,14 @@ public class Music extends SubCommand { sendMessage(player, C.NO_PLOT_PERMS); return true; } - final PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { + PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { @Override - public boolean onClick(final int index) { - final PlotItemStack item = getItem(index); + public boolean onClick(int index) { + PlotItemStack item = getItem(index); if (item == null) { return true; } - final int id = item.id == 7 ? 0 : item.id; + int id = item.id == 7 ? 0 : item.id; if (id == 0) { FlagManager.removePlotFlag(plot, "music"); } else { @@ -70,15 +70,15 @@ public class Music extends SubCommand { }; int index = 0; for (int i = 2256; i < 2268; i++) { - final String name = "&r&6" + WorldUtil.IMP.getClosestMatchingName(new PlotBlock((short) i, (byte) 0)); - final String[] lore = { "&r&aClick to play!" }; - final PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore); + String name = "&r&6" + WorldUtil.IMP.getClosestMatchingName(new PlotBlock((short) i, (byte) 0)); + String[] lore = {"&r&aClick to play!"}; + PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore); inv.setItem(index, item); index++; } if (player.getMeta("music") != null) { - final String name = "&r&6Cancel music"; - final String[] lore = { "&r&cClick to cancel!" }; + String name = "&r&6Cancel music"; + String[] lore = {"&r&cClick to cancel!"}; inv.setItem(index, new PlotItemStack(7, (short) 0, 1, name, lore)); } inv.openInventory(); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java index 07303e630..932275d61 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java @@ -24,22 +24,26 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.*; +import com.intellectualcrafters.plot.util.CmdConfirm; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; import java.util.HashSet; import java.util.UUID; @CommandDeclaration( -command = "setowner", -permission = "plots.set.owner", -description = "Set the plot owner", -usage = "/plot setowner ", -aliases = { "owner", "so", "seto" }, -category = CommandCategory.CLAIMING, -requiredType = RequiredType.NONE) + command = "setowner", + permission = "plots.set.owner", + description = "Set the plot owner", + usage = "/plot setowner ", + aliases = {"owner", "so", "seto"}, + category = CommandCategory.CLAIMING, + requiredType = RequiredType.NONE) public class Owner extends SetCommand { - + @Override public boolean set(final PlotPlayer plr, final Plot plot, String value) { HashSet plots = plot.getConnectedPlots(); @@ -49,7 +53,8 @@ public class Owner extends SetCommand { try { uuid = UUID.fromString(value); name = MainUtil.getName(uuid); - } catch (Exception e) {} + } catch (Exception e) { + } } else { uuid = UUIDHandler.getUUID(value, null); name = UUIDHandler.getName(uuid); @@ -79,8 +84,8 @@ public class Owner extends SetCommand { C.INVALID_PLAYER_OFFLINE.send(plr, value); return false; } - final int size = plots.size(); - final int currentPlots = (Settings.GLOBAL_LIMIT ? other.getPlotCount() : other.getPlotCount(plot.getArea().worldname)) + size; + int size = plots.size(); + int currentPlots = (Settings.GLOBAL_LIMIT ? other.getPlotCount() : other.getPlotCount(plot.getArea().worldname)) + size; if (currentPlots > other.getAllowedPlots()) { sendMessage(plr, C.CANT_TRANSFER_MORE_PLOTS); return false; @@ -99,7 +104,7 @@ public class Owner extends SetCommand { } } }; - if (Settings.CONFIRM_SETOWNER && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { + if (Settings.CONFIRM_SETOWNER && !Permissions.hasPermission(plr, "plots.confirm.bypass")) { CmdConfirm.addPending(plr, "/plot set owner " + value, run); } else { TaskManager.runTask(run); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java index 8972aa649..1506dd4ec 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java @@ -38,15 +38,16 @@ import java.util.Map.Entry; import java.util.UUID; @CommandDeclaration( -usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", -command = "purge", -permission = "plots.admin", -description = "Purge all plots for a world", -category = CommandCategory.ADMINISTRATION, -requiredType = RequiredType.CONSOLE) + usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", + command = "purge", + permission = "plots.admin", + description = "Purge all plots for a world", + category = CommandCategory.ADMINISTRATION, + requiredType = RequiredType.CONSOLE) public class Purge extends SubCommand { + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, String[] args) { if (args.length == 0) { return false; } @@ -178,7 +179,7 @@ public class Purge extends SubCommand { } } DBFunc.purgeIds(ids); - C.PURGE_SUCCESS.send(plr, ids.size() + "/" + (toDelete.size())); + C.PURGE_SUCCESS.send(plr, ids.size() + "/" + toDelete.size()); } }); return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index 148b3a3b4..35758cd84 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -36,6 +36,7 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -44,31 +45,31 @@ import java.util.Map.Entry; import java.util.UUID; @CommandDeclaration(command = "rate", -permission = "plots.rate", -description = "Rate the plot", -usage = "/plot rate [#|next]", -aliases = "rt", -category = CommandCategory.INFO, -requiredType = RequiredType.NONE) + permission = "plots.rate", + description = "Rate the plot", + usage = "/plot rate [#|next]", + aliases = "rt", + category = CommandCategory.INFO, + requiredType = RequiredType.NONE) public class Rate extends SubCommand { @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { + public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 1) { if (args[0].equalsIgnoreCase("next")) { - final ArrayList plots = new ArrayList<>(PS.get().getBasePlots()); + ArrayList plots = new ArrayList<>(PS.get().getBasePlots()); Collections.sort(plots, new Comparator() { @Override - public int compare(final Plot p1, final Plot p2) { + public int compare(Plot p1, Plot p2) { double v1 = 0; if (!p1.getRatings().isEmpty()) { - for (final Entry entry : p1.getRatings().entrySet()) { + for (Entry entry : p1.getRatings().entrySet()) { v1 -= 11 - entry.getValue().getAverageRating(); } } double v2 = 0; if (!p2.getRatings().isEmpty()) { - for (final Entry entry : p2.getRatings().entrySet()) { + for (Entry entry : p2.getRatings().entrySet()) { v2 -= 11 - entry.getValue().getAverageRating(); } } @@ -78,8 +79,8 @@ public class Rate extends SubCommand { return v2 > v1 ? 1 : -1; } }); - final UUID uuid = player.getUUID(); - for (final Plot p : plots) { + UUID uuid = player.getUUID(); + for (Plot p : plots) { if ((!Settings.REQUIRE_DONE || p.getFlags().containsKey("done")) && p.isBasePlot() && (p.hasRatings() || !p.getRatings() .containsKey(uuid)) && !p.isAdded(uuid)) { p.teleportPlayer(player); @@ -107,7 +108,7 @@ public class Rate extends SubCommand { sendMessage(player, C.RATING_NOT_DONE); return false; } - if ((Settings.RATING_CATEGORIES != null) && (!Settings.RATING_CATEGORIES.isEmpty())) { + if ((Settings.RATING_CATEGORIES != null) && !Settings.RATING_CATEGORIES.isEmpty()) { final Runnable run = new Runnable() { @Override public void run() { @@ -117,25 +118,25 @@ public class Rate extends SubCommand { } final MutableInt index = new MutableInt(0); final MutableInt rating = new MutableInt(0); - final String title = Settings.RATING_CATEGORIES.get(0); - final PlotInventory inventory = new PlotInventory(player, 1, title) { + String title = Settings.RATING_CATEGORIES.get(0); + PlotInventory inventory = new PlotInventory(player, 1, title) { @Override - public boolean onClick(final int i) { + public boolean onClick(int i) { rating.add((i + 1) * Math.pow(10, index.getValue())); index.increment(); if (index.getValue() >= Settings.RATING_CATEGORIES.size()) { close(); - final int rV = rating.getValue(); - final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rV)); - plot.addRating(player.getUUID(), result); - sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); + int rV = rating.getValue(); + Rating result = EventUtil.manager.callRating(this.player, plot, new Rating(rV)); + plot.addRating(this.player.getUUID(), result); + sendMessage(this.player, C.RATING_APPLIED, plot.getId().toString()); return false; } setTitle(Settings.RATING_CATEGORIES.get(index.getValue())); - if (Permissions.hasPermission(player, "plots.comment")) { - final Command command = MainCommand.getInstance().getCommand("comment"); + if (Permissions.hasPermission(this.player, "plots.comment")) { + Command command = MainCommand.getInstance().getCommand("comment"); if (command != null) { - MainUtil.sendMessage(player, C.COMMENT_THIS, command.getUsage().replaceAll("{label}", "plot")); + MainUtil.sendMessage(this.player, C.COMMENT_THIS, command.getUsage().replaceAll("{label}", "plot")); } } return false; @@ -173,9 +174,9 @@ public class Rate extends SubCommand { sendMessage(player, C.RATING_NOT_VALID); return true; } - final String arg = args[0]; + String arg = args[0]; final int rating; - if (MathMan.isInteger(arg) && (arg.length() < 3) && (!arg.isEmpty())) { + if (MathMan.isInteger(arg) && (arg.length() < 3) && !arg.isEmpty()) { rating = Integer.parseInt(arg); if (rating > 10 || rating < 1) { sendMessage(player, C.RATING_NOT_VALID); @@ -193,8 +194,8 @@ public class Rate extends SubCommand { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; } - final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); - plot.addRating(uuid,result); + Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); + plot.addRating(uuid, result); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); } }; @@ -220,19 +221,19 @@ public class Rate extends SubCommand { private int value; MutableInt(int i) { - value = i; + this.value = i; } void increment() { - value++; + this.value++; } void decrement() { - value--; + this.value--; } int getValue() { - return value; + return this.value; } void add(Number v) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java index fc5aa27dd..87a6e2a92 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java @@ -20,8 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.Set; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.generator.HybridPlotManager; @@ -35,23 +33,25 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.Set; + @CommandDeclaration( -command = "regenallroads", -description = "Regenerate all roads in the map using the set road schematic", -aliases = { "rgar" }, -usage = "/plot regenallroads [height]", -category = CommandCategory.ADMINISTRATION, -requiredType = RequiredType.CONSOLE, -permission = "plots.regenallroads") + command = "regenallroads", + description = "Regenerate all roads in the map using the set road schematic", + aliases = {"rgar"}, + usage = "/plot regenallroads [height]", + category = CommandCategory.ADMINISTRATION, + requiredType = RequiredType.CONSOLE, + permission = "plots.regenallroads") public class RegenAllRoads extends SubCommand { - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { int height = 0; if (args.length == 2) { try { height = Integer.parseInt(args[1]); - } catch (final NumberFormatException e) { + } catch (NumberFormatException e) { MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(0, 256)"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); return false; @@ -65,18 +65,18 @@ public class RegenAllRoads extends SubCommand { C.NOT_VALID_PLOT_WORLD.send(plr, args[0]); return false; } - final String name = args[0]; - final PlotManager manager = area.getPlotManager(); + String name = args[0]; + PlotManager manager = area.getPlotManager(); if ((manager == null) || !(manager instanceof HybridPlotManager)) { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); return false; } - final Set chunks = ChunkManager.manager.getChunkChunks(name); + Set chunks = ChunkManager.manager.getChunkChunks(name); MainUtil.sendMessage(plr, "&cIf no schematic is set, the following will not do anything"); MainUtil.sendMessage(plr, "&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); MainUtil.sendMessage(plr, "&6Potential chunks to update: &7" + (chunks.size() * 1024)); - MainUtil.sendMessage(plr, "&6Estimated time: &7" + (chunks.size()) + " seconds"); - final boolean result = HybridUtils.manager.scheduleRoadUpdate(area, height); + MainUtil.sendMessage(plr, "&6Estimated time: &7" + chunks.size() + " seconds"); + boolean result = HybridUtils.manager.scheduleRoadUpdate(area, height); if (!result) { MainUtil.sendMessage(plr, "&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java index c8bdbe8ab..3e57bb76d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java @@ -30,17 +30,18 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.Objects; @CommandDeclaration(command = "reload", -permission = "plots.admin.command.reload", -description = "Reload configurations", -usage = "/plot reload", -category = CommandCategory.ADMINISTRATION) + permission = "plots.admin.command.reload", + description = "Reload configurations", + usage = "/plot reload", + category = CommandCategory.ADMINISTRATION) public class Reload extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { try { // The following won't affect world generation, as that has to be // loaded during startup unfortunately. @@ -51,12 +52,13 @@ public class Reload extends SubCommand { PS.get().foreachPlotArea(new RunnableVal() { @Override public void run(PlotArea area) { - final ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds." + area.worldname); + ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds." + area.worldname); if (area.TYPE != 2 || !worldSection.contains("areas")) { area.saveConfiguration(worldSection); area.loadDefaultConfiguration(worldSection); } else { - ConfigurationSection areaSection = worldSection.getConfigurationSection("areas." + area.id + "-" + area.getMin() + "-" + area.getMax()); + ConfigurationSection areaSection = + worldSection.getConfigurationSection("areas." + area.id + "-" + area.getMin() + "-" + area.getMax()); YamlConfiguration clone = new YamlConfiguration(); for (String key : areaSection.getKeys(true)) { if (areaSection.get(key) instanceof MemorySection) { @@ -95,7 +97,7 @@ public class Reload extends SubCommand { }); PS.get().config.save(PS.get().configFile); MainUtil.sendMessage(plr, C.RELOADED_CONFIGS); - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); MainUtil.sendMessage(plr, C.RELOAD_FAILED); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java index f29648600..8f1d09003 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java @@ -35,27 +35,27 @@ import java.util.HashSet; import java.util.UUID; @CommandDeclaration( -command = "remove", -aliases = { "r" }, -description = "Remove a player from a plot", -usage = "/plot remove ", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE, -permission = "plots.remove") + command = "remove", + aliases = {"r"}, + description = "Remove a player from a plot", + usage = "/plot remove ", + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE, + permission = "plots.remove") public class Remove extends SubCommand { - + public Remove() { - requiredArguments = new Argument[] { Argument.PlayerName }; + this.requiredArguments = new Argument[]{Argument.PlayerName}; } - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { if (args.length != 1) { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot remove "); return true; } - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } @@ -70,18 +70,18 @@ public class Remove extends SubCommand { int count = 0; switch (args[0]) { case "unknown": { - final ArrayList toRemove = new ArrayList<>(); - final HashSet all = new HashSet<>(); + ArrayList toRemove = new ArrayList<>(); + HashSet all = new HashSet<>(); all.addAll(plot.getMembers()); all.addAll(plot.getTrusted()); all.addAll(plot.getDenied()); - for (final UUID uuid : all) { + for (UUID uuid : all) { if (UUIDHandler.getName(uuid) == null) { toRemove.add(uuid); count++; } } - for (final UUID uuid : toRemove) { + for (UUID uuid : toRemove) { plot.removeDenied(uuid); plot.removeTrusted(uuid); plot.removeMember(uuid); @@ -89,16 +89,16 @@ public class Remove extends SubCommand { break; } case "*": { - final ArrayList toRemove = new ArrayList<>(); - final HashSet all = new HashSet<>(); + ArrayList toRemove = new ArrayList<>(); + HashSet all = new HashSet<>(); all.addAll(plot.getMembers()); all.addAll(plot.getTrusted()); all.addAll(plot.getDenied()); - for (final UUID uuid : all) { + for (UUID uuid : all) { toRemove.add(uuid); count++; } - for (final UUID uuid : toRemove) { + for (UUID uuid : toRemove) { plot.removeDenied(uuid); plot.removeTrusted(uuid); plot.removeMember(uuid); @@ -106,7 +106,7 @@ public class Remove extends SubCommand { break; } default: - final UUID uuid = UUIDHandler.getUUID(args[0], null); + UUID uuid = UUIDHandler.getUUID(args[0], null); if (uuid != null) { if (plot.getTrusted().contains(uuid)) { if (plot.removeTrusted(uuid)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java index dff31294b..9ea99c407 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java @@ -4,8 +4,8 @@ import com.plotsquared.general.commands.CommandCaller; public enum RequiredType { CONSOLE, PLAYER, NONE; - - public boolean allows(final CommandCaller player) { + + public boolean allows(CommandCaller player) { switch (this) { case NONE: return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java index 1f1bf2cba..e19619a2f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java @@ -14,26 +14,28 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.net.URL; import java.util.List; import java.util.UUID; @CommandDeclaration(command = "save", -aliases = { "backup" }, -description = "Save your plot", -category = CommandCategory.SCHEMATIC, -requiredType = RequiredType.NONE, -permission = "plots.save") + aliases = {"backup"}, + description = "Save your plot", + category = CommandCategory.SCHEMATIC, + requiredType = RequiredType.NONE, + permission = "plots.save") public class Save extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, String[] args) { if (!Settings.METRICS) { - MainUtil.sendMessage(plr, "&cPlease enable metrics in order to use this command.\n&7 - Or host it yourself if you don't like the free service"); + MainUtil.sendMessage(plr, + "&cPlease enable metrics in order to use this command.\n&7 - Or host it yourself if you don't like the free service"); return false; } - final String world = plr.getLocation().getWorld(); + String world = plr.getLocation().getWorld(); if (!PS.get().hasPlotArea(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } @@ -60,14 +62,14 @@ public class Save extends SubCommand { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - final String time = (System.currentTimeMillis() / 1000) + ""; - final String name = PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", ""); + String time = (System.currentTimeMillis() / 1000) + ""; + String name = PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", ""); Location[] corners = plot.getCorners(); - final int size = (corners[1].getX() - corners[0].getX()) + 1; - final PlotId id = plot.getId(); - final String world = plot.getArea().toString().replaceAll(";", "-").replaceAll("[^A-Za-z0-9]", ""); + int size = (corners[1].getX() - corners[0].getX()) + 1; + PlotId id = plot.getId(); + String world = plot.getArea().toString().replaceAll(";", "-").replaceAll("[^A-Za-z0-9]", ""); final String file = time + "_" + world + "_" + id.x + "_" + id.y + "_" + size + "_" + name; - final UUID uuid = plr.getUUID(); + UUID uuid = plr.getUUID(); SchematicHandler.manager.upload(value, uuid, file, new RunnableVal() { @Override public void run(URL url) { @@ -77,7 +79,7 @@ public class Save extends SubCommand { return; } MainUtil.sendMessage(plr, C.SAVE_SUCCESS); - final List schematics = plr.getMeta("plot_schematics"); + List schematics = plr.getMeta("plot_schematics"); if (schematics != null) { schematics.add(file); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java index ab99b66a4..d2fb04e54 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java @@ -35,28 +35,30 @@ import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; @CommandDeclaration( -command = "schematic", -permission = "plots.schematic", -description = "Schematic command", -aliases = { "sch" }, -category = CommandCategory.SCHEMATIC, -usage = "/plot schematic ") + command = "schematic", + permission = "plots.schematic", + description = "Schematic command", + aliases = {"sch"}, + category = CommandCategory.SCHEMATIC, + usage = "/plot schematic ") public class SchematicCmd extends SubCommand { + private boolean running = false; @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { + public boolean onCommand(final PlotPlayer plr, String... args) { if (args.length < 1) { sendMessage(plr, C.SCHEMATIC_MISSING_ARG); return true; } - final String arg = args[0].toLowerCase(); + String arg = args[0].toLowerCase(); switch (arg) { case "paste": { if (!Permissions.hasPermission(plr, "plots.schematic.paste")) { @@ -67,7 +69,7 @@ public class SchematicCmd extends SubCommand { sendMessage(plr, C.SCHEMATIC_MISSING_ARG); break; } - final Location loc = plr.getLocation(); + Location loc = plr.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); @@ -80,40 +82,40 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (running) { + if (this.running) { MainUtil.sendMessage(plr, "&cTask is already running."); return false; } final String location = args[1]; - running = true; + this.running = true; TaskManager.runTaskAsync(new Runnable() { @Override public void run() { Schematic schematic; if (location.startsWith("url:")) { try { - final UUID uuid = UUID.fromString(location.substring(4)); - final URL base = new URL(Settings.WEB_URL); - final URL url = new URL(base, "uploads/" + uuid + ".schematic"); + UUID uuid = UUID.fromString(location.substring(4)); + URL base = new URL(Settings.WEB_URL); + URL url = new URL(base, "uploads/" + uuid + ".schematic"); schematic = SchematicHandler.manager.getSchematic(url); - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent url: " + location); - running = false; + SchematicCmd.this.running = false; return; } } else { schematic = SchematicHandler.manager.getSchematic(location); } if (schematic == null) { - running = false; + SchematicCmd.this.running = false; sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); return; } SchematicHandler.manager.paste(schematic, plot, 0, 0, 0, true, new RunnableVal() { @Override public void run(Boolean value) { - running = false; + SchematicCmd.this.running = false; if (value) { sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); } else { @@ -125,38 +127,38 @@ public class SchematicCmd extends SubCommand { }); break; } -// TODO test -// case "test": { -// if (!Permissions.hasPermission(plr, "plots.schematic.test")) { -// MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.test"); -// return false; -// } -// if (args.length < 2) { -// sendMessage(plr, C.SCHEMATIC_MISSING_ARG); -// return false; -// } -// final Location loc = plr.getLocation(); -// final Plot plot = MainUtil.getPlot(loc); -// if (plot == null) { -// sendMessage(plr, C.NOT_IN_PLOT); -// return false; -// } -// file = args[1]; -// schematic = SchematicHandler.manager.getSchematic(file); -// if (schematic == null) { -// sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); -// return false; -// } -// final int l1 = schematic.getSchematicDimension().getX(); -// final int l2 = schematic.getSchematicDimension().getZ(); + // TODO test + // case "test": { + // if (!Permissions.hasPermission(plr, "plots.schematic.test")) { + // MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.test"); + // return false; + // } + // if (args.length < 2) { + // sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + // return false; + // } + // final Location loc = plr.getLocation(); + // final Plot plot = MainUtil.getPlot(loc); + // if (plot == null) { + // sendMessage(plr, C.NOT_IN_PLOT); + // return false; + // } + // file = args[1]; + // schematic = SchematicHandler.manager.getSchematic(file); + // if (schematic == null) { + // sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); + // return false; + // } + // final int l1 = schematic.getSchematicDimension().getX(); + // final int l2 = schematic.getSchematicDimension().getZ(); // final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.id); -// if ((l1 < length) || (l2 < length)) { -// sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); -// break; -// } -// sendMessage(plr, C.SCHEMATIC_VALID); -// break; -// } + // if ((l1 < length) || (l2 < length)) { + // sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); + // break; + // } + // sendMessage(plr, C.SCHEMATIC_VALID); + // break; + // } case "saveall": case "exportall": { if (!ConsolePlayer.isConsole(plr)) { @@ -172,12 +174,12 @@ public class SchematicCmd extends SubCommand { C.NOT_VALID_PLOT_WORLD.send(plr, args[1]); return false; } - final Collection plots = area.getPlots(); - if ((plots.isEmpty())) { + Collection plots = area.getPlots(); + if (plots.isEmpty()) { MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall "); return false; } - final boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { + boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { @Override public void run() { MainUtil.sendMessage(plr, "&aFinished mass export"); @@ -198,13 +200,13 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.save"); return false; } - if (running) { + if (this.running) { MainUtil.sendMessage(plr, "&cTask is already running."); return false; } - final Plot p2; - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + Plot p2; + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } @@ -218,13 +220,13 @@ public class SchematicCmd extends SubCommand { } p2 = plot; loc.getWorld(); - final Collection plots = new ArrayList(); + Collection plots = new ArrayList(); plots.add(p2); - final boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { + boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { @Override public void run() { MainUtil.sendMessage(plr, "&aFinished export"); - running = false; + SchematicCmd.this.running = false; } }); if (!result) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java index 3f8b28cb6..63c2d57e4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java @@ -20,10 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Configuration; import com.intellectualcrafters.plot.flag.AbstractFlag; @@ -42,23 +38,28 @@ import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; + @CommandDeclaration( -command = "set", -description = "Set a plot value", -aliases = { "s" }, -usage = "/plot set ", -permission = "plots.set", -category = CommandCategory.APPEARANCE, -requiredType = RequiredType.NONE) + command = "set", + description = "Set a plot value", + aliases = {"s"}, + usage = "/plot set ", + permission = "plots.set", + category = CommandCategory.APPEARANCE, + requiredType = RequiredType.NONE) public class Set extends SubCommand { - public final static String[] values = new String[] { "biome", "alias", "home", "flag" }; - public final static String[] aliases = new String[] { "b", "w", "wf", "f", "a", "h", "fl" }; - + + public final static String[] values = new String[]{"biome", "alias", "home", "flag"}; + public final static String[] aliases = new String[]{"b", "w", "wf", "f", "a", "h", "fl"}; + private final SetCommand component; public Set() { - component = new SetCommand() { - + this.component = new SetCommand() { + @Override public String getCommand() { return "set.component"; @@ -66,15 +67,15 @@ public class Set extends SubCommand { @Override public boolean set(PlotPlayer plr, final Plot plot, String value) { - final PlotArea plotworld = plr.getLocation().getPlotArea(); - final PlotManager manager = plr.getLocation().getPlotManager(); - final String[] components = manager.getPlotComponents(plotworld, plot.getId()); - final boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(plr.getUUID()); - + PlotArea plotworld = plr.getLocation().getPlotArea(); + PlotManager manager = plr.getLocation().getPlotManager(); + String[] components = manager.getPlotComponents(plotworld, plot.getId()); + boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(plr.getUUID()); + String[] args = value.split(" "); String material = StringMan.join(Arrays.copyOfRange(args, 1, args.length), ",").trim(); - for (final String component : components) { + for (String component : components) { if (component.equalsIgnoreCase(args[0])) { if (!Permissions.hasPermission(plr, "plots.set." + component)) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set." + component); @@ -86,10 +87,10 @@ public class Set extends SubCommand { MainUtil.sendMessage(plr, C.NEED_BLOCK); return true; } - final String[] split = material.split(","); + String[] split = material.split(","); blocks = Configuration.BLOCKLIST.parseString(material); for (int i = 0; i < blocks.length; i++) { - final PlotBlock block = blocks[i]; + PlotBlock block = blocks[i]; if (block == null) { MainUtil.sendMessage(plr, C.NOT_VALID_BLOCK, split[i]); String name; @@ -98,7 +99,7 @@ public class Set extends SubCommand { } else { name = split[i]; } - final StringComparison.ComparisonResult match = WorldUtil.IMP.getClosestBlock(name); + StringComparison.ComparisonResult match = WorldUtil.IMP.getClosestBlock(name); if (match != null) { name = WorldUtil.IMP.getClosestMatchingName(match.best); if (name != null) { @@ -112,14 +113,14 @@ public class Set extends SubCommand { } } if (!allowUnsafe) { - for (final PlotBlock block : blocks) { + for (PlotBlock block : blocks) { if (!WorldUtil.IMP.isBlockSolid(block)) { MainUtil.sendMessage(plr, C.NOT_ALLOWED_BLOCK, block.toString()); return false; } } } - } catch (final Exception e2) { + } catch (Exception e2) { MainUtil.sendMessage(plr, C.NOT_VALID_BLOCK, material); return false; } @@ -147,7 +148,7 @@ public class Set extends SubCommand { } public boolean noArgs(PlotPlayer plr) { - final ArrayList newValues = new ArrayList<>(); + ArrayList newValues = new ArrayList<>(); newValues.addAll(Arrays.asList("biome", "alias", "home", "flag")); Plot plot = plr.getCurrentPlot(); if (plot != null) { @@ -158,7 +159,7 @@ public class Set extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer plr, final String... args) { + public boolean onCommand(PlotPlayer plr, String... args) { if (args.length == 0) { return noArgs(plr); } @@ -175,18 +176,18 @@ public class Set extends SubCommand { // components HashSet components = new HashSet<>(Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); if (components.contains(args[0].toLowerCase())) { - return component.onCommand(plr, Arrays.copyOfRange(args, 0, args.length)); + return this.component.onCommand(plr, Arrays.copyOfRange(args, 0, args.length)); } // flag { AbstractFlag af; try { af = new AbstractFlag(args[0].toLowerCase()); - } catch (final Exception e) { + } catch (Exception e) { af = new AbstractFlag(""); } if (FlagManager.getFlags().contains(af)) { - final StringBuilder a = new StringBuilder(); + StringBuilder a = new StringBuilder(); if (args.length > 1) { for (int x = 1; x < args.length; x++) { a.append(" ").append(args[x]); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java index da57b123e..0734ccdb2 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java @@ -9,11 +9,11 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.StringMan; public abstract class SetCommand extends SubCommand { - + @Override public boolean onCommand(PlotPlayer plr, String[] args) { - final Location loc = plr.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location loc = plr.getLocation(); + Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } @@ -36,7 +36,7 @@ public abstract class SetCommand extends SubCommand { } return set(plr, plot, StringMan.join(args, " ")); } - + public abstract boolean set(PlotPlayer plr, Plot plot, String value); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java index 2469ac249..967217167 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java @@ -29,17 +29,17 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "sethome", -permission = "plots.set.home", -description = "Set the plot home", -usage = "/plot sethome [none]", -aliases = { "sh", "seth" }, -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) + command = "sethome", + permission = "plots.set.home", + description = "Set the plot home", + usage = "/plot sethome [none]", + aliases = {"sh", "seth"}, + category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class SetHome extends SetCommand { - + @Override - public boolean set(final PlotPlayer plr, final Plot plot, final String value) { + public boolean set(PlotPlayer plr, Plot plot, String value) { switch (value.toLowerCase()) { case "unset": case "remove": diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java index ba37ac891..68f258b61 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java @@ -40,18 +40,18 @@ import java.util.List; import java.util.Map.Entry; @CommandDeclaration( -command = "setup", -permission = "plots.admin.command.setup", -description = "Setup wizard for plot worlds", -usage = "/plot setup", -aliases = { "create" }, -category = CommandCategory.ADMINISTRATION) + command = "setup", + permission = "plots.admin.command.setup", + description = "Setup wizard for plot worlds", + usage = "/plot setup", + aliases = {"create"}, + category = CommandCategory.ADMINISTRATION) public class Setup extends SubCommand { - - public void displayGenerators(final PlotPlayer plr) { - final StringBuilder message = new StringBuilder(); + + public void displayGenerators(PlotPlayer plr) { + StringBuilder message = new StringBuilder(); message.append("&6What generator do you want?"); - for (final Entry> entry : SetupUtils.generators.entrySet()) { + for (Entry> entry : SetupUtils.generators.entrySet()) { if (entry.getKey().equals("PlotSquared")) { message.append("\n&8 - &2").append(entry.getKey()).append(" (Default Generator)"); } else if (entry.getValue().isFull()) { @@ -62,9 +62,9 @@ public class Setup extends SubCommand { } MainUtil.sendMessage(plr, message.toString()); } - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(PlotPlayer plr, String[] args) { // going through setup SetupObject object = plr.getMeta("setup"); if (object == null) { @@ -84,34 +84,37 @@ public class Setup extends SubCommand { if (args[0].equalsIgnoreCase("back")) { if (object.setup_index > 0) { object.setup_index--; - final ConfigurationNode node = object.step[object.setup_index]; - sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", node.getDescription(), node.getType().getType(), node.getDefaultValue() + ""); + ConfigurationNode node = object.step[object.setup_index]; + sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", node.getDescription(), node.getType().getType(), + node.getDefaultValue() + ""); return false; } else if (object.current > 0) { object.current--; } } } - final int index = object.current; + int index = object.current; switch (index) { case 0: { // choose generator if ((args.length != 1) || !SetupUtils.generators.containsKey(args[0])) { - final String prefix = "\n&8 - &7"; - MainUtil.sendMessage(plr, "&cYou must choose a generator!" + prefix + StringMan.join(SetupUtils.generators.keySet(), prefix).replaceAll("PlotSquared", "&2PlotSquared")); + String prefix = "\n&8 - &7"; + MainUtil.sendMessage(plr, "&cYou must choose a generator!" + prefix + StringMan.join(SetupUtils.generators.keySet(), prefix) + .replaceAll("PlotSquared", "&2PlotSquared")); sendMessage(plr, C.SETUP_INIT); return false; } object.setupGenerator = args[0]; object.current++; - final String partial = "\n&8 - &7PARTIAL&8 - &7Vanilla with clusters of plots"; - MainUtil.sendMessage(plr, "&6What world type do you want?" + "\n&8 - &2DEFAULT&8 - &7Standard plot generation" + "\n&8 - &7AUGMENTED&8 - &7Plot generation with terrain" + partial); + String partial = "\n&8 - &7PARTIAL&8 - &7Vanilla with clusters of plots"; + MainUtil.sendMessage(plr, "&6What world type do you want?" + "\n&8 - &2DEFAULT&8 - &7Standard plot generation" + + "\n&8 - &7AUGMENTED&8 - &7Plot generation with terrain" + partial); break; } case 1: { // choose world type - final List allTypes = Arrays.asList("default", "augmented", "partial"); - final List allDesc = Arrays.asList("Standard plot generation", "Plot generation with vanilla terrain", + List allTypes = Arrays.asList("default", "augmented", "partial"); + List allDesc = Arrays.asList("Standard plot generation", "Plot generation with vanilla terrain", "Vanilla with clusters of plots"); - final ArrayList types = new ArrayList<>(); + ArrayList types = new ArrayList<>(); if (SetupUtils.generators.get(object.setupGenerator).isFull()) { types.add("default"); } @@ -119,8 +122,8 @@ public class Setup extends SubCommand { types.add("partial"); if ((args.length != 1) || !types.contains(args[0].toLowerCase())) { MainUtil.sendMessage(plr, "&cYou must choose a world type!"); - for (final String type : types) { - final int i = allTypes.indexOf(type); + for (String type : types) { + int i = allTypes.indexOf(type); if (type.equals("default")) { MainUtil.sendMessage(plr, "&8 - &2" + type + " &8-&7 " + allDesc.get(i)); } else { @@ -130,12 +133,13 @@ public class Setup extends SubCommand { return false; } object.type = allTypes.indexOf(args[0].toLowerCase()); - final GeneratorWrapper gen = SetupUtils.generators.get(object.setupGenerator); + GeneratorWrapper gen = SetupUtils.generators.get(object.setupGenerator); if (object.type == 0) { object.current = 6; if (object.step == null) { object.plotManager = object.setupGenerator; - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator().getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); SetupUtils.generators.get(object.plotManager).getPlotGenerator().processSetup(object); } if (object.step.length == 0) { @@ -143,29 +147,32 @@ public class Setup extends SubCommand { object.setup_index = 0; return true; } - final ConfigurationNode step = object.step[object.setup_index]; - sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + ConfigurationNode step = object.step[object.setup_index]; + sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), + step.getDefaultValue() + ""); } else { if (gen.isFull()) { object.plotManager = object.setupGenerator; object.setupGenerator = null; - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator().getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); SetupUtils.generators.get(object.plotManager).getPlotGenerator().processSetup(object); } else { object.plotManager = "PlotSquared"; MainUtil.sendMessage(plr, "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); MainUtil.sendMessage(plr, "&7 - You may need to manually configure the other plugin"); - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator().getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); } if (object.type == 2) { MainUtil.sendMessage(plr, "What would you like this area called?"); object.current++; } else { MainUtil.sendMessage(plr, "&6What terrain would you like in plots?" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); object.current = 5; } } @@ -211,29 +218,31 @@ public class Setup extends SubCommand { object.max = id; object.current++; MainUtil.sendMessage(plr, "&6What terrain would you like in plots?" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); break; } case 5: { // Choose terrain - final List terrain = Arrays.asList("none", "ore", "road", "all"); + List terrain = Arrays.asList("none", "ore", "road", "all"); if ((args.length != 1) || !terrain.contains(args[0].toLowerCase())) { MainUtil.sendMessage(plr, "&cYou must choose the terrain!" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); return false; } object.terrain = terrain.indexOf(args[0].toLowerCase()); object.current++; if (object.step == null) { - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator().getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); } - final ConfigurationNode step = object.step[object.setup_index]; - sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + ConfigurationNode step = object.step[object.setup_index]; + sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), + step.getDefaultValue() + ""); break; } case 6: { // world setup @@ -245,10 +254,11 @@ public class Setup extends SubCommand { } ConfigurationNode step = object.step[object.setup_index]; if (args.length < 1) { - sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), + step.getDefaultValue() + ""); return false; } - final boolean valid = step.isValid(args[0]); + boolean valid = step.isValid(args[0]); if (valid) { sendMessage(plr, C.SETUP_VALID_ARG, step.getConstant(), args[0]); step.setValue(args[0]); @@ -258,11 +268,13 @@ public class Setup extends SubCommand { return false; } step = object.step[object.setup_index]; - sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), + step.getDefaultValue() + ""); return false; } else { sendMessage(plr, C.SETUP_INVALID_ARG, args[0], step.getConstant()); - sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), + step.getDefaultValue() + ""); return false; } } @@ -277,11 +289,12 @@ public class Setup extends SubCommand { return false; } MainUtil.sendMessage(plr, - "&cThe world you specified already exists. After restarting, new terrain will use PlotSquared, however you may need to reset the world for it to generate correctly!"); + "&cThe world you specified already exists. After restarting, new terrain will use PlotSquared, however you may need to " + + "reset the world for it to generate correctly!"); } object.world = args[0]; plr.deleteMeta("setup"); - final String world; + String world; if (object.setupManager == null) { world = SetupUtils.manager.setupWorld(object); } else { @@ -289,7 +302,7 @@ public class Setup extends SubCommand { } try { plr.teleport(WorldUtil.IMP.getSpawn(world)); - } catch (final Exception e) { + } catch (Exception e) { plr.sendMessage("&cAn error occurred. See console for more information"); e.printStackTrace(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java index ef797fbf9..b6af61849 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java @@ -34,12 +34,12 @@ import java.util.List; */ public abstract class SubCommand extends com.plotsquared.general.commands.Command { - + /** * The category */ public CommandCategory category; - + /** * Send a message * @@ -49,17 +49,18 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman * * @see MainUtil#sendMessage(PlotPlayer, C, String...) */ - public boolean sendMessage(final PlotPlayer plr, final C c, final String... args) { + public boolean sendMessage(PlotPlayer plr, C c, String... args) { c.send(plr, args); return true; } - - public void paginate(PlotPlayer player, List c, int size, int page, RunnableVal3 add, String baseCommand, String header) { + + public void paginate(PlotPlayer player, List c, int size, int page, RunnableVal3 add, String baseCommand, + String header) { // Calculate pages & index if (page < 0) { page = 0; } - final int totalPages = (int) Math.ceil(c.size() / size); + int totalPages = (int) Math.ceil(c.size() / size); if (page > totalPages) { page = totalPages; } @@ -68,12 +69,13 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman max = c.size(); } // Send the header - header = header.replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%amount%", c.size() + "").replaceAll("%word%", "all"); + header = header.replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%amount%", c.size() + "") + .replaceAll("%word%", "all"); MainUtil.sendMessage(player, header); // Send the page content - final List subList = c.subList(page * size, max); + List subList = c.subList(page * size, max); int i = page * size; - for (final T obj : subList) { + for (T obj : subList) { i++; PlotMessage msg = new PlotMessage(); add.run(i, obj, msg); @@ -83,11 +85,12 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman if (page < totalPages && page > 0) { // Back | Next new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$1") .command(baseCommand + " " + (page + 2)) - .text(C.CLICKABLE.s()).color("$2").send(player); + .text(C.CLICKABLE.s()).color("$2").send(player); return; } if (page == 0 && totalPages != 0) { // Next - new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)).text(C.CLICKABLE.s()).color("$2").send(player); + new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)) + .text(C.CLICKABLE.s()).color("$2").send(player); return; } if (page == totalPages && totalPages != 0) { // Back diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java index e96620962..dce024944 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java @@ -29,17 +29,17 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration(usage = "/plot swap ", -command = "swap", -description = "Swap two plots", -aliases = { "switch" }, -category = CommandCategory.CLAIMING, -requiredType = RequiredType.NONE) + command = "swap", + description = "Swap two plots", + aliases = {"switch"}, + category = CommandCategory.CLAIMING, + requiredType = RequiredType.NONE) public class Swap extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location loc = plr.getLocation(); - final Plot plot1 = loc.getPlotAbs(); + public boolean onCommand(final PlotPlayer plr, String[] args) { + Location loc = plr.getLocation(); + Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); } @@ -51,8 +51,8 @@ public class Swap extends SubCommand { C.COMMAND_SYNTAX.send(plr, getUsage()); return false; } - final Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true); - if ((plot2 == null)) { + Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true); + if (plot2 == null) { return false; } if (plot1.equals(plot2)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java index 575ebc601..4a31cc5e6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java @@ -30,17 +30,17 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( -command = "target", -usage = "/plot target <|nearest>", -description = "Target a plot with your compass", -permission = "plots.target", -requiredType = RequiredType.NONE, -category = CommandCategory.INFO) + command = "target", + usage = "/plot target <|nearest>", + description = "Target a plot with your compass", + permission = "plots.target", + requiredType = RequiredType.NONE, + category = CommandCategory.INFO) public class Target extends SubCommand { @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - final Location ploc = plr.getLocation(); + public boolean onCommand(PlotPlayer plr, String[] args) { + Location ploc = plr.getLocation(); if (!ploc.isPlotArea()) { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; @@ -48,8 +48,8 @@ public class Target extends SubCommand { Plot target = null; if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) { int distance = Integer.MAX_VALUE; - for (final Plot plot : PS.get().getPlots(ploc.getWorld())) { - final double current = plot.getCenter().getEuclideanDistanceSquared(ploc); + for (Plot plot : PS.get().getPlots(ploc.getWorld())) { + double current = plot.getCenter().getEuclideanDistanceSquared(ploc); if (current < distance) { distance = (int) current; target = plot; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java index 9c2e3f9bb..618441f38 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java @@ -48,30 +48,30 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; @CommandDeclaration( -command = "template", -permission = "plots.admin", -description = "Create or use a world template", -usage = "/plot template [import|export]