diff --git a/.gitignore b/.gitignore index 90dc65d43..1e4e21fc2 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ /target/PlotSquared-Uber.jar /target/maven-archiver *.project -*.classpath \ No newline at end of file +*.classpath +/target/ diff --git a/src/main/java/com/intellectualcrafters/configuration/Configuration.java b/src/main/java/com/intellectualcrafters/configuration/Configuration.java index a912b5323..58e826d78 100644 --- a/src/main/java/com/intellectualcrafters/configuration/Configuration.java +++ b/src/main/java/com/intellectualcrafters/configuration/Configuration.java @@ -5,7 +5,8 @@ import java.util.Map; /** * Represents a source of configurable options and settings */ -public interface Configuration extends ConfigurationSection { +public interface Configuration extends ConfigurationSection +{ /** * Sets the default value of the given path as provided. *

@@ -20,7 +21,8 @@ public interface Configuration extends ConfigurationSection { * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ - public void addDefault(String path, Object value); + @Override + public void addDefault(final String path, final Object value); /** * Sets the default values of the given paths as provided. @@ -32,7 +34,7 @@ public interface Configuration extends ConfigurationSection { * @param defaults A map of Path->Values to add to defaults. * @throws IllegalArgumentException Thrown if defaults is null. */ - public void addDefaults(Map defaults); + public void addDefaults(final Map defaults); /** * Sets the default values of the given paths as provided. @@ -49,7 +51,7 @@ public interface Configuration extends ConfigurationSection { * @param defaults A configuration holding a list of defaults to copy. * @throws IllegalArgumentException Thrown if defaults is null or this. */ - public void addDefaults(Configuration defaults); + public void addDefaults(final Configuration defaults); /** * Sets the source of all default values for this {@link Configuration}. @@ -60,7 +62,7 @@ public interface Configuration extends ConfigurationSection { * @param defaults New source of default values for this configuration. * @throws IllegalArgumentException Thrown if defaults is null or this. */ - public void setDefaults(Configuration defaults); + public void setDefaults(final Configuration defaults); /** * Gets the source {@link Configuration} for this configuration. diff --git a/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java index 4f32c6545..3768af587 100644 --- a/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java +++ b/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java @@ -4,12 +4,14 @@ package com.intellectualcrafters.configuration; * Various settings for controlling the input and output of a {@link * Configuration} */ -public class ConfigurationOptions { +public class ConfigurationOptions +{ private char pathSeparator = '.'; private boolean copyDefaults = false; private final Configuration configuration; - protected ConfigurationOptions(Configuration configuration) { + protected ConfigurationOptions(final Configuration configuration) + { this.configuration = configuration; } @@ -18,7 +20,8 @@ public class ConfigurationOptions { * * @return Parent configuration */ - public Configuration configuration() { + public Configuration configuration() + { return configuration; } @@ -31,7 +34,8 @@ public class ConfigurationOptions { * * @return Path separator */ - public char pathSeparator() { + public char pathSeparator() + { return pathSeparator; } @@ -45,8 +49,9 @@ public class ConfigurationOptions { * @param value Path separator * @return This object, for chaining */ - public ConfigurationOptions pathSeparator(char value) { - this.pathSeparator = value; + public ConfigurationOptions pathSeparator(final char value) + { + pathSeparator = value; return this; } @@ -64,7 +69,8 @@ public class ConfigurationOptions { * * @return Whether or not defaults are directly copied */ - public boolean copyDefaults() { + public boolean copyDefaults() + { return copyDefaults; } @@ -83,8 +89,9 @@ public class ConfigurationOptions { * @param value Whether or not defaults are directly copied * @return This object, for chaining */ - public ConfigurationOptions copyDefaults(boolean value) { - this.copyDefaults = value; + public ConfigurationOptions copyDefaults(final boolean value) + { + copyDefaults = value; return this; } } diff --git a/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java b/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java index 9e368b566..d2f3dbd1b 100644 --- a/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java +++ b/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java @@ -7,7 +7,8 @@ import java.util.Set; /** * Represents a section of a {@link Configuration} */ -public interface ConfigurationSection { +public interface ConfigurationSection +{ /** * Gets a set containing all keys in this section. *

@@ -22,7 +23,7 @@ public interface ConfigurationSection { * list. * @return Set of keys contained within this ConfigurationSection. */ - public Set getKeys(boolean deep); + public Set getKeys(final boolean deep); /** * Gets a Map containing all keys and their values for this section. @@ -38,7 +39,7 @@ public interface ConfigurationSection { * list. * @return Map of keys and values of this section. */ - public Map getValues(boolean deep); + public Map getValues(final boolean deep); /** * Checks if this {@link ConfigurationSection} contains the given path. @@ -51,7 +52,7 @@ public interface ConfigurationSection { * default or being set. * @throws IllegalArgumentException Thrown when path is null. */ - public boolean contains(String path); + public boolean contains(final String path); /** * Checks if this {@link ConfigurationSection} has a value set for the @@ -65,7 +66,7 @@ public interface ConfigurationSection { * having a default. * @throws IllegalArgumentException Thrown when path is null. */ - public boolean isSet(String path); + public boolean isSet(final String path); /** * Gets the path of this {@link ConfigurationSection} from its root {@link @@ -132,7 +133,7 @@ public interface ConfigurationSection { * @param path Path of the Object to get. * @return Requested Object. */ - public Object get(String path); + public Object get(final String path); /** * Gets the requested Object by path, returning a default value if not @@ -146,7 +147,7 @@ public interface ConfigurationSection { * @param def The default value to return if the path is not found. * @return Requested Object. */ - public Object get(String path, Object def); + public Object get(final String path, final Object def); /** * Sets the specified path to the given value. @@ -162,7 +163,7 @@ public interface ConfigurationSection { * @param path Path of the object to set. * @param value New value to set the path to. */ - public void set(String path, Object value); + public void set(final String path, final Object value); /** * Creates an empty {@link ConfigurationSection} at the specified path. @@ -174,7 +175,7 @@ public interface ConfigurationSection { * @param path Path to create the section at. * @return Newly created section */ - public ConfigurationSection createSection(String path); + public ConfigurationSection createSection(final String path); /** * Creates a {@link ConfigurationSection} at the specified path, with @@ -188,7 +189,7 @@ public interface ConfigurationSection { * @param map The values to used. * @return Newly created section */ - public ConfigurationSection createSection(String path, Map map); + public ConfigurationSection createSection(final String path, final Map map); // Primitives /** @@ -201,7 +202,7 @@ public interface ConfigurationSection { * @param path Path of the String to get. * @return Requested String. */ - public String getString(String path); + public String getString(final String path); /** * Gets the requested String by path, returning a default value if not @@ -216,7 +217,7 @@ public interface ConfigurationSection { * not a String. * @return Requested String. */ - public String getString(String path, String def); + public String getString(final String path, final String def); /** * Checks if the specified path is a String. @@ -229,7 +230,7 @@ public interface ConfigurationSection { * @param path Path of the String to check. * @return Whether or not the specified path is a String. */ - public boolean isString(String path); + public boolean isString(final String path); /** * Gets the requested int by path. @@ -241,7 +242,7 @@ public interface ConfigurationSection { * @param path Path of the int to get. * @return Requested int. */ - public int getInt(String path); + public int getInt(final String path); /** * Gets the requested int by path, returning a default value if not found. @@ -255,7 +256,7 @@ public interface ConfigurationSection { * not an int. * @return Requested int. */ - public int getInt(String path, int def); + public int getInt(final String path, final int def); /** * Checks if the specified path is an int. @@ -268,7 +269,7 @@ public interface ConfigurationSection { * @param path Path of the int to check. * @return Whether or not the specified path is an int. */ - public boolean isInt(String path); + public boolean isInt(final String path); /** * Gets the requested boolean by path. @@ -280,7 +281,7 @@ public interface ConfigurationSection { * @param path Path of the boolean to get. * @return Requested boolean. */ - public boolean getBoolean(String path); + public boolean getBoolean(final String path); /** * Gets the requested boolean by path, returning a default value if not @@ -295,7 +296,7 @@ public interface ConfigurationSection { * not a boolean. * @return Requested boolean. */ - public boolean getBoolean(String path, boolean def); + public boolean getBoolean(final String path, final boolean def); /** * Checks if the specified path is a boolean. @@ -308,7 +309,7 @@ public interface ConfigurationSection { * @param path Path of the boolean to check. * @return Whether or not the specified path is a boolean. */ - public boolean isBoolean(String path); + public boolean isBoolean(final String path); /** * Gets the requested double by path. @@ -320,7 +321,7 @@ public interface ConfigurationSection { * @param path Path of the double to get. * @return Requested double. */ - public double getDouble(String path); + public double getDouble(final String path); /** * Gets the requested double by path, returning a default value if not @@ -335,7 +336,7 @@ public interface ConfigurationSection { * not a double. * @return Requested double. */ - public double getDouble(String path, double def); + public double getDouble(final String path, final double def); /** * Checks if the specified path is a double. @@ -348,7 +349,7 @@ public interface ConfigurationSection { * @param path Path of the double to check. * @return Whether or not the specified path is a double. */ - public boolean isDouble(String path); + public boolean isDouble(final String path); /** * Gets the requested long by path. @@ -360,7 +361,7 @@ public interface ConfigurationSection { * @param path Path of the long to get. * @return Requested long. */ - public long getLong(String path); + public long getLong(final String path); /** * Gets the requested long by path, returning a default value if not @@ -375,7 +376,7 @@ public interface ConfigurationSection { * not a long. * @return Requested long. */ - public long getLong(String path, long def); + public long getLong(final String path, final long def); /** * Checks if the specified path is a long. @@ -388,7 +389,7 @@ public interface ConfigurationSection { * @param path Path of the long to check. * @return Whether or not the specified path is a long. */ - public boolean isLong(String path); + public boolean isLong(final String path); // Java /** @@ -401,7 +402,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List. */ - public List getList(String path); + public List getList(final String path); /** * Gets the requested List by path, returning a default value if not @@ -416,7 +417,7 @@ public interface ConfigurationSection { * not a List. * @return Requested List. */ - public List getList(String path, List def); + public List getList(final String path, final List def); /** * Checks if the specified path is a List. @@ -429,7 +430,7 @@ public interface ConfigurationSection { * @param path Path of the List to check. * @return Whether or not the specified path is a List. */ - public boolean isList(String path); + public boolean isList(final String path); /** * Gets the requested List of String by path. @@ -444,7 +445,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of String. */ - public List getStringList(String path); + public List getStringList(final String path); /** * Gets the requested List of Integer by path. @@ -459,7 +460,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Integer. */ - public List getIntegerList(String path); + public List getIntegerList(final String path); /** * Gets the requested List of Boolean by path. @@ -474,7 +475,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Boolean. */ - public List getBooleanList(String path); + public List getBooleanList(final String path); /** * Gets the requested List of Double by path. @@ -489,7 +490,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Double. */ - public List getDoubleList(String path); + public List getDoubleList(final String path); /** * Gets the requested List of Float by path. @@ -504,7 +505,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Float. */ - public List getFloatList(String path); + public List getFloatList(final String path); /** * Gets the requested List of Long by path. @@ -519,7 +520,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Long. */ - public List getLongList(String path); + public List getLongList(final String path); /** * Gets the requested List of Byte by path. @@ -534,7 +535,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Byte. */ - public List getByteList(String path); + public List getByteList(final String path); /** * Gets the requested List of Character by path. @@ -549,7 +550,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Character. */ - public List getCharacterList(String path); + public List getCharacterList(final String path); /** * Gets the requested List of Short by path. @@ -564,7 +565,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Short. */ - public List getShortList(String path); + public List getShortList(final String path); /** * Gets the requested List of Maps by path. @@ -579,7 +580,7 @@ public interface ConfigurationSection { * @param path Path of the List to get. * @return Requested List of Maps. */ - public List> getMapList(String path); + public List> getMapList(final String path); /** * Gets the requested ConfigurationSection by path. @@ -592,7 +593,7 @@ public interface ConfigurationSection { * @param path Path of the ConfigurationSection to get. * @return Requested ConfigurationSection. */ - public ConfigurationSection getConfigurationSection(String path); + public ConfigurationSection getConfigurationSection(final String path); /** * Checks if the specified path is a ConfigurationSection. @@ -606,7 +607,7 @@ public interface ConfigurationSection { * @param path Path of the ConfigurationSection to check. * @return Whether or not the specified path is a ConfigurationSection. */ - public boolean isConfigurationSection(String path); + public boolean isConfigurationSection(final String path); /** * Gets the equivalent {@link ConfigurationSection} from the default @@ -638,5 +639,5 @@ public interface ConfigurationSection { * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ - public void addDefault(String path, Object value); + public void addDefault(final String path, final Object value); } diff --git a/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java b/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java index 38e9b0cb3..c7769dd7d 100644 --- a/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java +++ b/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java @@ -4,13 +4,15 @@ package com.intellectualcrafters.configuration; * Exception thrown when attempting to load an invalid {@link Configuration} */ @SuppressWarnings("serial") -public class InvalidConfigurationException extends Exception { +public class InvalidConfigurationException extends Exception +{ /** * Creates a new instance of InvalidConfigurationException without a * message or cause. */ - public InvalidConfigurationException() {} + public InvalidConfigurationException() + {} /** * Constructs an instance of InvalidConfigurationException with the @@ -18,7 +20,8 @@ public class InvalidConfigurationException extends Exception { * * @param msg The details of the exception. */ - public InvalidConfigurationException(String msg) { + public InvalidConfigurationException(final String msg) + { super(msg); } @@ -28,7 +31,8 @@ public class InvalidConfigurationException extends Exception { * * @param cause The cause of the exception. */ - public InvalidConfigurationException(Throwable cause) { + public InvalidConfigurationException(final Throwable cause) + { super(cause); } @@ -39,7 +43,8 @@ public class InvalidConfigurationException extends Exception { * @param cause The cause of the exception. * @param msg The details of the exception. */ - public InvalidConfigurationException(String msg, Throwable cause) { + public InvalidConfigurationException(final String msg, final Throwable cause) + { super(msg, cause); } } diff --git a/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java index ad81ab8f8..5448f837a 100644 --- a/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java +++ b/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java @@ -7,14 +7,16 @@ import java.util.Map; * from any source, and stores all values in memory only. * This is useful for temporary Configurations for providing defaults. */ -public class MemoryConfiguration extends MemorySection implements Configuration { +public class MemoryConfiguration extends MemorySection implements Configuration +{ protected Configuration defaults; protected MemoryConfigurationOptions options; /** * Creates an empty {@link MemoryConfiguration} with no default values. */ - public MemoryConfiguration() {} + public MemoryConfiguration() + {} /** * Creates an empty {@link MemoryConfiguration} using the specified {@link @@ -23,51 +25,67 @@ public class MemoryConfiguration extends MemorySection implements Configuration * @param defaults Default value provider * @throws IllegalArgumentException Thrown if defaults is null */ - public MemoryConfiguration(Configuration defaults) { + public MemoryConfiguration(final Configuration defaults) + { this.defaults = defaults; } @Override - public void addDefault(String path, Object value) { - if (path == null) throw new NullPointerException("Path may not be null"); - if (defaults == null) { + public void addDefault(final String path, final Object value) + { + if (path == null) { throw new NullPointerException("Path may not be null"); } + if (defaults == null) + { defaults = new MemoryConfiguration(); } defaults.set(path, value); } - public void addDefaults(Map defaults) { - if (defaults == null) throw new NullPointerException("Defaults may not be null"); + @Override + public void addDefaults(final Map defaults) + { + if (defaults == null) { throw new NullPointerException("Defaults may not be null"); } - for (Map.Entry entry : defaults.entrySet()) { + for (final Map.Entry entry : defaults.entrySet()) + { addDefault(entry.getKey(), entry.getValue()); } } - public void addDefaults(Configuration defaults) { - if (defaults == null) throw new NullPointerException("Defaults may not be null"); + @Override + public void addDefaults(final Configuration defaults) + { + if (defaults == null) { throw new NullPointerException("Defaults may not be null"); } addDefaults(defaults.getValues(true)); } - public void setDefaults(Configuration defaults) { - if (defaults == null) throw new NullPointerException("Defaults may not be null"); + @Override + public void setDefaults(final Configuration defaults) + { + if (defaults == null) { throw new NullPointerException("Defaults may not be null"); } this.defaults = defaults; } - public Configuration getDefaults() { + @Override + public Configuration getDefaults() + { return defaults; } @Override - public ConfigurationSection getParent() { + public ConfigurationSection getParent() + { return null; } - public MemoryConfigurationOptions options() { - if (options == null) { + @Override + public MemoryConfigurationOptions options() + { + if (options == null) + { options = new MemoryConfigurationOptions(this); } diff --git a/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java index 1720118c6..4e6af36c2 100644 --- a/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java +++ b/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java @@ -4,24 +4,29 @@ package com.intellectualcrafters.configuration; * Various settings for controlling the input and output of a {@link * MemoryConfiguration} */ -public class MemoryConfigurationOptions extends ConfigurationOptions { - protected MemoryConfigurationOptions(MemoryConfiguration configuration) { +public class MemoryConfigurationOptions extends ConfigurationOptions +{ + protected MemoryConfigurationOptions(final MemoryConfiguration configuration) + { super(configuration); } @Override - public MemoryConfiguration configuration() { + public MemoryConfiguration configuration() + { return (MemoryConfiguration) super.configuration(); } @Override - public MemoryConfigurationOptions copyDefaults(boolean value) { + public MemoryConfigurationOptions copyDefaults(final boolean value) + { super.copyDefaults(value); return this; } @Override - public MemoryConfigurationOptions pathSeparator(char value) { + public MemoryConfigurationOptions pathSeparator(final char value) + { super.pathSeparator(value); return this; } diff --git a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/src/main/java/com/intellectualcrafters/configuration/MemorySection.java index 2c3bc0f4c..042e9efe4 100644 --- a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java +++ b/src/main/java/com/intellectualcrafters/configuration/MemorySection.java @@ -10,70 +10,74 @@ import java.util.Set; /** * A type of {@link ConfigurationSection} that is stored in memory. */ -public class MemorySection implements ConfigurationSection { +public class MemorySection implements ConfigurationSection +{ protected final Map map = new LinkedHashMap(); private final Configuration root; private final ConfigurationSection parent; private final String path; private final String fullPath; - public static double toDouble(Object obj, double def) { - if (obj instanceof Number) { - return ((Number) obj).doubleValue(); - } - if (obj instanceof String) { - try { + public static double toDouble(final Object obj, final double def) + { + if (obj instanceof Number) { return ((Number) obj).doubleValue(); } + if (obj instanceof String) + { + try + { return Double.parseDouble((String) obj); } - catch (Exception e) {} + catch (final Exception e) + {} } - else if (obj instanceof List) { - List val = ((List) obj); - if (val.size() > 0) { - return toDouble(val.get(0), def); - } + else if (obj instanceof List) + { + final List val = ((List) obj); + if (val.size() > 0) { return toDouble(val.get(0), def); } } return def; } - - public static int toInt(Object obj, int def) { - if (obj instanceof Number) { - return ((Number) obj).intValue(); - } - if (obj instanceof String) { - try { + + public static int toInt(final Object obj, final int def) + { + if (obj instanceof Number) { return ((Number) obj).intValue(); } + if (obj instanceof String) + { + try + { return Integer.parseInt((String) obj); } - catch (Exception e) {} + catch (final Exception e) + {} } - else if (obj instanceof List) { - List val = ((List) obj); - if (val.size() > 0) { - return toInt(val.get(0), def); - } + else if (obj instanceof List) + { + final List val = ((List) obj); + if (val.size() > 0) { return toInt(val.get(0), def); } } return def; } - - public static long toLong(Object obj, long def) { - if (obj instanceof Number) { - return ((Number) obj).longValue(); - } - if (obj instanceof String) { - try { + + public static long toLong(final Object obj, final long def) + { + if (obj instanceof Number) { return ((Number) obj).longValue(); } + if (obj instanceof String) + { + try + { return Long.parseLong((String) obj); } - catch (Exception e) {} + catch (final Exception e) + {} } - else if (obj instanceof List) { - List val = ((List) obj); - if (val.size() > 0) { - return toLong(val.get(0), def); - } + else if (obj instanceof List) + { + final List val = ((List) obj); + if (val.size() > 0) { return toLong(val.get(0), def); } } return def; } - + /** * Creates an empty MemorySection for use as a root {@link Configuration} * section. @@ -84,15 +88,14 @@ public class MemorySection implements ConfigurationSection { * @throws IllegalStateException Thrown if this is not a {@link * Configuration} root. */ - protected MemorySection() { - if (!(this instanceof Configuration)) { - throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); - } + protected MemorySection() + { + if (!(this instanceof Configuration)) { throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); } - this.path = ""; - this.fullPath = ""; - this.parent = null; - this.root = (Configuration) this; + path = ""; + fullPath = ""; + parent = null; + root = (Configuration) this; } /** @@ -104,27 +107,32 @@ public class MemorySection implements ConfigurationSection { * @throws IllegalArgumentException Thrown is parent or path is null, or * if parent contains no root Configuration. */ - protected MemorySection(ConfigurationSection parent, String path) { - if (parent == null) throw new NullPointerException("Parent may not be null"); - if (path == null) throw new NullPointerException("Path may not be null"); + protected MemorySection(final ConfigurationSection parent, final String path) + { + if (parent == null) { throw new NullPointerException("Parent may not be null"); } + if (path == null) { throw new NullPointerException("Path may not be null"); } this.path = path; this.parent = parent; - this.root = parent.getRoot(); + root = parent.getRoot(); - if (root == null) throw new NullPointerException("Path may not be orphaned"); + if (root == null) { throw new NullPointerException("Path may not be orphaned"); } - this.fullPath = createPath(parent, path); + fullPath = createPath(parent, path); } - public Set getKeys(boolean deep) { - Set result = new LinkedHashSet(); + @Override + public Set getKeys(final boolean deep) + { + final Set result = new LinkedHashSet(); - Configuration root = getRoot(); - if (root != null && root.options().copyDefaults()) { - ConfigurationSection defaults = getDefaultSection(); + final Configuration root = getRoot(); + if ((root != null) && root.options().copyDefaults()) + { + final ConfigurationSection defaults = getDefaultSection(); - if (defaults != null) { + if (defaults != null) + { result.addAll(defaults.getKeys(deep)); } } @@ -134,14 +142,18 @@ public class MemorySection implements ConfigurationSection { return result; } - public Map getValues(boolean deep) { - Map result = new LinkedHashMap(); + @Override + public Map getValues(final boolean deep) + { + final Map result = new LinkedHashMap(); - Configuration root = getRoot(); - if (root != null && root.options().copyDefaults()) { - ConfigurationSection defaults = getDefaultSection(); + final Configuration root = getRoot(); + if ((root != null) && root.options().copyDefaults()) + { + final ConfigurationSection defaults = getDefaultSection(); - if (defaults != null) { + if (defaults != null) + { result.putAll(defaults.getValues(deep)); } } @@ -151,172 +163,200 @@ public class MemorySection implements ConfigurationSection { return result; } - public boolean contains(String path) { + @Override + public boolean contains(final String path) + { return get(path) != null; } - public boolean isSet(String path) { - Configuration root = getRoot(); - if (root == null) { - return false; - } - if (root.options().copyDefaults()) { - return contains(path); - } + @Override + public boolean isSet(final String path) + { + final Configuration root = getRoot(); + if (root == null) { return false; } + if (root.options().copyDefaults()) { return contains(path); } return get(path, null) != null; } - public String getCurrentPath() { + @Override + public String getCurrentPath() + { return fullPath; } - public String getName() { + @Override + public String getName() + { return path; } - public Configuration getRoot() { + @Override + public Configuration getRoot() + { return root; } - public ConfigurationSection getParent() { + @Override + public ConfigurationSection getParent() + { return parent; } - public void addDefault(String path, Object value) { - if (path == null) throw new NullPointerException("Path cannot be null"); + @Override + public void addDefault(final String path, final Object value) + { + if (path == null) { throw new NullPointerException("Path cannot be null"); } - Configuration root = getRoot(); - if (root == null) { - throw new IllegalStateException("Cannot add default without root"); - } - if (root == this) { - throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation"); - } + final Configuration root = getRoot(); + if (root == null) { throw new IllegalStateException("Cannot add default without root"); } + if (root == this) { throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation"); } root.addDefault(createPath(this, path), value); } - public ConfigurationSection getDefaultSection() { - Configuration root = getRoot(); - Configuration defaults = root == null ? null : root.getDefaults(); + @Override + public ConfigurationSection getDefaultSection() + { + final Configuration root = getRoot(); + final Configuration defaults = root == null ? null : root.getDefaults(); - if (defaults != null) { - if (defaults.isConfigurationSection(getCurrentPath())) { - return defaults.getConfigurationSection(getCurrentPath()); - } + if (defaults != null) + { + if (defaults.isConfigurationSection(getCurrentPath())) { return defaults.getConfigurationSection(getCurrentPath()); } } return null; } - public void set(String path, Object value) { - if (path == null) throw new NullPointerException("Cannot set to an empty path"); + @Override + public void set(final String path, final Object value) + { + if (path == null) { throw new NullPointerException("Cannot set to an empty path"); } - Configuration root = getRoot(); - if (root == null) { - throw new IllegalStateException("Cannot use section without a root"); - } + final Configuration root = getRoot(); + if (root == null) { throw new IllegalStateException("Cannot use section without a root"); } final char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index int i1 = -1, i2; ConfigurationSection section = this; - while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { - String node = path.substring(i2, i1); - ConfigurationSection subSection = section.getConfigurationSection(node); - if (subSection == null) { + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) + { + final String node = path.substring(i2, i1); + final ConfigurationSection subSection = section.getConfigurationSection(node); + if (subSection == null) + { section = section.createSection(node); - } else { + } + else + { section = subSection; } } - String key = path.substring(i2); - if (section == this) { - if (value == null) { + final String key = path.substring(i2); + if (section == this) + { + if (value == null) + { map.remove(key); - } else { + } + else + { map.put(key, value); } - } else { + } + else + { section.set(key, value); } } - public Object get(String path) { + @Override + public Object get(final String path) + { return get(path, getDefault(path)); } - public Object get(String path, Object def) { - if (path == null) throw new NullPointerException("Path cannot be null"); + @Override + public Object get(final String path, final Object def) + { + if (path == null) { throw new NullPointerException("Path cannot be null"); } - if (path.length() == 0) { - return this; - } + if (path.length() == 0) { return this; } - Configuration root = getRoot(); - if (root == null) { - throw new IllegalStateException("Cannot access section without a root"); - } + final Configuration root = getRoot(); + if (root == null) { throw new IllegalStateException("Cannot access section without a root"); } final char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index int i1 = -1, i2; ConfigurationSection section = this; - while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) + { section = section.getConfigurationSection(path.substring(i2, i1)); - if (section == null) { - return def; - } + if (section == null) { return def; } } - String key = path.substring(i2); - if (section == this) { - Object result = map.get(key); + final String key = path.substring(i2); + if (section == this) + { + final Object result = map.get(key); return (result == null) ? def : result; } return section.get(key, def); } - public ConfigurationSection createSection(String path) { - if (path == null) throw new NullPointerException("Cannot create section at empty path"); - Configuration root = getRoot(); - if (root == null) { - throw new IllegalStateException("Cannot create section without a root"); - } + @Override + public ConfigurationSection createSection(final String path) + { + if (path == null) { throw new NullPointerException("Cannot create section at empty path"); } + final Configuration root = getRoot(); + if (root == null) { throw new IllegalStateException("Cannot create section without a root"); } final char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index int i1 = -1, i2; ConfigurationSection section = this; - while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { - String node = path.substring(i2, i1); - ConfigurationSection subSection = section.getConfigurationSection(node); - if (subSection == null) { + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) + { + final String node = path.substring(i2, i1); + final ConfigurationSection subSection = section.getConfigurationSection(node); + if (subSection == null) + { section = section.createSection(node); - } else { + } + else + { section = subSection; } } - String key = path.substring(i2); - if (section == this) { - ConfigurationSection result = new MemorySection(this, key); + final String key = path.substring(i2); + if (section == this) + { + final ConfigurationSection result = new MemorySection(this, key); map.put(key, result); return result; } return section.createSection(key); } - public ConfigurationSection createSection(String path, Map map) { - ConfigurationSection section = createSection(path); + @Override + public ConfigurationSection createSection(final String path, final Map map) + { + final ConfigurationSection section = createSection(path); - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() instanceof Map) { + for (final Map.Entry entry : map.entrySet()) + { + if (entry.getValue() instanceof Map) + { section.createSection(entry.getKey().toString(), (Map) entry.getValue()); - } else { + } + else + { section.set(entry.getKey().toString(), entry.getValue()); } } @@ -325,108 +365,146 @@ public class MemorySection implements ConfigurationSection { } // Primitives - public String getString(String path) { - Object def = getDefault(path); + @Override + public String getString(final String path) + { + final Object def = getDefault(path); return getString(path, def != null ? def.toString() : null); } - public String getString(String path, String def) { - Object val = get(path, def); + @Override + public String getString(final String path, final String def) + { + final Object val = get(path, def); return (val != null) ? val.toString() : def; } - public boolean isString(String path) { - Object val = get(path); + @Override + public boolean isString(final String path) + { + final Object val = get(path); return val instanceof String; } - public int getInt(String path) { - Object def = getDefault(path); + @Override + public int getInt(final String path) + { + final Object def = getDefault(path); return getInt(path, toInt(def, 0)); } - public int getInt(String path, int def) { - Object val = get(path, def); + @Override + public int getInt(final String path, final int def) + { + final Object val = get(path, def); return toInt(val, def); } - public boolean isInt(String path) { - Object val = get(path); + @Override + public boolean isInt(final String path) + { + final Object val = get(path); return val instanceof Integer; } - public boolean getBoolean(String path) { - Object def = getDefault(path); + @Override + public boolean getBoolean(final String path) + { + final Object def = getDefault(path); return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false); } - public boolean getBoolean(String path, boolean def) { - Object val = get(path, def); + @Override + public boolean getBoolean(final String path, final boolean def) + { + final Object val = get(path, def); return (val instanceof Boolean) ? (Boolean) val : def; } - public boolean isBoolean(String path) { - Object val = get(path); + @Override + public boolean isBoolean(final String path) + { + final Object val = get(path); return val instanceof Boolean; } - public double getDouble(String path) { - Object def = getDefault(path); + @Override + public double getDouble(final String path) + { + final Object def = getDefault(path); return getDouble(path, toDouble(def, 0)); } - public double getDouble(String path, double def) { - Object val = get(path, def); + @Override + public double getDouble(final String path, final double def) + { + final Object val = get(path, def); return toDouble(val, def); } - public boolean isDouble(String path) { - Object val = get(path); + @Override + public boolean isDouble(final String path) + { + final Object val = get(path); return val instanceof Double; } - public long getLong(String path) { - Object def = getDefault(path); + @Override + public long getLong(final String path) + { + final Object def = getDefault(path); return getLong(path, toLong(def, 0)); } - public long getLong(String path, long def) { - Object val = get(path, def); + @Override + public long getLong(final String path, final long def) + { + final Object val = get(path, def); return toLong(val, def); } - public boolean isLong(String path) { - Object val = get(path); + @Override + public boolean isLong(final String path) + { + final Object val = get(path); return val instanceof Long; } // Java - public List getList(String path) { - Object def = getDefault(path); + @Override + public List getList(final String path) + { + final Object def = getDefault(path); return getList(path, (def instanceof List) ? (List) def : null); } - public List getList(String path, List def) { - Object val = get(path, def); + @Override + public List getList(final String path, final List def) + { + final Object val = get(path, def); return (List) ((val instanceof List) ? val : def); } - public boolean isList(String path) { - Object val = get(path); + @Override + public boolean isList(final String path) + { + final Object val = get(path); return val instanceof List; } - public List getStringList(String path) { - List list = getList(path); + @Override + public List getStringList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if ((object instanceof String) || (isPrimitiveWrapper(object))) { + for (final Object object : list) + { + if ((object instanceof String) || (isPrimitiveWrapper(object))) + { result.add(String.valueOf(object)); } } @@ -434,26 +512,36 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getIntegerList(String path) { - List list = getList(path); + @Override + public List getIntegerList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Integer) { + for (final Object object : list) + { + if (object instanceof Integer) + { result.add((Integer) object); - } else if (object instanceof String) { - try { + } + else if (object instanceof String) + { + try + { result.add(Integer.valueOf((String) object)); - } catch (Exception ex) { } - } else if (object instanceof Character) { + catch (final Exception ex) + {} + } + else if (object instanceof Character) + { result.add((int) ((Character) object).charValue()); - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add(((Number) object).intValue()); } } @@ -461,22 +549,29 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getBooleanList(String path) { - List list = getList(path); + @Override + public List getBooleanList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Boolean) { + for (final Object object : list) + { + if (object instanceof Boolean) + { result.add((Boolean) object); - } else if (object instanceof String) { - if (Boolean.TRUE.toString().equals(object)) { + } + else if (object instanceof String) + { + if (Boolean.TRUE.toString().equals(object)) + { result.add(true); - } else if (Boolean.FALSE.toString().equals(object)) { + } + else if (Boolean.FALSE.toString().equals(object)) + { result.add(false); } } @@ -485,26 +580,36 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getDoubleList(String path) { - List list = getList(path); + @Override + public List getDoubleList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Double) { + for (final Object object : list) + { + if (object instanceof Double) + { result.add((Double) object); - } else if (object instanceof String) { - try { + } + else if (object instanceof String) + { + try + { result.add(Double.valueOf((String) object)); - } catch (Exception ex) { } - } else if (object instanceof Character) { + catch (final Exception ex) + {} + } + else if (object instanceof Character) + { result.add((double) ((Character) object).charValue()); - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add(((Number) object).doubleValue()); } } @@ -512,26 +617,36 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getFloatList(String path) { - List list = getList(path); + @Override + public List getFloatList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Float) { + for (final Object object : list) + { + if (object instanceof Float) + { result.add((Float) object); - } else if (object instanceof String) { - try { + } + else if (object instanceof String) + { + try + { result.add(Float.valueOf((String) object)); - } catch (Exception ex) { } - } else if (object instanceof Character) { + catch (final Exception ex) + {} + } + else if (object instanceof Character) + { result.add((float) ((Character) object).charValue()); - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add(((Number) object).floatValue()); } } @@ -539,26 +654,36 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getLongList(String path) { - List list = getList(path); + @Override + public List getLongList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Long) { + for (final Object object : list) + { + if (object instanceof Long) + { result.add((Long) object); - } else if (object instanceof String) { - try { + } + else if (object instanceof String) + { + try + { result.add(Long.valueOf((String) object)); - } catch (Exception ex) { } - } else if (object instanceof Character) { + catch (final Exception ex) + {} + } + else if (object instanceof Character) + { result.add((long) ((Character) object).charValue()); - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add(((Number) object).longValue()); } } @@ -566,26 +691,36 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getByteList(String path) { - List list = getList(path); + @Override + public List getByteList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Byte) { + for (final Object object : list) + { + if (object instanceof Byte) + { result.add((Byte) object); - } else if (object instanceof String) { - try { + } + else if (object instanceof String) + { + try + { result.add(Byte.valueOf((String) object)); - } catch (Exception ex) { } - } else if (object instanceof Character) { + catch (final Exception ex) + {} + } + else if (object instanceof Character) + { result.add((byte) ((Character) object).charValue()); - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add(((Number) object).byteValue()); } } @@ -593,25 +728,32 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getCharacterList(String path) { - List list = getList(path); + @Override + public List getCharacterList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Character) { + for (final Object object : list) + { + if (object instanceof Character) + { result.add((Character) object); - } else if (object instanceof String) { - String str = (String) object; + } + else if (object instanceof String) + { + final String str = (String) object; - if (str.length() == 1) { + if (str.length() == 1) + { result.add(str.charAt(0)); } - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add((char) ((Number) object).intValue()); } } @@ -619,26 +761,36 @@ public class MemorySection implements ConfigurationSection { return result; } - public List getShortList(String path) { - List list = getList(path); + @Override + public List getShortList(final String path) + { + final List list = getList(path); - if (list == null) { - return new ArrayList(0); - } + if (list == null) { return new ArrayList(0); } - List result = new ArrayList(); + final List result = new ArrayList(); - for (Object object : list) { - if (object instanceof Short) { + for (final Object object : list) + { + if (object instanceof Short) + { result.add((Short) object); - } else if (object instanceof String) { - try { + } + else if (object instanceof String) + { + try + { result.add(Short.valueOf((String) object)); - } catch (Exception ex) { } - } else if (object instanceof Character) { + catch (final Exception ex) + {} + } + else if (object instanceof Character) + { result.add((short) ((Character) object).charValue()); - } else if (object instanceof Number) { + } + else if (object instanceof Number) + { result.add(((Number) object).shortValue()); } } @@ -646,16 +798,18 @@ public class MemorySection implements ConfigurationSection { return result; } - public List> getMapList(String path) { - List list = getList(path); - List> result = new ArrayList>(); + @Override + public List> getMapList(final String path) + { + final List list = getList(path); + final List> result = new ArrayList>(); - if (list == null) { - return result; - } + if (list == null) { return result; } - for (Object object : list) { - if (object instanceof Map) { + for (final Object object : list) + { + if (object instanceof Map) + { result.add((Map) object); } } @@ -663,74 +817,93 @@ public class MemorySection implements ConfigurationSection { return result; } - public ConfigurationSection getConfigurationSection(String path) { + @Override + public ConfigurationSection getConfigurationSection(final String path) + { Object val = get(path, null); - if (val != null) { - return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; - } + if (val != null) { return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; } val = get(path, getDefault(path)); return (val instanceof ConfigurationSection) ? createSection(path) : null; } - public boolean isConfigurationSection(String path) { - Object val = get(path); + @Override + public boolean isConfigurationSection(final String path) + { + final Object val = get(path); return val instanceof ConfigurationSection; } - protected boolean isPrimitiveWrapper(Object input) { - return input instanceof Integer || input instanceof Boolean || - input instanceof Character || input instanceof Byte || - input instanceof Short || input instanceof Double || - input instanceof Long || input instanceof Float; + protected boolean isPrimitiveWrapper(final Object input) + { + return (input instanceof Integer) || (input instanceof Boolean) || + (input instanceof Character) || (input instanceof Byte) || + (input instanceof Short) || (input instanceof Double) || + (input instanceof Long) || (input instanceof Float); } - protected Object getDefault(String path) { - if (path == null) throw new NullPointerException("Path may not be null"); + protected Object getDefault(final String path) + { + if (path == null) { throw new NullPointerException("Path may not be null"); } - Configuration root = getRoot(); - Configuration defaults = root == null ? null : root.getDefaults(); + final Configuration root = getRoot(); + final Configuration defaults = root == null ? null : root.getDefaults(); return (defaults == null) ? null : defaults.get(createPath(this, path)); } - protected void mapChildrenKeys(Set output, ConfigurationSection section, boolean deep) { - if (section instanceof MemorySection) { - MemorySection sec = (MemorySection) section; + protected void mapChildrenKeys(final Set output, final ConfigurationSection section, final boolean deep) + { + if (section instanceof MemorySection) + { + final MemorySection sec = (MemorySection) section; - for (Map.Entry entry : sec.map.entrySet()) { + for (final Map.Entry entry : sec.map.entrySet()) + { output.add(createPath(section, entry.getKey(), this)); - if ((deep) && (entry.getValue() instanceof ConfigurationSection)) { - ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); + if ((deep) && (entry.getValue() instanceof ConfigurationSection)) + { + final ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); mapChildrenKeys(output, subsection, deep); } } - } else { - Set keys = section.getKeys(deep); + } + else + { + final Set keys = section.getKeys(deep); - for (String key : keys) { + for (final String key : keys) + { output.add(createPath(section, key, this)); } } } - protected void mapChildrenValues(Map output, ConfigurationSection section, boolean deep) { - if (section instanceof MemorySection) { - MemorySection sec = (MemorySection) section; + protected void mapChildrenValues(final Map output, final ConfigurationSection section, final boolean deep) + { + if (section instanceof MemorySection) + { + final MemorySection sec = (MemorySection) section; - for (Map.Entry entry : sec.map.entrySet()) { + for (final Map.Entry entry : sec.map.entrySet()) + { output.put(createPath(section, entry.getKey(), this), entry.getValue()); - if (entry.getValue() instanceof ConfigurationSection) { - if (deep) { + if (entry.getValue() instanceof ConfigurationSection) + { + if (deep) + { mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep); } } } - } else { - Map values = section.getValues(deep); + } + else + { + final Map values = section.getValues(deep); - for (Map.Entry entry : values.entrySet()) { + for (final Map.Entry entry : values.entrySet()) + { output.put(createPath(section, entry.getKey(), this), entry.getValue()); } } @@ -747,7 +920,8 @@ public class MemorySection implements ConfigurationSection { * @param key Name of the specified section. * @return Full path of the section from its root. */ - public static String createPath(ConfigurationSection section, String key) { + public static String createPath(final ConfigurationSection section, final String key) + { return createPath(section, key, (section == null) ? null : section.getRoot()); } @@ -763,18 +937,20 @@ public class MemorySection implements ConfigurationSection { * @param relativeTo Section to create the path relative to. * @return Full path of the section from its root. */ - public static String createPath(ConfigurationSection section, String key, ConfigurationSection relativeTo) { - if (section == null) throw new NullPointerException("Cannot create path without a section"); - Configuration root = section.getRoot(); - if (root == null) { - throw new IllegalStateException("Cannot create path without a root"); - } - char separator = root.options().pathSeparator(); + public static String createPath(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo) + { + if (section == null) { throw new NullPointerException("Cannot create path without a section"); } + final Configuration root = section.getRoot(); + if (root == null) { throw new IllegalStateException("Cannot create path without a root"); } + final char separator = root.options().pathSeparator(); - StringBuilder builder = new StringBuilder(); - if (section != null) { - for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) { - if (builder.length() > 0) { + final StringBuilder builder = new StringBuilder(); + if (section != null) + { + for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) + { + if (builder.length() > 0) + { builder.insert(0, separator); } @@ -782,8 +958,10 @@ public class MemorySection implements ConfigurationSection { } } - if ((key != null) && (key.length() > 0)) { - if (builder.length() > 0) { + if ((key != null) && (key.length() > 0)) + { + if (builder.length() > 0) + { builder.append(separator); } @@ -794,15 +972,16 @@ public class MemorySection implements ConfigurationSection { } @Override - public String toString() { - Configuration root = getRoot(); + public String toString() + { + final Configuration root = getRoot(); return new StringBuilder() - .append(getClass().getSimpleName()) - .append("[path='") - .append(getCurrentPath()) - .append("', root='") - .append(root == null ? null : root.getClass().getSimpleName()) - .append("']") - .toString(); + .append(getClass().getSimpleName()) + .append("[path='") + .append(getCurrentPath()) + .append("', root='") + .append(root == null ? null : root.getClass().getSimpleName()) + .append("']") + .toString(); } } diff --git a/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java index 171374deb..5cec0073b 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java @@ -24,7 +24,8 @@ import com.intellectualcrafters.configuration.MemoryConfiguration; * This is a base class for all File based implementations of {@link * Configuration} */ -public abstract class FileConfiguration extends MemoryConfiguration { +public abstract class FileConfiguration extends MemoryConfiguration +{ /** * This value specified that the system default encoding should be * completely ignored, as it cannot handle the ASCII character set, or it @@ -49,7 +50,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { */ @Deprecated public static final boolean SYSTEM_UTF; - static { + static + { final byte[] testBytes = Base64Coder.decode("ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4NCg=="); final String testString = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n"; final Charset defaultCharset = Charset.defaultCharset(); @@ -63,7 +65,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { /** * Creates an empty {@link FileConfiguration} with no default values. */ - public FileConfiguration() { + public FileConfiguration() + { super(); } @@ -73,7 +76,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { * * @param defaults Default value provider */ - public FileConfiguration(Configuration defaults) { + public FileConfiguration(final Configuration defaults) + { super(defaults); } @@ -92,17 +96,21 @@ public abstract class FileConfiguration extends MemoryConfiguration { * any reason. * @throws IllegalArgumentException Thrown when file is null. */ - public void save(File file) throws IOException { - if (file == null) throw new NullPointerException("File cannot be null"); + public void save(final File file) throws IOException + { + if (file == null) { throw new NullPointerException("File cannot be null"); } file.getParentFile().mkdirs(); - String data = saveToString(); + final String data = saveToString(); - Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset()); + final Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset()); - try { + try + { writer.write(data); - } finally { + } + finally + { writer.close(); } } @@ -122,8 +130,9 @@ public abstract class FileConfiguration extends MemoryConfiguration { * any reason. * @throws IllegalArgumentException Thrown when file is null. */ - public void save(String file) throws IOException { - if (file == null) throw new NullPointerException("File cannot be null"); + public void save(final String file) throws IOException + { + if (file == null) { throw new NullPointerException("File cannot be null"); } save(new File(file)); } @@ -157,8 +166,9 @@ public abstract class FileConfiguration extends MemoryConfiguration { * a valid Configuration. * @throws IllegalArgumentException Thrown when file is null. */ - public void load(File file) throws IOException, InvalidConfigurationException { - if (file == null) throw new NullPointerException("File cannot be null"); + public void load(final File file) throws IOException, InvalidConfigurationException + { + if (file == null) { throw new NullPointerException("File cannot be null"); } final FileInputStream stream = new FileInputStream(file); @@ -184,8 +194,9 @@ public abstract class FileConfiguration extends MemoryConfiguration { * @see #load(Reader) */ @Deprecated - public void load(InputStream stream) throws IOException, InvalidConfigurationException { - if (stream == null) throw new NullPointerException("Stream cannot be null"); + public void load(final InputStream stream) throws IOException, InvalidConfigurationException + { + if (stream == null) { throw new NullPointerException("Stream cannot be null"); } load(new InputStreamReader(stream, UTF8_OVERRIDE ? StandardCharsets.UTF_8 : Charset.defaultCharset())); } @@ -203,19 +214,24 @@ public abstract class FileConfiguration extends MemoryConfiguration { * represent a valid Configuration * @throws IllegalArgumentException thrown when reader is null */ - public void load(Reader reader) throws IOException, InvalidConfigurationException { - BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + public void load(final Reader reader) throws IOException, InvalidConfigurationException + { + final BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); - try { + try + { String line; - while ((line = input.readLine()) != null) { + while ((line = input.readLine()) != null) + { builder.append(line); builder.append('\n'); } - } finally { + } + finally + { input.close(); } @@ -240,8 +256,9 @@ public abstract class FileConfiguration extends MemoryConfiguration { * a valid Configuration. * @throws IllegalArgumentException Thrown when file is null. */ - public void load(String file) throws IOException, InvalidConfigurationException { - if (file == null) throw new NullPointerException("File cannot be null"); + public void load(final String file) throws IOException, InvalidConfigurationException + { + if (file == null) { throw new NullPointerException("File cannot be null"); } load(new File(file)); } @@ -261,7 +278,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { * invalid. * @throws IllegalArgumentException Thrown if contents is null. */ - public abstract void loadFromString(String contents) throws InvalidConfigurationException; + public abstract void loadFromString(final String contents) throws InvalidConfigurationException; /** * Compiles the header for this {@link FileConfiguration} and returns the @@ -276,11 +293,13 @@ public abstract class FileConfiguration extends MemoryConfiguration { protected abstract String buildHeader(); @Override - public FileConfigurationOptions options() { - if (options == null) { + public FileConfigurationOptions options() + { + if (options == null) + { options = new FileConfigurationOptions(this); } return (FileConfigurationOptions) options; } -} \ No newline at end of file +} diff --git a/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java index 72936c667..9b26be71c 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java @@ -7,27 +7,32 @@ import com.intellectualcrafters.configuration.MemoryConfigurationOptions; * Various settings for controlling the input and output of a {@link * FileConfiguration} */ -public class FileConfigurationOptions extends MemoryConfigurationOptions { +public class FileConfigurationOptions extends MemoryConfigurationOptions +{ private String header = null; private boolean copyHeader = true; - protected FileConfigurationOptions(MemoryConfiguration configuration) { + protected FileConfigurationOptions(final MemoryConfiguration configuration) + { super(configuration); } @Override - public FileConfiguration configuration() { + public FileConfiguration configuration() + { return (FileConfiguration) super.configuration(); } @Override - public FileConfigurationOptions copyDefaults(boolean value) { + public FileConfigurationOptions copyDefaults(final boolean value) + { super.copyDefaults(value); return this; } @Override - public FileConfigurationOptions pathSeparator(char value) { + public FileConfigurationOptions pathSeparator(final char value) + { super.pathSeparator(value); return this; } @@ -46,7 +51,8 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { * * @return Header */ - public String header() { + public String header() + { return header; } @@ -65,8 +71,9 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { * @param value New header * @return This object, for chaining */ - public FileConfigurationOptions header(String value) { - this.header = value; + public FileConfigurationOptions header(final String value) + { + header = value; return this; } @@ -88,7 +95,8 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { * * @return Whether or not to copy the header */ - public boolean copyHeader() { + public boolean copyHeader() + { return copyHeader; } @@ -111,7 +119,8 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { * @param value Whether or not to copy the header * @return This object, for chaining */ - public FileConfigurationOptions copyHeader(boolean value) { + public FileConfigurationOptions copyHeader(final boolean value) + { copyHeader = value; return this; diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java index d1277be62..2a3a5fc20 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java @@ -22,7 +22,8 @@ import com.intellectualcrafters.plot.PS; * An implementation of {@link Configuration} which saves all files in Yaml. * Note that this implementation is not synchronized. */ -public class YamlConfiguration extends FileConfiguration { +public class YamlConfiguration extends FileConfiguration +{ protected static final String COMMENT_PREFIX = "# "; protected static final String BLANK_CONFIG = "{}\n"; private final DumperOptions yamlOptions = new DumperOptions(); @@ -30,16 +31,18 @@ public class YamlConfiguration extends FileConfiguration { private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); @Override - public String saveToString() { + public String saveToString() + { yamlOptions.setIndent(options().indent()); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlOptions.setAllowUnicode(SYSTEM_UTF); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - String header = buildHeader(); + final String header = buildHeader(); String dump = yaml.dump(getValues(false)); - if (dump.equals(BLANK_CONFIG)) { + if (dump.equals(BLANK_CONFIG)) + { dump = ""; } @@ -47,63 +50,85 @@ public class YamlConfiguration extends FileConfiguration { } @Override - public void loadFromString(String contents) throws InvalidConfigurationException { - if (contents == null) throw new NullPointerException("Contents cannot be null"); + public void loadFromString(final String contents) throws InvalidConfigurationException + { + if (contents == null) { throw new NullPointerException("Contents cannot be null"); } Map input; - try { + try + { input = (Map) yaml.load(contents); - } catch (YAMLException e) { + } + catch (final YAMLException e) + { throw new InvalidConfigurationException(e); - } catch (ClassCastException e) { + } + catch (final ClassCastException e) + { throw new InvalidConfigurationException("Top level is not a Map."); } - String header = parseHeader(contents); - if (header.length() > 0) { + final String header = parseHeader(contents); + if (header.length() > 0) + { options().header(header); } - if (input != null) { + if (input != null) + { convertMapsToSections(input, this); } } - protected void convertMapsToSections(Map input, ConfigurationSection section) { - for (Map.Entry entry : input.entrySet()) { - String key = entry.getKey().toString(); - Object value = entry.getValue(); + protected void convertMapsToSections(final Map input, final ConfigurationSection section) + { + for (final Map.Entry entry : input.entrySet()) + { + final String key = entry.getKey().toString(); + final Object value = entry.getValue(); - if (value instanceof Map) { + if (value instanceof Map) + { convertMapsToSections((Map) value, section.createSection(key)); - } else { + } + else + { section.set(key, value); } } } - protected String parseHeader(String input) { - String[] lines = input.split("\r?\n", -1); - StringBuilder result = new StringBuilder(); + protected String parseHeader(final String input) + { + final String[] lines = input.split("\r?\n", -1); + final StringBuilder result = new StringBuilder(); boolean readingHeader = true; boolean foundHeader = false; - for (int i = 0; (i < lines.length) && (readingHeader); i++) { - String line = lines[i]; + for (int i = 0; (i < lines.length) && (readingHeader); i++) + { + final String line = lines[i]; - if (line.startsWith(COMMENT_PREFIX)) { - if (i > 0) { + if (line.startsWith(COMMENT_PREFIX)) + { + if (i > 0) + { result.append("\n"); } - if (line.length() > COMMENT_PREFIX.length()) { + if (line.length() > COMMENT_PREFIX.length()) + { result.append(line.substring(COMMENT_PREFIX.length())); } foundHeader = true; - } else if ((foundHeader) && (line.length() == 0)) { + } + else if ((foundHeader) && (line.length() == 0)) + { result.append("\n"); - } else if (foundHeader) { + } + else if (foundHeader) + { readingHeader = false; } } @@ -112,34 +137,35 @@ public class YamlConfiguration extends FileConfiguration { } @Override - protected String buildHeader() { - String header = options().header(); + protected String buildHeader() + { + final String header = options().header(); - if (options().copyHeader()) { - Configuration def = getDefaults(); + if (options().copyHeader()) + { + final Configuration def = getDefaults(); - if ((def != null) && (def instanceof FileConfiguration)) { - FileConfiguration filedefaults = (FileConfiguration) def; - String defaultsHeader = filedefaults.buildHeader(); + if ((def != null) && (def instanceof FileConfiguration)) + { + final FileConfiguration filedefaults = (FileConfiguration) def; + final String defaultsHeader = filedefaults.buildHeader(); - if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { - return defaultsHeader; - } + if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { return defaultsHeader; } } } - if (header == null) { - return ""; - } + if (header == null) { return ""; } - StringBuilder builder = new StringBuilder(); - String[] lines = header.split("\r?\n", -1); + final StringBuilder builder = new StringBuilder(); + final String[] lines = header.split("\r?\n", -1); boolean startedHeader = false; - for (int i = lines.length - 1; i >= 0; i--) { + for (int i = lines.length - 1; i >= 0; i--) + { builder.insert(0, "\n"); - if ((startedHeader) || (lines[i].length() != 0)) { + if ((startedHeader) || (lines[i].length() != 0)) + { builder.insert(0, lines[i]); builder.insert(0, COMMENT_PREFIX); startedHeader = true; @@ -150,8 +176,10 @@ public class YamlConfiguration extends FileConfiguration { } @Override - public YamlConfigurationOptions options() { - if (options == null) { + public YamlConfigurationOptions options() + { + if (options == null) + { options = new YamlConfigurationOptions(this); } @@ -171,28 +199,36 @@ public class YamlConfiguration extends FileConfiguration { * @return Resulting configuration * @throws IllegalArgumentException Thrown if file is null */ - public static YamlConfiguration loadConfiguration(File file) { - if (file == null) throw new NullPointerException("File cannot be null"); + public static YamlConfiguration loadConfiguration(final File file) + { + if (file == null) { throw new NullPointerException("File cannot be null"); } - YamlConfiguration config = new YamlConfiguration(); + final YamlConfiguration config = new YamlConfiguration(); - try { + try + { config.load(file); - } catch (Exception ex) { - try { - String path = file.getAbsolutePath() + "_broken"; + } + catch (final Exception ex) + { + try + { + file.getAbsolutePath(); File dest = new File(file.getAbsolutePath() + "_broken"); int i = 0; - while (dest.exists()) { + while (dest.exists()) + { dest = new File(file.getAbsolutePath() + "_broken_" + i++); } - Files.copy( file.toPath(), dest.toPath() , StandardCopyOption.REPLACE_EXISTING); + Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); PS.debug("&dCould not read: &7" + file); PS.debug("&drenamed to: &7" + dest.getName()); PS.debug("&c============ Full stacktrace ============"); ex.printStackTrace(); PS.debug("&c========================================="); - } catch (IOException e) { + } + catch (final IOException e) + { e.printStackTrace(); } } @@ -215,17 +251,23 @@ public class YamlConfiguration extends FileConfiguration { * @see #loadConfiguration(Reader) */ @Deprecated - public static YamlConfiguration loadConfiguration(InputStream stream) { - if (stream == null) throw new NullPointerException("Stream cannot be null"); + public static YamlConfiguration loadConfiguration(final InputStream stream) + { + if (stream == null) { throw new NullPointerException("Stream cannot be null"); } - YamlConfiguration config = new YamlConfiguration(); + final YamlConfiguration config = new YamlConfiguration(); - try { + try + { config.load(stream); - } catch (IOException ex) { + } + catch (final IOException ex) + { PS.debug("Cannot load configuration from stream"); ex.printStackTrace(); - } catch (InvalidConfigurationException ex) { + } + catch (final InvalidConfigurationException ex) + { ex.printStackTrace(); PS.debug("Cannot load configuration from stream"); } @@ -233,7 +275,6 @@ public class YamlConfiguration extends FileConfiguration { return config; } - /** * Creates a new {@link YamlConfiguration}, loading from the given reader. *

@@ -245,17 +286,23 @@ public class YamlConfiguration extends FileConfiguration { * @return resulting configuration * @throws IllegalArgumentException Thrown if stream is null */ - public static YamlConfiguration loadConfiguration(Reader reader) { - if (reader == null) throw new NullPointerException("Reader cannot be null"); + public static YamlConfiguration loadConfiguration(final Reader reader) + { + if (reader == null) { throw new NullPointerException("Reader cannot be null"); } - YamlConfiguration config = new YamlConfiguration(); + final YamlConfiguration config = new YamlConfiguration(); - try { + try + { config.load(reader); - } catch (IOException ex) { + } + catch (final IOException ex) + { PS.debug("Cannot load configuration from stream"); ex.printStackTrace(); - } catch (InvalidConfigurationException ex) { + } + catch (final InvalidConfigurationException ex) + { PS.debug("Cannot load configuration from stream"); ex.printStackTrace(); } diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java index 6783d5ce4..75eae9250 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java @@ -4,38 +4,45 @@ package com.intellectualcrafters.configuration.file; * Various settings for controlling the input and output of a {@link * YamlConfiguration} */ -public class YamlConfigurationOptions extends FileConfigurationOptions { +public class YamlConfigurationOptions extends FileConfigurationOptions +{ private int indent = 2; - protected YamlConfigurationOptions(YamlConfiguration configuration) { + protected YamlConfigurationOptions(final YamlConfiguration configuration) + { super(configuration); } @Override - public YamlConfiguration configuration() { + public YamlConfiguration configuration() + { return (YamlConfiguration) super.configuration(); } @Override - public YamlConfigurationOptions copyDefaults(boolean value) { + public YamlConfigurationOptions copyDefaults(final boolean value) + { super.copyDefaults(value); return this; } @Override - public YamlConfigurationOptions pathSeparator(char value) { + public YamlConfigurationOptions pathSeparator(final char value) + { super.pathSeparator(value); return this; } @Override - public YamlConfigurationOptions header(String value) { + public YamlConfigurationOptions header(final String value) + { super.header(value); return this; } @Override - public YamlConfigurationOptions copyHeader(boolean value) { + public YamlConfigurationOptions copyHeader(final boolean value) + { super.copyHeader(value); return this; } @@ -47,7 +54,8 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { * * @return How much to indent by */ - public int indent() { + public int indent() + { return indent; } @@ -59,11 +67,12 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { * @param value New indent * @return This object, for chaining */ - public YamlConfigurationOptions indent(int value) { - if (value < 2) throw new IllegalArgumentException("Indent must be at least 2 characters"); - if (value > 9) throw new IllegalArgumentException("Indent cannot be greater than 9 characters"); + public YamlConfigurationOptions indent(final int value) + { + if (value < 2) { throw new IllegalArgumentException("Indent must be at least 2 characters"); } + if (value > 9) { throw new IllegalArgumentException("Indent cannot be greater than 9 characters"); } - this.indent = value; + indent = value; return this; } } diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java index 5a8b41732..688a53791 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java @@ -10,30 +10,37 @@ import org.yaml.snakeyaml.nodes.Tag; import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; -public class YamlConstructor extends SafeConstructor { +public class YamlConstructor extends SafeConstructor +{ - public YamlConstructor() { - this.yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); + public YamlConstructor() + { + yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); } - private class ConstructCustomObject extends ConstructYamlMap { + private class ConstructCustomObject extends ConstructYamlMap + { @Override - public Object construct(Node node) { - if (node.isTwoStepsConstruction()) { - throw new YAMLException("Unexpected referential mapping structure. Node: " + node); - } + public Object construct(final Node node) + { + if (node.isTwoStepsConstruction()) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } - Map raw = (Map) super.construct(node); + final Map raw = (Map) super.construct(node); - if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { - Map typed = new LinkedHashMap(raw.size()); - for (Map.Entry entry : raw.entrySet()) { + if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) + { + final Map typed = new LinkedHashMap(raw.size()); + for (final Map.Entry entry : raw.entrySet()) + { typed.put(entry.getKey().toString(), entry.getValue()); } - try { + try + { return ConfigurationSerialization.deserializeObject(typed); - } catch (IllegalArgumentException ex) { + } + catch (final IllegalArgumentException ex) + { throw new YAMLException("Could not deserialize object", ex); } } @@ -42,7 +49,8 @@ public class YamlConstructor extends SafeConstructor { } @Override - public void construct2ndStep(Node node, Object object) { + public void construct2ndStep(final Node node, final Object object) + { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } } diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java index d4ef6da29..f5bf748f2 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java @@ -10,25 +10,31 @@ import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; -public class YamlRepresenter extends Representer { +public class YamlRepresenter extends Representer +{ - public YamlRepresenter() { - this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); - this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); + public YamlRepresenter() + { + multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); + multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); } - private class RepresentConfigurationSection extends RepresentMap { + private class RepresentConfigurationSection extends RepresentMap + { @Override - public Node representData(Object data) { + public Node representData(final Object data) + { return super.representData(((ConfigurationSection) data).getValues(false)); } } - private class RepresentConfigurationSerializable extends RepresentMap { + private class RepresentConfigurationSerializable extends RepresentMap + { @Override - public Node representData(Object data) { - ConfigurationSerializable serializable = (ConfigurationSerializable) data; - Map values = new LinkedHashMap(); + public Node representData(final Object data) + { + final ConfigurationSerializable serializable = (ConfigurationSerializable) data; + final Map values = new LinkedHashMap(); values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); values.putAll(serializable.serialize()); diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java index e403ebed9..0cca20083 100644 --- a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java +++ b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java @@ -21,7 +21,8 @@ import java.util.Map; * @see DelegateDeserialization * @see SerializableAs */ -public interface ConfigurationSerializable { +public interface ConfigurationSerializable +{ /** * Creates a Map representation of this class. diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java index db59bff3f..17eb82574 100644 --- a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java +++ b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java @@ -14,103 +14,130 @@ import com.intellectualcrafters.configuration.Configuration; /** * Utility class for storing and retrieving classes for {@link Configuration}. */ -public class ConfigurationSerialization { +public class ConfigurationSerialization +{ public static final String SERIALIZED_TYPE_KEY = "=="; private final Class clazz; private static Map> aliases = new HashMap>(); - protected ConfigurationSerialization(Class clazz) { + protected ConfigurationSerialization(final Class clazz) + { this.clazz = clazz; } - protected Method getMethod(String name, boolean isStatic) { - try { - Method method = clazz.getDeclaredMethod(name, Map.class); + protected Method getMethod(final String name, final boolean isStatic) + { + try + { + final Method method = clazz.getDeclaredMethod(name, Map.class); - if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { - return null; - } - if (Modifier.isStatic(method.getModifiers()) != isStatic) { - return null; - } + if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { return null; } + if (Modifier.isStatic(method.getModifiers()) != isStatic) { return null; } return method; - } catch (NoSuchMethodException ex) { + } + catch (final NoSuchMethodException ex) + { return null; - } catch (SecurityException ex) { + } + catch (final SecurityException ex) + { return null; } } - protected Constructor getConstructor() { - try { + protected Constructor getConstructor() + { + try + { return clazz.getConstructor(Map.class); - } catch (NoSuchMethodException ex) { + } + catch (final NoSuchMethodException ex) + { return null; - } catch (SecurityException ex) { + } + catch (final SecurityException ex) + { return null; } } - protected ConfigurationSerializable deserializeViaMethod(Method method, Map args) { - try { - ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); + protected ConfigurationSerializable deserializeViaMethod(final Method method, final Map args) + { + try + { + final ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); - if (result == null) { - Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null"); - } else { + if (result == null) + { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null"); + } + else + { return result; } - } catch (Throwable ex) { + } + catch (final Throwable ex) + { Logger.getLogger(ConfigurationSerialization.class.getName()).log( - Level.SEVERE, - "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); } return null; } - protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map args) { - try { + protected ConfigurationSerializable deserializeViaCtor(final Constructor ctor, final Map args) + { + try + { return ctor.newInstance(args); - } catch (Throwable ex) { + } + catch (final Throwable ex) + { Logger.getLogger(ConfigurationSerialization.class.getName()).log( - Level.SEVERE, - "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); } return null; } - public ConfigurationSerializable deserialize(Map args) { - if (args == null) { - throw new NullPointerException("Args must not be null"); - } + public ConfigurationSerializable deserialize(final Map args) + { + if (args == null) { throw new NullPointerException("Args must not be null"); } ConfigurationSerializable result = null; Method method = null; - if (result == null) { + if (result == null) + { method = getMethod("deserialize", true); - if (method != null) { + if (method != null) + { result = deserializeViaMethod(method, args); } } - if (result == null) { + if (result == null) + { method = getMethod("valueOf", true); - if (method != null) { + if (method != null) + { result = deserializeViaMethod(method, args); } } - if (result == null) { - Constructor constructor = getConstructor(); + if (result == null) + { + final Constructor constructor = getConstructor(); - if (constructor != null) { + if (constructor != null) + { result = deserializeViaCtor(constructor, args); } } @@ -133,7 +160,8 @@ public class ConfigurationSerialization { * @param clazz Class to deserialize into * @return New instance of the specified class */ - public static ConfigurationSerializable deserializeObject(Map args, Class clazz) { + public static ConfigurationSerializable deserializeObject(final Map args, final Class clazz) + { return new ConfigurationSerialization(clazz).deserialize(args); } @@ -151,25 +179,28 @@ public class ConfigurationSerialization { * @param args Arguments for deserialization * @return New instance of the specified class */ - public static ConfigurationSerializable deserializeObject(Map args) { + public static ConfigurationSerializable deserializeObject(final Map args) + { Class clazz = null; - if (args.containsKey(SERIALIZED_TYPE_KEY)) { - try { - String alias = (String) args.get(SERIALIZED_TYPE_KEY); + if (args.containsKey(SERIALIZED_TYPE_KEY)) + { + try + { + final String alias = (String) args.get(SERIALIZED_TYPE_KEY); - if (alias == null) { - throw new IllegalArgumentException("Cannot have null alias"); - } + if (alias == null) { throw new IllegalArgumentException("Cannot have null alias"); } clazz = getClassByAlias(alias); - if (clazz == null) { - throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); - } - } catch (ClassCastException ex) { + if (clazz == null) { throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); } + } + catch (final ClassCastException ex) + { ex.fillInStackTrace(); throw ex; } - } else { + } + else + { throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); } @@ -182,10 +213,12 @@ public class ConfigurationSerialization { * * @param clazz Class to register */ - public static void registerClass(Class clazz) { - DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + public static void registerClass(final Class clazz) + { + final DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); - if (delegate == null) { + if (delegate == null) + { registerClass(clazz, getAlias(clazz)); registerClass(clazz, clazz.getName()); } @@ -199,7 +232,8 @@ public class ConfigurationSerialization { * @param alias Alias to register as * @see SerializableAs */ - public static void registerClass(Class clazz, String alias) { + public static void registerClass(final Class clazz, final String alias) + { aliases.put(alias, clazz); } @@ -208,7 +242,8 @@ public class ConfigurationSerialization { * * @param alias Alias to unregister */ - public static void unregisterClass(String alias) { + public static void unregisterClass(final String alias) + { aliases.remove(alias); } @@ -218,9 +253,10 @@ public class ConfigurationSerialization { * * @param clazz Class to unregister */ - public static void unregisterClass(Class clazz) { - while (aliases.values().remove(clazz)) { - } + public static void unregisterClass(final Class clazz) + { + while (aliases.values().remove(clazz)) + {} } /** @@ -230,7 +266,8 @@ public class ConfigurationSerialization { * @param alias Alias of the serializable * @return Registered class, or null if not found */ - public static Class getClassByAlias(String alias) { + public static Class getClassByAlias(final String alias) + { return aliases.get(alias); } @@ -241,23 +278,27 @@ public class ConfigurationSerialization { * @param clazz Class to get alias for * @return Alias to use for the class */ - public static String getAlias(Class clazz) { + public static String getAlias(final Class clazz) + { DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); - if (delegate != null) { - if ((delegate.value() == null) || (delegate.value() == clazz)) { + if (delegate != null) + { + if ((delegate.value() == null) || (delegate.value() == clazz)) + { delegate = null; - } else { + } + else + { return getAlias(delegate.value()); } } - if (delegate == null) { - SerializableAs alias = clazz.getAnnotation(SerializableAs.class); + if (delegate == null) + { + final SerializableAs alias = clazz.getAnnotation(SerializableAs.class); - if ((alias != null) && (alias.value() != null)) { - return alias.value(); - } + if ((alias != null) && (alias.value() != null)) { return alias.value(); } } return clazz.getName(); diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java b/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java index bc505ccf2..bb0e04d68 100644 --- a/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java +++ b/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java @@ -11,7 +11,8 @@ import java.lang.annotation.Target; */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) -public @interface DelegateDeserialization { +public @interface DelegateDeserialization +{ /** * Which class should be used as a delegate for this classes * deserialization diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java b/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java index 668da9ac9..fde872a1b 100644 --- a/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java +++ b/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java @@ -21,7 +21,8 @@ import java.lang.annotation.Target; */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) -public @interface SerializableAs { +public @interface SerializableAs +{ /** * This is the name your class will be stored and retrieved as. *

diff --git a/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java b/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java index 67fc3d9b4..146f4e658 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java @@ -3,7 +3,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Byte_Array} tag. */ -public final class ByteArrayTag extends Tag { +public final class ByteArrayTag extends Tag +{ private final byte[] value; /** @@ -11,7 +12,8 @@ public final class ByteArrayTag extends Tag { * * @param value the value of the tag */ - public ByteArrayTag(final byte[] value) { + public ByteArrayTag(final byte[] value) + { super(); this.value = value; } @@ -22,30 +24,36 @@ public final class ByteArrayTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public ByteArrayTag(final String name, final byte[] value) { + public ByteArrayTag(final String name, final byte[] value) + { super(name); this.value = value; } @Override - public byte[] getValue() { - return this.value; + public byte[] getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final StringBuilder hex = new StringBuilder(); - for (final byte b : this.value) { + for (final byte b : value) + { final String hexDigits = Integer.toHexString(b).toUpperCase(); - if (hexDigits.length() == 1) { + if (hexDigits.length() == 1) + { hex.append("0"); } hex.append(hexDigits).append(" "); } final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } return "TAG_Byte_Array" + append + ": " + hex; } diff --git a/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java b/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java index 6ee42254c..fbdb1d30e 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java @@ -3,7 +3,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Byte} tag. */ -public final class ByteTag extends Tag { +public final class ByteTag extends Tag +{ private final byte value; /** @@ -11,7 +12,8 @@ public final class ByteTag extends Tag { * * @param value the value of the tag */ - public ByteTag(final byte value) { + public ByteTag(final byte value) + { super(); this.value = value; } @@ -22,23 +24,27 @@ public final class ByteTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public ByteTag(final String name, final byte value) { + public ByteTag(final String name, final byte value) + { super(name); this.value = value; } @Override - public Byte getValue() { - return this.value; + public Byte getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_Byte" + append + ": " + this.value; + return "TAG_Byte" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java b/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java index 842aba19b..6400f748f 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java @@ -8,7 +8,8 @@ import java.util.Map; /** * The {@code TAG_Compound} tag. */ -public final class CompoundTag extends Tag { +public final class CompoundTag extends Tag +{ private final Map value; /** @@ -16,7 +17,8 @@ public final class CompoundTag extends Tag { * * @param value the value of the tag */ - public CompoundTag(final Map value) { + public CompoundTag(final Map value) + { super(); this.value = Collections.unmodifiableMap(value); } @@ -27,7 +29,8 @@ public final class CompoundTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public CompoundTag(final String name, final Map value) { + public CompoundTag(final String name, final Map value) + { super(name); this.value = Collections.unmodifiableMap(value); } @@ -39,13 +42,15 @@ public final class CompoundTag extends Tag { * * @return true if the tag contains the given key */ - public boolean containsKey(final String key) { - return this.value.containsKey(key); + public boolean containsKey(final String key) + { + return value.containsKey(key); } @Override - public Map getValue() { - return this.value; + public Map getValue() + { + return value; } /** @@ -55,7 +60,8 @@ public final class CompoundTag extends Tag { * * @return the new compound tag */ - public CompoundTag setValue(final Map value) { + public CompoundTag setValue(final Map value) + { return new CompoundTag(getName(), value); } @@ -64,8 +70,9 @@ public final class CompoundTag extends Tag { * * @return the builder */ - public CompoundTagBuilder createBuilder() { - return new CompoundTagBuilder(new HashMap(this.value)); + public CompoundTagBuilder createBuilder() + { + return new CompoundTagBuilder(new HashMap(value)); } /** @@ -76,11 +83,15 @@ public final class CompoundTag extends Tag { * * @return a byte array */ - public byte[] getByteArray(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ByteArrayTag) { + public byte[] getByteArray(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ByteArrayTag) + { return ((ByteArrayTag) tag).getValue(); - } else { + } + else + { return new byte[0]; } } @@ -93,11 +104,15 @@ public final class CompoundTag extends Tag { * * @return a byte */ - public byte getByte(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ByteTag) { + public byte getByte(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else { + } + else + { return (byte) 0; } } @@ -110,11 +125,15 @@ public final class CompoundTag extends Tag { * * @return a double */ - public double getDouble(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof DoubleTag) { + public double getDouble(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -127,21 +146,35 @@ public final class CompoundTag extends Tag { * * @return a double */ - public double asDouble(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ByteTag) { + public double asDouble(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) + { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -154,11 +187,15 @@ public final class CompoundTag extends Tag { * * @return a float */ - public float getFloat(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof FloatTag) { + public float getFloat(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -171,11 +208,15 @@ public final class CompoundTag extends Tag { * * @return an int array */ - public int[] getIntArray(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof IntArrayTag) { + public int[] getIntArray(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof IntArrayTag) + { return ((IntArrayTag) tag).getValue(); - } else { + } + else + { return new int[0]; } } @@ -188,11 +229,15 @@ public final class CompoundTag extends Tag { * * @return an int */ - public int getInt(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof IntTag) { + public int getInt(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -205,21 +250,35 @@ public final class CompoundTag extends Tag { * * @return an int */ - public int asInt(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ByteTag) { + public int asInt(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) + { return ((LongTag) tag).getValue().intValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue().intValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue().intValue(); - } else { + } + else + { return 0; } } @@ -232,11 +291,15 @@ public final class CompoundTag extends Tag { * * @return a list of tags */ - public List getList(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ListTag) { + public List getList(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ListTag) + { return ((ListTag) tag).getValue(); - } else { + } + else + { return Collections.emptyList(); } } @@ -249,11 +312,15 @@ public final class CompoundTag extends Tag { * * @return a tag list instance */ - public ListTag getListTag(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ListTag) { + public ListTag getListTag(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ListTag) + { return (ListTag) tag; - } else { + } + else + { return new ListTag(key, StringTag.class, Collections. emptyList()); } } @@ -270,16 +337,23 @@ public final class CompoundTag extends Tag { * @return a list of tags */ @SuppressWarnings("unchecked") - public List getList(final String key, final Class listType) { - final Tag tag = this.value.get(key); - if (tag instanceof ListTag) { + public List getList(final String key, final Class listType) + { + final Tag tag = value.get(key); + if (tag instanceof ListTag) + { final ListTag listTag = (ListTag) tag; - if (listTag.getType().equals(listType)) { + if (listTag.getType().equals(listType)) + { return (List) listTag.getValue(); - } else { + } + else + { return Collections.emptyList(); } - } else { + } + else + { return Collections.emptyList(); } } @@ -292,11 +366,15 @@ public final class CompoundTag extends Tag { * * @return a long */ - public long getLong(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof LongTag) { + public long getLong(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof LongTag) + { return ((LongTag) tag).getValue(); - } else { + } + else + { return 0L; } } @@ -309,21 +387,35 @@ public final class CompoundTag extends Tag { * * @return a long */ - public long asLong(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ByteTag) { + public long asLong(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) + { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue().longValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue().longValue(); - } else { + } + else + { return 0L; } } @@ -336,11 +428,15 @@ public final class CompoundTag extends Tag { * * @return a short */ - public short getShort(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof ShortTag) { + public short getShort(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -353,25 +449,32 @@ public final class CompoundTag extends Tag { * * @return a string */ - public String getString(final String key) { - final Tag tag = this.value.get(key); - if (tag instanceof StringTag) { + public String getString(final String key) + { + final Tag tag = value.get(key); + if (tag instanceof StringTag) + { return ((StringTag) tag).getValue(); - } else { + } + else + { return ""; } } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } final StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n"); - for (final Map.Entry entry : this.value.entrySet()) { + bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n"); + for (final Map.Entry entry : value.entrySet()) + { bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); } bldr.append("}"); diff --git a/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java b/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java index 3036481f2..69f4d7356 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java +++ b/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java @@ -8,14 +8,16 @@ import java.util.Map; /** * Helps create compound tags. */ -public class CompoundTagBuilder { +public class CompoundTagBuilder +{ private final Map entries; /** * Create a new instance. */ - CompoundTagBuilder() { - this.entries = new HashMap(); + CompoundTagBuilder() + { + entries = new HashMap(); } /** @@ -23,9 +25,10 @@ public class CompoundTagBuilder { * * @param value the value */ - CompoundTagBuilder(final Map value) { + CompoundTagBuilder(final Map value) + { checkNotNull(value); - this.entries = value; + entries = value; } /** @@ -33,7 +36,8 @@ public class CompoundTagBuilder { * * @return a new builder */ - public static CompoundTagBuilder create() { + public static CompoundTagBuilder create() + { return new CompoundTagBuilder(); } @@ -45,10 +49,11 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder put(final String key, final Tag value) { + public CompoundTagBuilder put(final String key, final Tag value) + { checkNotNull(key); checkNotNull(value); - this.entries.put(key, value); + entries.put(key, value); return this; } @@ -60,7 +65,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putByteArray(final String key, final byte[] value) { + public CompoundTagBuilder putByteArray(final String key, final byte[] value) + { return put(key, new ByteArrayTag(key, value)); } @@ -72,7 +78,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putByte(final String key, final byte value) { + public CompoundTagBuilder putByte(final String key, final byte value) + { return put(key, new ByteTag(key, value)); } @@ -84,7 +91,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putDouble(final String key, final double value) { + public CompoundTagBuilder putDouble(final String key, final double value) + { return put(key, new DoubleTag(key, value)); } @@ -96,7 +104,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putFloat(final String key, final float value) { + public CompoundTagBuilder putFloat(final String key, final float value) + { return put(key, new FloatTag(key, value)); } @@ -108,7 +117,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putIntArray(final String key, final int[] value) { + public CompoundTagBuilder putIntArray(final String key, final int[] value) + { return put(key, new IntArrayTag(key, value)); } @@ -120,7 +130,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putInt(final String key, final int value) { + public CompoundTagBuilder putInt(final String key, final int value) + { return put(key, new IntTag(key, value)); } @@ -132,7 +143,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putLong(final String key, final long value) { + public CompoundTagBuilder putLong(final String key, final long value) + { return put(key, new LongTag(key, value)); } @@ -144,7 +156,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putShort(final String key, final short value) { + public CompoundTagBuilder putShort(final String key, final short value) + { return put(key, new ShortTag(key, value)); } @@ -156,7 +169,8 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putString(final String key, final String value) { + public CompoundTagBuilder putString(final String key, final String value) + { return put(key, new StringTag(key, value)); } @@ -167,9 +181,11 @@ public class CompoundTagBuilder { * * @return this object */ - public CompoundTagBuilder putAll(final Map value) { + public CompoundTagBuilder putAll(final Map value) + { checkNotNull(value); - for (final Map.Entry entry : value.entrySet()) { + for (final Map.Entry entry : value.entrySet()) + { put(entry.getKey(), entry.getValue()); } return this; @@ -180,8 +196,9 @@ public class CompoundTagBuilder { * * @return the new compound tag */ - public CompoundTag build() { - return new CompoundTag(new HashMap(this.entries)); + public CompoundTag build() + { + return new CompoundTag(new HashMap(entries)); } /** @@ -191,7 +208,8 @@ public class CompoundTagBuilder { * * @return the created compound tag */ - public CompoundTag build(final String name) { - return new CompoundTag(name, new HashMap(this.entries)); + public CompoundTag build(final String name) + { + return new CompoundTag(name, new HashMap(entries)); } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java b/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java index f7db525b3..272571f16 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java @@ -3,7 +3,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Double} tag. */ -public final class DoubleTag extends Tag { +public final class DoubleTag extends Tag +{ private final double value; /** @@ -11,7 +12,8 @@ public final class DoubleTag extends Tag { * * @param value the value of the tag */ - public DoubleTag(final double value) { + public DoubleTag(final double value) + { super(); this.value = value; } @@ -22,23 +24,27 @@ public final class DoubleTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public DoubleTag(final String name, final double value) { + public DoubleTag(final String name, final double value) + { super(name); this.value = value; } @Override - public Double getValue() { - return this.value; + public Double getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_Double" + append + ": " + this.value; + return "TAG_Double" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/EndTag.java b/src/main/java/com/intellectualcrafters/jnbt/EndTag.java index 70ffaa488..811ab5e81 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/EndTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/EndTag.java @@ -3,21 +3,25 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_End} tag. */ -public final class EndTag extends Tag { +public final class EndTag extends Tag +{ /** * Creates the tag. */ - public EndTag() { + public EndTag() + { super(); } @Override - public Object getValue() { + public Object getValue() + { return null; } @Override - public String toString() { + public String toString() + { return "TAG_End"; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java b/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java index 02649fbad..6cb78472b 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java @@ -3,7 +3,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Float} tag. */ -public final class FloatTag extends Tag { +public final class FloatTag extends Tag +{ private final float value; /** @@ -11,7 +12,8 @@ public final class FloatTag extends Tag { * * @param value the value of the tag */ - public FloatTag(final float value) { + public FloatTag(final float value) + { super(); this.value = value; } @@ -22,23 +24,27 @@ public final class FloatTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public FloatTag(final String name, final float value) { + public FloatTag(final String name, final float value) + { super(name); this.value = value; } @Override - public Float getValue() { - return this.value; + public Float getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_Float" + append + ": " + this.value; + return "TAG_Float" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java b/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java index 372002f05..14df42798 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java @@ -5,7 +5,8 @@ import static com.google.common.base.Preconditions.checkNotNull; /** * The {@code TAG_Int_Array} tag. */ -public final class IntArrayTag extends Tag { +public final class IntArrayTag extends Tag +{ private final int[] value; /** @@ -13,7 +14,8 @@ public final class IntArrayTag extends Tag { * * @param value the value of the tag */ - public IntArrayTag(final int[] value) { + public IntArrayTag(final int[] value) + { super(); checkNotNull(value); this.value = value; @@ -25,31 +27,37 @@ public final class IntArrayTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public IntArrayTag(final String name, final int[] value) { + public IntArrayTag(final String name, final int[] value) + { super(name); checkNotNull(value); this.value = value; } @Override - public int[] getValue() { - return this.value; + public int[] getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final StringBuilder hex = new StringBuilder(); - for (final int b : this.value) { + for (final int b : value) + { final String hexDigits = Integer.toHexString(b).toUpperCase(); - if (hexDigits.length() == 1) { + if (hexDigits.length() == 1) + { hex.append("0"); } hex.append(hexDigits).append(" "); } final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } return "TAG_Int_Array" + append + ": " + hex; } diff --git a/src/main/java/com/intellectualcrafters/jnbt/IntTag.java b/src/main/java/com/intellectualcrafters/jnbt/IntTag.java index abffe3825..389f4a67d 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/IntTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/IntTag.java @@ -3,7 +3,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Int} tag. */ -public final class IntTag extends Tag { +public final class IntTag extends Tag +{ private final int value; /** @@ -11,7 +12,8 @@ public final class IntTag extends Tag { * * @param value the value of the tag */ - public IntTag(final int value) { + public IntTag(final int value) + { super(); this.value = value; } @@ -22,23 +24,27 @@ public final class IntTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public IntTag(final String name, final int value) { + public IntTag(final String name, final int value) + { super(name); this.value = value; } @Override - public Integer getValue() { - return this.value; + public Integer getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_Int" + append + ": " + this.value; + return "TAG_Int" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/ListTag.java b/src/main/java/com/intellectualcrafters/jnbt/ListTag.java index 5a0cd5faf..6a859ed57 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/ListTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/ListTag.java @@ -6,11 +6,11 @@ import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; - /** * The {@code TAG_List} tag. */ -public final class ListTag extends Tag { +public final class ListTag extends Tag +{ private final Class type; private final List value; @@ -20,7 +20,8 @@ public final class ListTag extends Tag { * @param type the type of tag * @param value the value of the tag */ - public ListTag(final Class type, final List value) { + public ListTag(final Class type, final List value) + { super(); checkNotNull(value); this.type = type; @@ -34,7 +35,8 @@ public final class ListTag extends Tag { * @param type the type of tag * @param value the value of the tag */ - public ListTag(final String name, final Class type, final List value) { + public ListTag(final String name, final Class type, final List value) + { super(name); checkNotNull(value); this.type = type; @@ -46,13 +48,15 @@ public final class ListTag extends Tag { * * @return The type of item in this list. */ - public Class getType() { - return this.type; + public Class getType() + { + return type; } @Override - public List getValue() { - return this.value; + public List getValue() + { + return value; } /** @@ -62,7 +66,8 @@ public final class ListTag extends Tag { * * @return a new list tag */ - public ListTag setValue(final List list) { + public ListTag setValue(final List list) + { return new ListTag(getName(), getType(), list); } @@ -73,10 +78,14 @@ public final class ListTag extends Tag { * * @return the tag or null */ - public Tag getIfExists(final int index) { - try { - return this.value.get(index); - } catch (final NoSuchElementException e) { + public Tag getIfExists(final int index) + { + try + { + return value.get(index); + } + catch (final NoSuchElementException e) + { return null; } } @@ -89,11 +98,15 @@ public final class ListTag extends Tag { * * @return a byte array */ - public byte[] getByteArray(final int index) { + public byte[] getByteArray(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ByteArrayTag) { + if (tag instanceof ByteArrayTag) + { return ((ByteArrayTag) tag).getValue(); - } else { + } + else + { return new byte[0]; } } @@ -106,11 +119,15 @@ public final class ListTag extends Tag { * * @return a byte */ - public byte getByte(final int index) { + public byte getByte(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else { + } + else + { return (byte) 0; } } @@ -123,11 +140,15 @@ public final class ListTag extends Tag { * * @return a double */ - public double getDouble(final int index) { + public double getDouble(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof DoubleTag) { + if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -140,21 +161,35 @@ public final class ListTag extends Tag { * * @return a double */ - public double asDouble(final int index) { + public double asDouble(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) + { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -167,11 +202,15 @@ public final class ListTag extends Tag { * * @return a float */ - public float getFloat(final int index) { + public float getFloat(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof FloatTag) { + if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -184,11 +223,15 @@ public final class ListTag extends Tag { * * @return an int array */ - public int[] getIntArray(final int index) { + public int[] getIntArray(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof IntArrayTag) { + if (tag instanceof IntArrayTag) + { return ((IntArrayTag) tag).getValue(); - } else { + } + else + { return new int[0]; } } @@ -201,11 +244,15 @@ public final class ListTag extends Tag { * * @return an int */ - public int getInt(final int index) { + public int getInt(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof IntTag) { + if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -218,21 +265,35 @@ public final class ListTag extends Tag { * * @return an int */ - public int asInt(final int index) { + public int asInt(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) + { return ((LongTag) tag).getValue().intValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue().intValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue().intValue(); - } else { + } + else + { return 0; } } @@ -245,11 +306,15 @@ public final class ListTag extends Tag { * * @return a list of tags */ - public List getList(final int index) { + public List getList(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ListTag) { + if (tag instanceof ListTag) + { return ((ListTag) tag).getValue(); - } else { + } + else + { return Collections.emptyList(); } } @@ -262,11 +327,15 @@ public final class ListTag extends Tag { * * @return a tag list instance */ - public ListTag getListTag(final int index) { + public ListTag getListTag(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ListTag) { + if (tag instanceof ListTag) + { return (ListTag) tag; - } else { + } + else + { return new ListTag(StringTag.class, Collections. emptyList()); } } @@ -283,16 +352,23 @@ public final class ListTag extends Tag { * @return a list of tags */ @SuppressWarnings("unchecked") - public List getList(final int index, final Class listType) { + public List getList(final int index, final Class listType) + { final Tag tag = getIfExists(index); - if (tag instanceof ListTag) { + if (tag instanceof ListTag) + { final ListTag listTag = (ListTag) tag; - if (listTag.getType().equals(listType)) { + if (listTag.getType().equals(listType)) + { return (List) listTag.getValue(); - } else { + } + else + { return Collections.emptyList(); } - } else { + } + else + { return Collections.emptyList(); } } @@ -305,11 +381,15 @@ public final class ListTag extends Tag { * * @return a long */ - public long getLong(final int index) { + public long getLong(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof LongTag) { + if (tag instanceof LongTag) + { return ((LongTag) tag).getValue(); - } else { + } + else + { return 0L; } } @@ -322,21 +402,35 @@ public final class ListTag extends Tag { * * @return a long */ - public long asLong(final int index) { + public long asLong(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { + if (tag instanceof ByteTag) + { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) + { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) + { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) + { return ((FloatTag) tag).getValue().longValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) + { return ((DoubleTag) tag).getValue().longValue(); - } else { + } + else + { return 0; } } @@ -349,11 +443,15 @@ public final class ListTag extends Tag { * * @return a short */ - public short getShort(final int index) { + public short getShort(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof ShortTag) { + if (tag instanceof ShortTag) + { return ((ShortTag) tag).getValue(); - } else { + } + else + { return 0; } } @@ -366,25 +464,32 @@ public final class ListTag extends Tag { * * @return a string */ - public String getString(final int index) { + public String getString(final int index) + { final Tag tag = getIfExists(index); - if (tag instanceof StringTag) { + if (tag instanceof StringTag) + { return ((StringTag) tag).getValue(); - } else { + } + else + { return ""; } } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } final StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_List").append(append).append(": ").append(this.value.size()).append(" entries of type ").append(NBTUtils.getTypeName(this.type)).append("\r\n{\r\n"); - for (final Tag t : this.value) { + bldr.append("TAG_List").append(append).append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n"); + for (final Tag t : value) + { bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); } bldr.append("}"); diff --git a/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java b/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java index af94f866d..013529fbb 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java +++ b/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java @@ -10,7 +10,8 @@ import java.util.List; /** * Helps create list tags. */ -public class ListTagBuilder { +public class ListTagBuilder +{ private final Class type; private final List entries; @@ -19,42 +20,42 @@ public class ListTagBuilder { * * @param type of tag contained in this list */ - ListTagBuilder(final Class type) { + ListTagBuilder(final Class type) + { checkNotNull(type); this.type = type; - this.entries = new ArrayList(); + entries = new ArrayList(); } /** * Create a new builder instance. - * + * * @param type * * @return a new builder */ - public static ListTagBuilder create(final Class type) { + public static ListTagBuilder create(final Class type) + { return new ListTagBuilder(type); } /** * Create a new builder instance. - * + * * @param entries * @param * * @return a new builder */ @SafeVarargs - public static ListTagBuilder createWith(final T... entries) { + public static ListTagBuilder createWith(final T... entries) + { checkNotNull(entries); - if (entries.length == 0) { - throw new IllegalArgumentException("This method needs an array of at least one entry"); - } + if (entries.length == 0) { throw new IllegalArgumentException("This method needs an array of at least one entry"); } final Class type = entries[0].getClass(); - for (int i = 1; i < entries.length; i++) { - if (!type.isInstance(entries[i])) { - throw new IllegalArgumentException("An array of different tag types was provided"); - } + for (int i = 1; i < entries.length; i++) + { + if (!type.isInstance(entries[i])) { throw new IllegalArgumentException("An array of different tag types was provided"); } } final ListTagBuilder builder = new ListTagBuilder(type); builder.addAll(Arrays.asList(entries)); @@ -68,12 +69,11 @@ public class ListTagBuilder { * * @return this object */ - public ListTagBuilder add(final Tag value) { + public ListTagBuilder add(final Tag value) + { checkNotNull(value); - if (!this.type.isInstance(value)) { - throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + this.type.getCanonicalName()); - } - this.entries.add(value); + if (!type.isInstance(value)) { throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName()); } + entries.add(value); return this; } @@ -84,9 +84,11 @@ public class ListTagBuilder { * * @return this object */ - public ListTagBuilder addAll(final Collection value) { + public ListTagBuilder addAll(final Collection value) + { checkNotNull(value); - for (final Tag v : value) { + for (final Tag v : value) + { add(v); } return this; @@ -97,8 +99,9 @@ public class ListTagBuilder { * * @return the new list tag */ - public ListTag build() { - return new ListTag(this.type, new ArrayList(this.entries)); + public ListTag build() + { + return new ListTag(type, new ArrayList(entries)); } /** @@ -108,7 +111,8 @@ public class ListTagBuilder { * * @return the created list tag */ - public ListTag build(final String name) { - return new ListTag(name, this.type, new ArrayList(this.entries)); + public ListTag build(final String name) + { + return new ListTag(name, type, new ArrayList(entries)); } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/LongTag.java b/src/main/java/com/intellectualcrafters/jnbt/LongTag.java index 0473c075d..f4e53f558 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/LongTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/LongTag.java @@ -3,7 +3,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Long} tag. */ -public final class LongTag extends Tag { +public final class LongTag extends Tag +{ private final long value; /** @@ -11,7 +12,8 @@ public final class LongTag extends Tag { * * @param value the value of the tag */ - public LongTag(final long value) { + public LongTag(final long value) + { super(); this.value = value; } @@ -22,23 +24,27 @@ public final class LongTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public LongTag(final String name, final long value) { + public LongTag(final String name, final long value) + { super(name); this.value = value; } @Override - public Long getValue() { - return this.value; + public Long getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_Long" + append + ": " + this.value; + return "TAG_Long" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java b/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java index 891345802..57f431dbf 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java @@ -25,15 +25,17 @@ import java.nio.charset.Charset; /** * A class which holds constant values. */ -public final class NBTConstants { +public final class NBTConstants +{ public static final Charset CHARSET = Charset.forName("UTF-8"); - public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11; + public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, + TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11; /** * Default private constructor. */ - private NBTConstants() { - } + private NBTConstants() + {} /** * Convert a type ID to its corresponding {@link Tag} class. @@ -44,8 +46,10 @@ public final class NBTConstants { * * @throws IllegalArgumentException thrown if the tag ID is not valid */ - public static Class getClassFromType(final int id) { - switch (id) { + public static Class getClassFromType(final int id) + { + switch (id) + { case TYPE_END: return EndTag.class; case TYPE_BYTE: diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java b/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java index 2b5981b92..fce72a74b 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java @@ -14,11 +14,12 @@ import java.util.Map; * subclasses of the {@code Tag} object. The NBT format was created by Markus Persson, and the specification * may be found at @linktourl http://www.minecraft.net/docs/NBT.txt"> http://www.minecraft.net/docs/NBT.txt. */ -public final class NBTInputStream implements Closeable { +public final class NBTInputStream implements Closeable +{ private final DataInputStream is; private int count; - + /** * Creates a new {@code NBTInputStream}, which will source its data from the specified input stream. * @@ -26,7 +27,8 @@ public final class NBTInputStream implements Closeable { * * @throws IOException if an I/O error occurs */ - public NBTInputStream(final InputStream is) throws IOException { + public NBTInputStream(final InputStream is) throws IOException + { this.is = new DataInputStream(is); } @@ -37,10 +39,11 @@ public final class NBTInputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - public Tag readTag() throws IOException { + public Tag readTag() throws IOException + { return readTag(0, Integer.MAX_VALUE); } - + /** * Reads an NBT tag from the stream. * @@ -48,7 +51,8 @@ public final class NBTInputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - public Tag readTag(int maxDepth) throws IOException { + public Tag readTag(final int maxDepth) throws IOException + { return readTag(0, maxDepth); } @@ -61,16 +65,20 @@ public final class NBTInputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private Tag readTag(final int depth, int maxDepth) throws IOException { - if ((count++) > maxDepth) throw new IOException("Exceeds max depth: " + count); - final int type = this.is.readByte() & 0xFF; + private Tag readTag(final int depth, final int maxDepth) throws IOException + { + if ((count++) > maxDepth) { throw new IOException("Exceeds max depth: " + count); } + final int type = is.readByte() & 0xFF; String name; - if (type != NBTConstants.TYPE_END) { - final int nameLength = this.is.readShort() & 0xFFFF; + if (type != NBTConstants.TYPE_END) + { + final int nameLength = is.readShort() & 0xFFFF; final byte[] nameBytes = new byte[nameLength]; - this.is.readFully(nameBytes); + is.readFully(nameBytes); name = new String(nameBytes, NBTConstants.CHARSET); - } else { + } + else + { name = ""; } return readTagPayload(type, name, depth, maxDepth); @@ -87,84 +95,96 @@ public final class NBTInputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private Tag readTagPayload(final int type, final String name, final int depth, int maxDepth) throws IOException { - if ((count++) > maxDepth) throw new IOException("Exceeds max depth: " + count); + private Tag readTagPayload(final int type, final String name, final int depth, final int maxDepth) throws IOException + { + if ((count++) > maxDepth) { throw new IOException("Exceeds max depth: " + count); } count++; - switch (type) { + switch (type) + { case NBTConstants.TYPE_END: - if (depth == 0) { + if (depth == 0) + { throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it."); - } else { + } + else + { return new EndTag(); } case NBTConstants.TYPE_BYTE: - return new ByteTag(name, this.is.readByte()); + return new ByteTag(name, is.readByte()); case NBTConstants.TYPE_SHORT: - return new ShortTag(name, this.is.readShort()); + return new ShortTag(name, is.readShort()); case NBTConstants.TYPE_INT: - return new IntTag(name, this.is.readInt()); + return new IntTag(name, is.readInt()); case NBTConstants.TYPE_LONG: - return new LongTag(name, this.is.readLong()); + return new LongTag(name, is.readLong()); case NBTConstants.TYPE_FLOAT: - return new FloatTag(name, this.is.readFloat()); + return new FloatTag(name, is.readFloat()); case NBTConstants.TYPE_DOUBLE: - return new DoubleTag(name, this.is.readDouble()); + return new DoubleTag(name, is.readDouble()); case NBTConstants.TYPE_BYTE_ARRAY: - int length = this.is.readInt(); - + int length = is.readInt(); + // Max depth - if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count); + if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count); // - + } + byte[] bytes = new byte[length]; - this.is.readFully(bytes); + is.readFully(bytes); return new ByteArrayTag(name, bytes); case NBTConstants.TYPE_STRING: - length = this.is.readShort(); - + length = is.readShort(); + // Max depth - if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count); + if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count); // - + } + bytes = new byte[length]; - this.is.readFully(bytes); + is.readFully(bytes); return new StringTag(name, new String(bytes, NBTConstants.CHARSET)); case NBTConstants.TYPE_LIST: - final int childType = this.is.readByte(); - length = this.is.readInt(); - + final int childType = is.readByte(); + length = is.readInt(); + // Max depth - if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count); + if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count); // - + } + final List tagList = new ArrayList(); - for (int i = 0; i < length; ++i) { + for (int i = 0; i < length; ++i) + { final Tag tag = readTagPayload(childType, "", depth + 1, maxDepth); - if (tag instanceof EndTag) { - throw new IOException("TAG_End not permitted in a list."); - } + if (tag instanceof EndTag) { throw new IOException("TAG_End not permitted in a list."); } tagList.add(tag); } return new ListTag(name, NBTUtils.getTypeClass(childType), tagList); case NBTConstants.TYPE_COMPOUND: final Map tagMap = new HashMap(); - while (true) { + while (true) + { final Tag tag = readTag(depth + 1, maxDepth); - if (tag instanceof EndTag) { + if (tag instanceof EndTag) + { break; - } else { + } + else + { tagMap.put(tag.getName(), tag); } } return new CompoundTag(name, tagMap); case NBTConstants.TYPE_INT_ARRAY: - length = this.is.readInt(); + length = is.readInt(); // Max depth - if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count); + if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count); } // final int[] data = new int[length]; - for (int i = 0; i < length; i++) { - data[i] = this.is.readInt(); + for (int i = 0; i < length; i++) + { + data[i] = is.readInt(); } return new IntArrayTag(name, data); default: @@ -173,7 +193,8 @@ public final class NBTInputStream implements Closeable { } @Override - public void close() throws IOException { - this.is.close(); + public void close() throws IOException + { + is.close(); } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java index 54a6f895a..2a628aeab 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java @@ -29,13 +29,14 @@ import java.util.List; /** *

This class writes NBT, or Named Binary Tag Tag objects to an * underlying OutputStream.

The NBT format was created by Markus Persson, and the - * specification may be found at + * specification may be found at * @linktourl http://www.minecraft.net/docs/NBT.txt *

* * @author Graham Edgecombe */ -public final class NBTOutputStream implements Closeable { +public final class NBTOutputStream implements Closeable +{ /** * The output stream. */ @@ -48,7 +49,8 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - public NBTOutputStream(final OutputStream os) throws IOException { + public NBTOutputStream(final OutputStream os) throws IOException + { this.os = new DataOutputStream(os); } @@ -59,16 +61,15 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - public void writeTag(final Tag tag) throws IOException { + public void writeTag(final Tag tag) throws IOException + { final int type = NBTUtils.getTypeCode(tag.getClass()); final String name = tag.getName(); final byte[] nameBytes = name.getBytes(NBTConstants.CHARSET); - this.os.writeByte(type); - this.os.writeShort(nameBytes.length); - this.os.write(nameBytes); - if (type == NBTConstants.TYPE_END) { - throw new IOException("Named TAG_End not permitted."); - } + os.writeByte(type); + os.writeShort(nameBytes.length); + os.write(nameBytes); + if (type == NBTConstants.TYPE_END) { throw new IOException("Named TAG_End not permitted."); } writeTagPayload(tag); } @@ -79,9 +80,11 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeTagPayload(final Tag tag) throws IOException { + private void writeTagPayload(final Tag tag) throws IOException + { final int type = NBTUtils.getTypeCode(tag.getClass()); - switch (type) { + switch (type) + { case NBTConstants.TYPE_END: writeEndTagPayload((EndTag) tag); break; @@ -130,8 +133,9 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeByteTagPayload(final ByteTag tag) throws IOException { - this.os.writeByte(tag.getValue()); + private void writeByteTagPayload(final ByteTag tag) throws IOException + { + os.writeByte(tag.getValue()); } /** @@ -141,10 +145,11 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException { + private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException + { final byte[] bytes = tag.getValue(); - this.os.writeInt(bytes.length); - this.os.write(bytes); + os.writeInt(bytes.length); + os.write(bytes); } /** @@ -154,11 +159,13 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeCompoundTagPayload(final CompoundTag tag) throws IOException { - for (final Tag childTag : tag.getValue().values()) { + private void writeCompoundTagPayload(final CompoundTag tag) throws IOException + { + for (final Tag childTag : tag.getValue().values()) + { writeTag(childTag); } - this.os.writeByte((byte) 0); // end tag - better way? + os.writeByte((byte) 0); // end tag - better way? } /** @@ -168,13 +175,15 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeListTagPayload(final ListTag tag) throws IOException { + private void writeListTagPayload(final ListTag tag) throws IOException + { final Class clazz = tag.getType(); final List tags = tag.getValue(); final int size = tags.size(); - this.os.writeByte(NBTUtils.getTypeCode(clazz)); - this.os.writeInt(size); - for (final Tag tag1 : tags) { + os.writeByte(NBTUtils.getTypeCode(clazz)); + os.writeInt(size); + for (final Tag tag1 : tags) + { writeTagPayload(tag1); } } @@ -186,10 +195,11 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeStringTagPayload(final StringTag tag) throws IOException { + private void writeStringTagPayload(final StringTag tag) throws IOException + { final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET); - this.os.writeShort(bytes.length); - this.os.write(bytes); + os.writeShort(bytes.length); + os.write(bytes); } /** @@ -199,8 +209,9 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeDoubleTagPayload(final DoubleTag tag) throws IOException { - this.os.writeDouble(tag.getValue()); + private void writeDoubleTagPayload(final DoubleTag tag) throws IOException + { + os.writeDouble(tag.getValue()); } /** @@ -210,8 +221,9 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeFloatTagPayload(final FloatTag tag) throws IOException { - this.os.writeFloat(tag.getValue()); + private void writeFloatTagPayload(final FloatTag tag) throws IOException + { + os.writeFloat(tag.getValue()); } /** @@ -221,8 +233,9 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeLongTagPayload(final LongTag tag) throws IOException { - this.os.writeLong(tag.getValue()); + private void writeLongTagPayload(final LongTag tag) throws IOException + { + os.writeLong(tag.getValue()); } /** @@ -232,8 +245,9 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeIntTagPayload(final IntTag tag) throws IOException { - this.os.writeInt(tag.getValue()); + private void writeIntTagPayload(final IntTag tag) throws IOException + { + os.writeInt(tag.getValue()); } /** @@ -243,8 +257,9 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeShortTagPayload(final ShortTag tag) throws IOException { - this.os.writeShort(tag.getValue()); + private void writeShortTagPayload(final ShortTag tag) throws IOException + { + os.writeShort(tag.getValue()); } /** @@ -254,28 +269,33 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - private void writeEndTagPayload(final EndTag tag) { + private void writeEndTagPayload(final EndTag tag) + { /* empty */ } - private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException { + private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException + { final int[] data = tag.getValue(); - this.os.writeInt(data.length); - for (final int element : data) { - this.os.writeInt(element); + os.writeInt(data.length); + for (final int element : data) + { + os.writeInt(element); } } @Override - public void close() throws IOException { - this.os.close(); + public void close() throws IOException + { + os.close(); } /** * Flush output - * @throws IOException + * @throws IOException */ - public void flush() throws IOException { - this.os.flush(); + public void flush() throws IOException + { + os.flush(); } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java b/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java index 06b23b22c..a130d525e 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java @@ -5,12 +5,13 @@ import java.util.Map; /** * A class which contains NBT-related utility methods. */ -public final class NBTUtils { +public final class NBTUtils +{ /** * Default private constructor. */ - private NBTUtils() { - } + private NBTUtils() + {} /** * Gets the type name of a tag. @@ -19,32 +20,58 @@ public final class NBTUtils { * * @return The type name. */ - public static String getTypeName(final Class clazz) { - if (clazz.equals(ByteArrayTag.class)) { + public static String getTypeName(final Class clazz) + { + if (clazz.equals(ByteArrayTag.class)) + { return "TAG_Byte_Array"; - } else if (clazz.equals(ByteTag.class)) { + } + else if (clazz.equals(ByteTag.class)) + { return "TAG_Byte"; - } else if (clazz.equals(CompoundTag.class)) { + } + else if (clazz.equals(CompoundTag.class)) + { return "TAG_Compound"; - } else if (clazz.equals(DoubleTag.class)) { + } + else if (clazz.equals(DoubleTag.class)) + { return "TAG_Double"; - } else if (clazz.equals(EndTag.class)) { + } + else if (clazz.equals(EndTag.class)) + { return "TAG_End"; - } else if (clazz.equals(FloatTag.class)) { + } + else if (clazz.equals(FloatTag.class)) + { return "TAG_Float"; - } else if (clazz.equals(IntTag.class)) { + } + else if (clazz.equals(IntTag.class)) + { return "TAG_Int"; - } else if (clazz.equals(ListTag.class)) { + } + else if (clazz.equals(ListTag.class)) + { return "TAG_List"; - } else if (clazz.equals(LongTag.class)) { + } + else if (clazz.equals(LongTag.class)) + { return "TAG_Long"; - } else if (clazz.equals(ShortTag.class)) { + } + else if (clazz.equals(ShortTag.class)) + { return "TAG_Short"; - } else if (clazz.equals(StringTag.class)) { + } + else if (clazz.equals(StringTag.class)) + { return "TAG_String"; - } else if (clazz.equals(IntArrayTag.class)) { + } + else if (clazz.equals(IntArrayTag.class)) + { return "TAG_Int_Array"; - } else { + } + else + { throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ")."); } } @@ -58,32 +85,58 @@ public final class NBTUtils { * * @throws IllegalArgumentException if the tag class is invalid. */ - public static int getTypeCode(final Class clazz) { - if (clazz.equals(ByteArrayTag.class)) { + public static int getTypeCode(final Class clazz) + { + if (clazz.equals(ByteArrayTag.class)) + { return NBTConstants.TYPE_BYTE_ARRAY; - } else if (clazz.equals(ByteTag.class)) { + } + else if (clazz.equals(ByteTag.class)) + { return NBTConstants.TYPE_BYTE; - } else if (clazz.equals(CompoundTag.class)) { + } + else if (clazz.equals(CompoundTag.class)) + { return NBTConstants.TYPE_COMPOUND; - } else if (clazz.equals(DoubleTag.class)) { + } + else if (clazz.equals(DoubleTag.class)) + { return NBTConstants.TYPE_DOUBLE; - } else if (clazz.equals(EndTag.class)) { + } + else if (clazz.equals(EndTag.class)) + { return NBTConstants.TYPE_END; - } else if (clazz.equals(FloatTag.class)) { + } + else if (clazz.equals(FloatTag.class)) + { return NBTConstants.TYPE_FLOAT; - } else if (clazz.equals(IntTag.class)) { + } + else if (clazz.equals(IntTag.class)) + { return NBTConstants.TYPE_INT; - } else if (clazz.equals(ListTag.class)) { + } + else if (clazz.equals(ListTag.class)) + { return NBTConstants.TYPE_LIST; - } else if (clazz.equals(LongTag.class)) { + } + else if (clazz.equals(LongTag.class)) + { return NBTConstants.TYPE_LONG; - } else if (clazz.equals(ShortTag.class)) { + } + else if (clazz.equals(ShortTag.class)) + { return NBTConstants.TYPE_SHORT; - } else if (clazz.equals(StringTag.class)) { + } + else if (clazz.equals(StringTag.class)) + { return NBTConstants.TYPE_STRING; - } else if (clazz.equals(IntArrayTag.class)) { + } + else if (clazz.equals(IntArrayTag.class)) + { return NBTConstants.TYPE_INT_ARRAY; - } else { + } + else + { throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ")."); } } @@ -97,8 +150,10 @@ public final class NBTUtils { * * @throws IllegalArgumentException if the tag type is invalid. */ - public static Class getTypeClass(final int type) { - switch (type) { + public static Class getTypeClass(final int type) + { + switch (type) + { case NBTConstants.TYPE_END: return EndTag.class; case NBTConstants.TYPE_BYTE: @@ -138,14 +193,11 @@ public final class NBTUtils { * * @return child tag */ - public static T getChildTag(final Map items, final String key, final Class expected) throws IllegalArgumentException { - if (!items.containsKey(key)) { - throw new IllegalArgumentException("Missing a \"" + key + "\" tag"); - } + public static T getChildTag(final Map items, final String key, final Class expected) throws IllegalArgumentException + { + if (!items.containsKey(key)) { throw new IllegalArgumentException("Missing a \"" + key + "\" tag"); } final Tag tag = items.get(key); - if (!expected.isInstance(tag)) { - throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName()); - } + if (!expected.isInstance(tag)) { throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName()); } return expected.cast(tag); } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java b/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java index 5f3b7ec6d..34a1adf9a 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java @@ -23,7 +23,8 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Short} tag. */ -public final class ShortTag extends Tag { +public final class ShortTag extends Tag +{ private final short value; /** @@ -31,7 +32,8 @@ public final class ShortTag extends Tag { * * @param value the value of the tag */ - public ShortTag(final short value) { + public ShortTag(final short value) + { super(); this.value = value; } @@ -42,23 +44,27 @@ public final class ShortTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public ShortTag(final String name, final short value) { + public ShortTag(final String name, final short value) + { super(name); this.value = value; } @Override - public Short getValue() { - return this.value; + public Short getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_Short" + append + ": " + this.value; + return "TAG_Short" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/StringTag.java b/src/main/java/com/intellectualcrafters/jnbt/StringTag.java index cb50376a8..e69a75bcc 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/StringTag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/StringTag.java @@ -5,7 +5,8 @@ import static com.google.common.base.Preconditions.checkNotNull; /** * The {@code TAG_String} tag. */ -public final class StringTag extends Tag { +public final class StringTag extends Tag +{ private final String value; /** @@ -13,7 +14,8 @@ public final class StringTag extends Tag { * * @param value the value of the tag */ - public StringTag(final String value) { + public StringTag(final String value) + { super(); checkNotNull(value); this.value = value; @@ -25,24 +27,28 @@ public final class StringTag extends Tag { * @param name the name of the tag * @param value the value of the tag */ - public StringTag(final String name, final String value) { + public StringTag(final String name, final String value) + { super(name); checkNotNull(value); this.value = value; } @Override - public String getValue() { - return this.value; + public String getValue() + { + return value; } @Override - public String toString() { + public String toString() + { final String name = getName(); String append = ""; - if ((name != null) && !name.equals("")) { - append = "(\"" + this.getName() + "\")"; + if ((name != null) && !name.equals("")) + { + append = "(\"" + getName() + "\")"; } - return "TAG_String" + append + ": " + this.value; + return "TAG_String" + append + ": " + value; } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/Tag.java b/src/main/java/com/intellectualcrafters/jnbt/Tag.java index 6fce19169..0c50682ba 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/Tag.java +++ b/src/main/java/com/intellectualcrafters/jnbt/Tag.java @@ -23,13 +23,15 @@ package com.intellectualcrafters.jnbt; /** * Represents a NBT tag. */ -public abstract class Tag { +public abstract class Tag +{ private final String name; /** * Create a new tag with an empty name. */ - Tag() { + Tag() + { this(""); } @@ -38,8 +40,10 @@ public abstract class Tag { * * @param name the name */ - Tag(String name) { - if (name == null) { + Tag(String name) + { + if (name == null) + { name = ""; } this.name = name; @@ -50,8 +54,9 @@ public abstract class Tag { * * @return the name of this tag */ - public final String getName() { - return this.name; + public final String getName() + { + return name; } /** diff --git a/src/main/java/com/intellectualcrafters/json/CDL.java b/src/main/java/com/intellectualcrafters/json/CDL.java index fb69ce28b..0704da569 100644 --- a/src/main/java/com/intellectualcrafters/json/CDL.java +++ b/src/main/java/com/intellectualcrafters/json/CDL.java @@ -4,20 +4,21 @@ package com.intellectualcrafters.json; * This provides static methods to convert comma delimited text into a JSONArray, and to covert a JSONArray into comma * delimited text. Comma delimited text is a very popular format for data interchange. It is understood by most * database, spreadsheet, and organizer programs. - * + * * Each row of text represents a row in a table or a data record. Each row ends with a NEWLINE character. Each row * contains one or more values. Values are separated by commas. A value can contain any character except for comma, * unless is is wrapped in single quotes or double quotes. - * + * * The first row usually contains the names of the columns. - * + * * A comma delimited list can be converted into a JSONArray of JSONObjects. The names for the elements in the * JSONObjects can be taken from the names in the first row. * * @author JSON.org * @version 2014-05-03 */ -public class CDL { +public class CDL +{ /** * Get the next value. The value can be wrapped in quotes. The value can be empty. * @@ -27,28 +28,32 @@ public class CDL { * * @throws JSONException if the quoted string is badly formed. */ - private static String getValue(final JSONTokener x) throws JSONException { + private static String getValue(final JSONTokener x) throws JSONException + { char c; char q; StringBuffer sb; - do { + do + { c = x.next(); - } while ((c == ' ') || (c == '\t')); - switch (c) { + } + while ((c == ' ') || (c == '\t')); + switch (c) + { case 0: return null; case '"': case '\'': q = c; sb = new StringBuffer(); - for (;;) { + for (;;) + { c = x.next(); - if (c == q) { + if (c == q) + { break; } - if ((c == 0) || (c == '\n') || (c == '\r')) { - throw x.syntaxError("Missing close quote '" + q + "'."); - } + if ((c == 0) || (c == '\n') || (c == '\r')) { throw x.syntaxError("Missing close quote '" + q + "'."); } sb.append(c); } return sb.toString(); @@ -70,23 +75,24 @@ public class CDL { * * @throws JSONException */ - public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException { + public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException + { final JSONArray ja = new JSONArray(); - for (;;) { + for (;;) + { final String value = getValue(x); char c = x.next(); - if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) { - return null; - } + if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) { return null; } ja.put(value); - for (;;) { - if (c == ',') { + for (;;) + { + if (c == ',') + { break; } - if (c != ' ') { - if ((c == '\n') || (c == '\r') || (c == 0)) { - return ja; - } + if (c != ' ') + { + if ((c == '\n') || (c == '\r') || (c == 0)) { return ja; } throw x.syntaxError("Bad character '" + c + "' (" + (int) c + ")."); } c = x.next(); @@ -106,7 +112,8 @@ public class CDL { * * @throws JSONException */ - public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException { + public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException + { final JSONArray ja = rowToJSONArray(x); return ja != null ? ja.toJSONObject(names) : null; } @@ -119,26 +126,35 @@ public class CDL { * * @return A string ending in NEWLINE. */ - public static String rowToString(final JSONArray ja) { + public static String rowToString(final JSONArray ja) + { final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ja.length(); i += 1) { - if (i > 0) { + for (int i = 0; i < ja.length(); i += 1) + { + if (i > 0) + { sb.append(','); } final Object object = ja.opt(i); - if (object != null) { + if (object != null) + { final String string = object.toString(); - if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) { + if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) + { sb.append('"'); final int length = string.length(); - for (int j = 0; j < length; j += 1) { + for (int j = 0; j < length; j += 1) + { final char c = string.charAt(j); - if ((c >= ' ') && (c != '"')) { + if ((c >= ' ') && (c != '"')) + { sb.append(c); } } sb.append('"'); - } else { + } + else + { sb.append(string); } } @@ -156,7 +172,8 @@ public class CDL { * * @throws JSONException */ - public static JSONArray toJSONArray(final String string) throws JSONException { + public static JSONArray toJSONArray(final String string) throws JSONException + { return toJSONArray(new JSONTokener(string)); } @@ -169,7 +186,8 @@ public class CDL { * * @throws JSONException */ - public static JSONArray toJSONArray(final JSONTokener x) throws JSONException { + public static JSONArray toJSONArray(final JSONTokener x) throws JSONException + { return toJSONArray(rowToJSONArray(x), x); } @@ -184,7 +202,8 @@ public class CDL { * * @throws JSONException */ - public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException { + public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException + { return toJSONArray(names, new JSONTokener(string)); } @@ -199,21 +218,20 @@ public class CDL { * * @throws JSONException */ - public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException { - if ((names == null) || (names.length() == 0)) { - return null; - } + public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException + { + if ((names == null) || (names.length() == 0)) { return null; } final JSONArray ja = new JSONArray(); - for (;;) { + for (;;) + { final JSONObject jo = rowToJSONObject(names, x); - if (jo == null) { + if (jo == null) + { break; } ja.put(jo); } - if (ja.length() == 0) { - return null; - } + if (ja.length() == 0) { return null; } return ja; } @@ -227,13 +245,13 @@ public class CDL { * * @throws JSONException */ - public static String toString(final JSONArray ja) throws JSONException { + public static String toString(final JSONArray ja) throws JSONException + { final JSONObject jo = ja.optJSONObject(0); - if (jo != null) { + if (jo != null) + { final JSONArray names = jo.names(); - if (names != null) { - return rowToString(names) + toString(names, ja); - } + if (names != null) { return rowToString(names) + toString(names, ja); } } return null; } @@ -249,14 +267,15 @@ public class CDL { * * @throws JSONException */ - public static String toString(final JSONArray names, final JSONArray ja) throws JSONException { - if ((names == null) || (names.length() == 0)) { - return null; - } + public static String toString(final JSONArray names, final JSONArray ja) throws JSONException + { + if ((names == null) || (names.length() == 0)) { return null; } final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ja.length(); i += 1) { + for (int i = 0; i < ja.length(); i += 1) + { final JSONObject jo = ja.optJSONObject(i); - if (jo != null) { + if (jo != null) + { sb.append(rowToString(jo.toJSONArray(names))); } } diff --git a/src/main/java/com/intellectualcrafters/json/Cookie.java b/src/main/java/com/intellectualcrafters/json/Cookie.java index 13a11c597..52f90895d 100644 --- a/src/main/java/com/intellectualcrafters/json/Cookie.java +++ b/src/main/java/com/intellectualcrafters/json/Cookie.java @@ -27,7 +27,8 @@ package com.intellectualcrafters.json; * @author JSON.org * @version 2014-05-03 */ -public class Cookie { +public class Cookie +{ /** * Produce a copy of a string in which the characters '+', '%', '=', ';' and control characters are replaced with * "%hh". This is a gentle form of URL encoding, attempting to cause as little distortion to the string as possible. @@ -39,18 +40,23 @@ public class Cookie { * * @return The escaped result. */ - public static String escape(final String string) { + public static String escape(final String string) + { char c; final String s = string.trim(); final int length = s.length(); final StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; i += 1) { + for (int i = 0; i < length; i += 1) + { c = s.charAt(i); - if ((c < ' ') || (c == '+') || (c == '%') || (c == '=') || (c == ';')) { + if ((c < ' ') || (c == '+') || (c == '%') || (c == '=') || (c == ';')) + { sb.append('%'); sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char) (c & 0x0f), 16)); - } else { + } + else + { sb.append(c); } } @@ -71,7 +77,8 @@ public class Cookie { * * @throws JSONException */ - public static JSONObject toJSONObject(final String string) throws JSONException { + public static JSONObject toJSONObject(final String string) throws JSONException + { String name; final JSONObject jo = new JSONObject(); Object value; @@ -80,15 +87,22 @@ public class Cookie { x.next('='); jo.put("value", x.nextTo(';')); x.next(); - while (x.more()) { + while (x.more()) + { name = unescape(x.nextTo("=;")); - if (x.next() != '=') { - if (name.equals("secure")) { + if (x.next() != '=') + { + if (name.equals("secure")) + { value = Boolean.TRUE; - } else { + } + else + { throw x.syntaxError("Missing '=' in cookie parameter."); } - } else { + } + else + { value = unescape(x.nextTo(';')); x.next(); } @@ -108,24 +122,29 @@ public class Cookie { * * @throws JSONException */ - public static String toString(final JSONObject jo) throws JSONException { + public static String toString(final JSONObject jo) throws JSONException + { final StringBuilder sb = new StringBuilder(); sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); - if (jo.has("expires")) { + if (jo.has("expires")) + { sb.append(";expires="); sb.append(jo.getString("expires")); } - if (jo.has("domain")) { + if (jo.has("domain")) + { sb.append(";domain="); sb.append(escape(jo.getString("domain"))); } - if (jo.has("path")) { + if (jo.has("path")) + { sb.append(";path="); sb.append(escape(jo.getString("path"))); } - if (jo.optBoolean("secure")) { + if (jo.optBoolean("secure")) + { sb.append(";secure"); } return sb.toString(); @@ -139,17 +158,23 @@ public class Cookie { * * @return The unescaped string. */ - public static String unescape(final String string) { + public static String unescape(final String string) + { final int length = string.length(); final StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; ++i) { + for (int i = 0; i < length; ++i) + { char c = string.charAt(i); - if (c == '+') { + if (c == '+') + { c = ' '; - } else if ((c == '%') && ((i + 2) < length)) { + } + else if ((c == '%') && ((i + 2) < length)) + { final int d = JSONTokener.dehexchar(string.charAt(i + 1)); final int e = JSONTokener.dehexchar(string.charAt(i + 2)); - if ((d >= 0) && (e >= 0)) { + if ((d >= 0) && (e >= 0)) + { c = (char) ((d * 16) + e); i += 2; } diff --git a/src/main/java/com/intellectualcrafters/json/CookieList.java b/src/main/java/com/intellectualcrafters/json/CookieList.java index 85553dc13..add20262f 100644 --- a/src/main/java/com/intellectualcrafters/json/CookieList.java +++ b/src/main/java/com/intellectualcrafters/json/CookieList.java @@ -8,12 +8,13 @@ import java.util.Iterator; * @author JSON.org * @version 2014-05-03 */ -public class CookieList { +public class CookieList +{ /** * Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated * from the values by '='. The pairs are separated by ';'. The names and the values will be unescaped, possibly * converting '+' and '%' sequences. - * + * * To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * @@ -23,10 +24,12 @@ public class CookieList { * * @throws JSONException */ - public static JSONObject toJSONObject(final String string) throws JSONException { + public static JSONObject toJSONObject(final String string) throws JSONException + { final JSONObject jo = new JSONObject(); final JSONTokener x = new JSONTokener(string); - while (x.more()) { + while (x.more()) + { final String name = Cookie.unescape(x.nextTo('=')); x.next('='); jo.put(name, Cookie.unescape(x.nextTo(';'))); @@ -46,15 +49,19 @@ public class CookieList { * * @throws JSONException */ - public static String toString(final JSONObject jo) throws JSONException { + public static String toString(final JSONObject jo) throws JSONException + { boolean b = false; final Iterator keys = jo.keys(); String string; final StringBuilder sb = new StringBuilder(); - while (keys.hasNext()) { + while (keys.hasNext()) + { string = keys.next(); - if (!jo.isNull(string)) { - if (b) { + if (!jo.isNull(string)) + { + if (b) + { sb.append(';'); } sb.append(Cookie.escape(string)); diff --git a/src/main/java/com/intellectualcrafters/json/HTTP.java b/src/main/java/com/intellectualcrafters/json/HTTP.java index 2e5f2b763..01d5e26e9 100644 --- a/src/main/java/com/intellectualcrafters/json/HTTP.java +++ b/src/main/java/com/intellectualcrafters/json/HTTP.java @@ -28,31 +28,37 @@ import java.util.Iterator; * @author JSON.org * @version 2014-05-03 */ -public class HTTP { +public class HTTP +{ /** * Carriage return/line feed. */ public static final String CRLF = "\r\n"; - public static JSONObject toJSONObject(final String string) throws JSONException { + public static JSONObject toJSONObject(final String string) throws JSONException + { final JSONObject jo = new JSONObject(); final HTTPTokener x = new HTTPTokener(string); String token; token = x.nextToken(); - if (token.toUpperCase().startsWith("HTTP")) { + if (token.toUpperCase().startsWith("HTTP")) + { // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); - } else { + } + else + { // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } // Fields - while (x.more()) { + while (x.more()) + { final String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); @@ -63,8 +69,8 @@ public class HTTP { /** * Convert a JSONObject into an HTTP header. A request header must contain - * - * + * + * *
      * {
      *    Method: "POST" (for example),
@@ -72,10 +78,10 @@ public class HTTP {
      *    "HTTP-Version": "HTTP/1.1" (for example)
      * }
      * 
- * + * * A response header must contain - * - * + * + * *
      * {
      *    "HTTP-Version": "HTTP/1.1" (for example),
@@ -83,7 +89,7 @@ public class HTTP {
      *    "Reason-Phrase": "OK" (for example)
      * }
      * 
- * + * * Any other members of the JSONObject will be output as HTTP fields. The result will end with two CRLF pairs. * * @param jo A JSONObject @@ -92,17 +98,21 @@ public class HTTP { * * @throws JSONException if the object does not contain enough information. */ - public static String toString(final JSONObject jo) throws JSONException { + public static String toString(final JSONObject jo) throws JSONException + { final Iterator keys = jo.keys(); String string; final StringBuilder sb = new StringBuilder(); - if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { + if (jo.has("Status-Code") && jo.has("Reason-Phrase")) + { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); - } else if (jo.has("Method") && jo.has("Request-URI")) { + } + else if (jo.has("Method") && jo.has("Request-URI")) + { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); @@ -110,13 +120,17 @@ public class HTTP { sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); - } else { + } + else + { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); - while (keys.hasNext()) { + while (keys.hasNext()) + { string = keys.next(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) + { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); diff --git a/src/main/java/com/intellectualcrafters/json/HTTPTokener.java b/src/main/java/com/intellectualcrafters/json/HTTPTokener.java index d6bb2cf1e..ad99eae1d 100644 --- a/src/main/java/com/intellectualcrafters/json/HTTPTokener.java +++ b/src/main/java/com/intellectualcrafters/json/HTTPTokener.java @@ -6,13 +6,15 @@ package com.intellectualcrafters.json; * @author JSON.org * @version 2014-05-03 */ -public class HTTPTokener extends JSONTokener { +public class HTTPTokener extends JSONTokener +{ /** * Construct an HTTPTokener from a string. * * @param string A source string. */ - public HTTPTokener(final String string) { + public HTTPTokener(final String string) + { super(string); } @@ -23,30 +25,30 @@ public class HTTPTokener extends JSONTokener { * * @throws JSONException */ - public String nextToken() throws JSONException { + public String nextToken() throws JSONException + { char c; char q; final StringBuilder sb = new StringBuilder(); - do { + do + { c = next(); - } while (Character.isWhitespace(c)); - if ((c == '"') || (c == '\'')) { + } + while (Character.isWhitespace(c)); + if ((c == '"') || (c == '\'')) + { q = c; - for (;;) { + for (;;) + { c = next(); - if (c < ' ') { - throw syntaxError("Unterminated string."); - } - if (c == q) { - return sb.toString(); - } + if (c < ' ') { throw syntaxError("Unterminated string."); } + if (c == q) { return sb.toString(); } sb.append(c); } } - for (;;) { - if ((c == 0) || Character.isWhitespace(c)) { - return sb.toString(); - } + for (;;) + { + if ((c == 0) || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } diff --git a/src/main/java/com/intellectualcrafters/json/JSONArray.java b/src/main/java/com/intellectualcrafters/json/JSONArray.java index c31b44653..64711cea6 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONArray.java +++ b/src/main/java/com/intellectualcrafters/json/JSONArray.java @@ -34,16 +34,16 @@ import java.util.Map; * accessing the values by index, and put methods for adding or replacing values. The values can be any of * these types: Boolean, JSONArray, JSONObject, Number, * String, or the JSONObject.NULL object. - * + * * The constructor can convert a JSON text into a Java object. The toString method converts to JSON text. - * + * * A get method returns a value if one can be found, and throws an exception if one cannot be found. An * opt method returns a default value instead of throwing an exception, and so is useful for obtaining * optional values. - * + * * The generic get() and opt() methods return an object which you can cast or query for type. * There are also typed get and opt methods that do type checking and type coercion for you. - * + * * The texts produced by the toString methods strictly conform to JSON syntax rules. The constructors are * more forgiving in the texts they will accept:
  • An extra , (comma) may appear * just before the closing bracket.
  • The null value will be inserted when there is , @@ -56,7 +56,8 @@ import java.util.Map; * @author JSON.org * @version 2014-05-03 */ -public class JSONArray { +public class JSONArray +{ /** * The arrayList where the JSONArray's properties are kept. */ @@ -65,8 +66,9 @@ public class JSONArray { /** * Construct an empty JSONArray. */ - public JSONArray() { - this.myArrayList = new ArrayList(); + public JSONArray() + { + myArrayList = new ArrayList(); } /** @@ -76,26 +78,29 @@ public class JSONArray { * * @throws JSONException If there is a syntax error. */ - public JSONArray(final JSONTokener x) throws JSONException { + public JSONArray(final JSONTokener x) throws JSONException + { this(); - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() != ']') { + if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } + if (x.nextClean() != ']') + { x.back(); - for (;;) { - if (x.nextClean() == ',') { + for (;;) + { + if (x.nextClean() == ',') + { x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); + myArrayList.add(JSONObject.NULL); } - switch (x.nextClean()) { + else + { + x.back(); + myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) + { case ',': - if (x.nextClean() == ']') { - return; - } + if (x.nextClean() == ']') { return; } x.back(); break; case ']': @@ -115,7 +120,8 @@ public class JSONArray { * * @throws JSONException If there is a syntax error. */ - public JSONArray(final String source) throws JSONException { + public JSONArray(final String source) throws JSONException + { this(new JSONTokener(source)); } @@ -124,11 +130,14 @@ public class JSONArray { * * @param collection A Collection. */ - public JSONArray(final Collection collection) { - this.myArrayList = new ArrayList(); - if (collection != null) { - for (final Object aCollection : collection) { - this.myArrayList.add(JSONObject.wrap(aCollection)); + public JSONArray(final Collection collection) + { + myArrayList = new ArrayList(); + if (collection != null) + { + for (final Object aCollection : collection) + { + myArrayList.add(JSONObject.wrap(aCollection)); } } } @@ -138,14 +147,19 @@ public class JSONArray { * * @throws JSONException If not an array. */ - public JSONArray(final Object array) throws JSONException { + public JSONArray(final Object array) throws JSONException + { this(); - if (array.getClass().isArray()) { + if (array.getClass().isArray()) + { final int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { + for (int i = 0; i < length; i += 1) + { this.put(JSONObject.wrap(Array.get(array, i))); } - } else { + } + else + { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } @@ -159,11 +173,10 @@ public class JSONArray { * * @throws JSONException If there is no value for the index. */ - public Object get(final int index) throws JSONException { - final Object object = this.opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } + public Object get(final int index) throws JSONException + { + final Object object = opt(index); + if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return object; } @@ -176,13 +189,14 @@ public class JSONArray { * * @throws JSONException If there is no value for the index or if the value is not convertible to boolean. */ - public boolean getBoolean(final int index) throws JSONException { - final Object object = this.get(index); - if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { + public boolean getBoolean(final int index) throws JSONException + { + final Object object = get(index); + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) + { return false; - } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { - return true; } + else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } @@ -195,11 +209,15 @@ public class JSONArray { * * @throws JSONException If the key is not found or if the value cannot be converted to a number. */ - public double getDouble(final int index) throws JSONException { - final Object object = this.get(index); - try { + public double getDouble(final int index) throws JSONException + { + final Object object = get(index); + try + { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -213,11 +231,15 @@ public class JSONArray { * * @throws JSONException If the key is not found or if the value is not a number. */ - public int getInt(final int index) throws JSONException { - final Object object = this.get(index); - try { + public int getInt(final int index) throws JSONException + { + final Object object = get(index); + try + { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -231,11 +253,10 @@ public class JSONArray { * * @throws JSONException If there is no value for the index. or if the value is not a JSONArray */ - public JSONArray getJSONArray(final int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof JSONArray) { - return (JSONArray) object; - } + public JSONArray getJSONArray(final int index) throws JSONException + { + final Object object = get(index); + if (object instanceof JSONArray) { return (JSONArray) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } @@ -248,11 +269,10 @@ public class JSONArray { * * @throws JSONException If there is no value for the index or if the value is not a JSONObject */ - public JSONObject getJSONObject(final int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof JSONObject) { - return (JSONObject) object; - } + public JSONObject getJSONObject(final int index) throws JSONException + { + final Object object = get(index); + if (object instanceof JSONObject) { return (JSONObject) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } @@ -265,11 +285,15 @@ public class JSONArray { * * @throws JSONException If the key is not found or if the value cannot be converted to a number. */ - public long getLong(final int index) throws JSONException { - final Object object = this.get(index); - try { + public long getLong(final int index) throws JSONException + { + final Object object = get(index); + try + { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -283,11 +307,10 @@ public class JSONArray { * * @throws JSONException If there is no string value for the index. */ - public String getString(final int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof String) { - return (String) object; - } + public String getString(final int index) throws JSONException + { + final Object object = get(index); + if (object instanceof String) { return (String) object; } throw new JSONException("JSONArray[" + index + "] not a string."); } @@ -298,8 +321,9 @@ public class JSONArray { * * @return true if the value at the index is null, or if there is no value. */ - public boolean isNull(final int index) { - return JSONObject.NULL.equals(this.opt(index)); + public boolean isNull(final int index) + { + return JSONObject.NULL.equals(opt(index)); } /** @@ -312,14 +336,17 @@ public class JSONArray { * * @throws JSONException If the array contains an invalid number. */ - public String join(final String separator) throws JSONException { - final int len = this.length(); + public String join(final String separator) throws JSONException + { + final int len = length(); final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < len; i += 1) { - if (i > 0) { + for (int i = 0; i < len; i += 1) + { + if (i > 0) + { sb.append(separator); } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + sb.append(JSONObject.valueToString(myArrayList.get(i))); } return sb.toString(); } @@ -329,8 +356,9 @@ public class JSONArray { * * @return The length (or size). */ - public int length() { - return this.myArrayList.size(); + public int length() + { + return myArrayList.size(); } /** @@ -340,8 +368,9 @@ public class JSONArray { * * @return An object value, or null if there is no object at that index. */ - public Object opt(final int index) { - return ((index < 0) || (index >= this.length())) ? null : this.myArrayList.get(index); + public Object opt(final int index) + { + return ((index < 0) || (index >= length())) ? null : myArrayList.get(index); } /** @@ -352,7 +381,8 @@ public class JSONArray { * * @return The truth. */ - public boolean optBoolean(final int index) { + public boolean optBoolean(final int index) + { return this.optBoolean(index, false); } @@ -365,10 +395,14 @@ public class JSONArray { * * @return The truth. */ - public boolean optBoolean(final int index, final boolean defaultValue) { - try { - return this.getBoolean(index); - } catch (final Exception e) { + public boolean optBoolean(final int index, final boolean defaultValue) + { + try + { + return getBoolean(index); + } + catch (final Exception e) + { return defaultValue; } } @@ -381,7 +415,8 @@ public class JSONArray { * * @return The value. */ - public double optDouble(final int index) { + public double optDouble(final int index) + { return this.optDouble(index, Double.NaN); } @@ -394,10 +429,14 @@ public class JSONArray { * * @return The value. */ - public double optDouble(final int index, final double defaultValue) { - try { - return this.getDouble(index); - } catch (final Exception e) { + public double optDouble(final int index, final double defaultValue) + { + try + { + return getDouble(index); + } + catch (final Exception e) + { return defaultValue; } } @@ -410,7 +449,8 @@ public class JSONArray { * * @return The value. */ - public int optInt(final int index) { + public int optInt(final int index) + { return this.optInt(index, 0); } @@ -423,10 +463,14 @@ public class JSONArray { * * @return The value. */ - public int optInt(final int index, final int defaultValue) { - try { - return this.getInt(index); - } catch (final Exception e) { + public int optInt(final int index, final int defaultValue) + { + try + { + return getInt(index); + } + catch (final Exception e) + { return defaultValue; } } @@ -438,8 +482,9 @@ public class JSONArray { * * @return A JSONArray value, or null if the index has no value, or if the value is not a JSONArray. */ - public JSONArray optJSONArray(final int index) { - final Object o = this.opt(index); + public JSONArray optJSONArray(final int index) + { + final Object o = opt(index); return o instanceof JSONArray ? (JSONArray) o : null; } @@ -451,8 +496,9 @@ public class JSONArray { * * @return A JSONObject value. */ - public JSONObject optJSONObject(final int index) { - final Object o = this.opt(index); + public JSONObject optJSONObject(final int index) + { + final Object o = opt(index); return o instanceof JSONObject ? (JSONObject) o : null; } @@ -464,7 +510,8 @@ public class JSONArray { * * @return The value. */ - public long optLong(final int index) { + public long optLong(final int index) + { return this.optLong(index, 0); } @@ -477,10 +524,14 @@ public class JSONArray { * * @return The value. */ - public long optLong(final int index, final long defaultValue) { - try { - return this.getLong(index); - } catch (final Exception e) { + public long optLong(final int index, final long defaultValue) + { + try + { + return getLong(index); + } + catch (final Exception e) + { return defaultValue; } } @@ -493,7 +544,8 @@ public class JSONArray { * * @return A String value. */ - public String optString(final int index) { + public String optString(final int index) + { return this.optString(index, ""); } @@ -505,8 +557,9 @@ public class JSONArray { * * @return A String value. */ - public String optString(final int index, final String defaultValue) { - final Object object = this.opt(index); + public String optString(final int index, final String defaultValue) + { + final Object object = opt(index); return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); } @@ -517,7 +570,8 @@ public class JSONArray { * * @return this. */ - public JSONArray put(final boolean value) { + public JSONArray put(final boolean value) + { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -529,7 +583,8 @@ public class JSONArray { * * @return this. */ - public JSONArray put(final Collection value) { + public JSONArray put(final Collection value) + { this.put(new JSONArray(value)); return this; } @@ -543,7 +598,8 @@ public class JSONArray { * * @throws JSONException if the value is not finite. */ - public JSONArray put(final double value) throws JSONException { + public JSONArray put(final double value) throws JSONException + { final Double d = value; JSONObject.testValidity(d); this.put(d); @@ -557,7 +613,8 @@ public class JSONArray { * * @return this. */ - public JSONArray put(final int value) { + public JSONArray put(final int value) + { this.put(new Integer(value)); return this; } @@ -569,7 +626,8 @@ public class JSONArray { * * @return this. */ - public JSONArray put(final long value) { + public JSONArray put(final long value) + { this.put(new Long(value)); return this; } @@ -581,7 +639,8 @@ public class JSONArray { * * @return this. */ - public JSONArray put(final Map value) { + public JSONArray put(final Map value) + { this.put(new JSONObject(value)); return this; } @@ -594,8 +653,9 @@ public class JSONArray { * * @return this. */ - public JSONArray put(final Object value) { - this.myArrayList.add(value); + public JSONArray put(final Object value) + { + myArrayList.add(value); return this; } @@ -610,7 +670,8 @@ public class JSONArray { * * @throws JSONException If the index is negative. */ - public JSONArray put(final int index, final boolean value) throws JSONException { + public JSONArray put(final int index, final boolean value) throws JSONException + { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -625,7 +686,8 @@ public class JSONArray { * * @throws JSONException If the index is negative or if the value is not finite. */ - public JSONArray put(final int index, final Collection value) throws JSONException { + public JSONArray put(final int index, final Collection value) throws JSONException + { this.put(index, new JSONArray(value)); return this; } @@ -641,7 +703,8 @@ public class JSONArray { * * @throws JSONException If the index is negative or if the value is not finite. */ - public JSONArray put(final int index, final double value) throws JSONException { + public JSONArray put(final int index, final double value) throws JSONException + { this.put(index, new Double(value)); return this; } @@ -657,7 +720,8 @@ public class JSONArray { * * @throws JSONException If the index is negative. */ - public JSONArray put(final int index, final int value) throws JSONException { + public JSONArray put(final int index, final int value) throws JSONException + { this.put(index, new Integer(value)); return this; } @@ -673,7 +737,8 @@ public class JSONArray { * * @throws JSONException If the index is negative. */ - public JSONArray put(final int index, final long value) throws JSONException { + public JSONArray put(final int index, final long value) throws JSONException + { this.put(index, new Long(value)); return this; } @@ -688,7 +753,8 @@ public class JSONArray { * * @throws JSONException If the index is negative or if the the value is an invalid number. */ - public JSONArray put(final int index, final Map value) throws JSONException { + public JSONArray put(final int index, final Map value) throws JSONException + { this.put(index, new JSONObject(value)); return this; } @@ -705,15 +771,18 @@ public class JSONArray { * * @throws JSONException If the index is negative or if the the value is an invalid number. */ - public JSONArray put(final int index, final Object value) throws JSONException { + public JSONArray put(final int index, final Object value) throws JSONException + { JSONObject.testValidity(value); - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); + if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } + if (index < length()) + { + myArrayList.set(index, value); } - if (index < this.length()) { - this.myArrayList.set(index, value); - } else { - while (index != this.length()) { + else + { + while (index != length()) + { this.put(JSONObject.NULL); } this.put(value); @@ -728,8 +797,9 @@ public class JSONArray { * * @return The value that was associated with the index, or null if there was no value. */ - public Object remove(final int index) { - return (index >= 0) && (index < this.length()) ? this.myArrayList.remove(index) : null; + public Object remove(final int index) + { + return (index >= 0) && (index < length()) ? myArrayList.remove(index) : null; } /** @@ -739,28 +809,24 @@ public class JSONArray { * * @return true if they are equal */ - public boolean similar(final Object other) { - if (!(other instanceof JSONArray)) { - return false; - } - final int len = this.length(); - if (len != ((JSONArray) other).length()) { - return false; - } - for (int i = 0; i < len; i += 1) { - final Object valueThis = this.get(i); + public boolean similar(final Object other) + { + if (!(other instanceof JSONArray)) { return false; } + final int len = length(); + if (len != ((JSONArray) other).length()) { return false; } + for (int i = 0; i < len; i += 1) + { + final Object valueThis = get(i); final Object valueOther = ((JSONArray) other).get(i); - if (valueThis instanceof JSONObject) { - if (!((JSONObject) valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray) valueThis).similar(valueOther)) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; + if (valueThis instanceof JSONObject) + { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } } + else if (valueThis instanceof JSONArray) + { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } + } + else if (!valueThis.equals(valueOther)) { return false; } } return true; } @@ -774,13 +840,13 @@ public class JSONArray { * * @throws JSONException If any of the names are null. */ - public JSONObject toJSONObject(final JSONArray names) throws JSONException { - if ((names == null) || (names.length() == 0) || (this.length() == 0)) { - return null; - } + public JSONObject toJSONObject(final JSONArray names) throws JSONException + { + if ((names == null) || (names.length() == 0) || (length() == 0)) { return null; } final JSONObject jo = new JSONObject(); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); + for (int i = 0; i < names.length(); i += 1) + { + jo.put(names.getString(i), opt(i)); } return jo; } @@ -789,16 +855,20 @@ public class JSONArray { * Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to * produce a syntactically correct JSON text then null will be returned instead. This could occur if the array * contains an invalid number. - * + * * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the array. */ @Override - public String toString() { - try { + public String toString() + { + try + { return this.toString(0); - } catch (final Exception e) { + } + catch (final Exception e) + { return null; } } @@ -815,29 +885,32 @@ public class JSONArray { * * @throws JSONException */ - public String toString(final int indentFactor) throws JSONException { + public String toString(final int indentFactor) throws JSONException + { final StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { + synchronized (sw.getBuffer()) + { return this.write(sw, indentFactor, 0).toString(); } } /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. - * + * * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * * @throws JSONException */ - public Writer write(final Writer writer) throws JSONException { + public Writer write(final Writer writer) throws JSONException + { return this.write(writer, 0, 0); } /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. - * + * * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. @@ -847,34 +920,45 @@ public class JSONArray { * * @throws JSONException */ - Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { - try { + Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException + { + try + { boolean commanate = false; - final int length = this.length(); + final int length = length(); writer.write('['); - if (length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); - } else if (length != 0) { + if (length == 1) + { + JSONObject.writeValue(writer, myArrayList.get(0), indentFactor, indent); + } + else if (length != 0) + { final int newindent = indent + indentFactor; - for (int i = 0; i < length; i += 1) { - if (commanate) { + for (int i = 0; i < length; i += 1) + { + if (commanate) + { writer.write(','); } - if (indentFactor > 0) { + if (indentFactor > 0) + { writer.write('\n'); } JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); + JSONObject.writeValue(writer, myArrayList.get(i), indentFactor, newindent); commanate = true; } - if (indentFactor > 0) { + if (indentFactor > 0) + { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; - } catch (final IOException e) { + } + catch (final IOException e) + { throw new JSONException(e); } } diff --git a/src/main/java/com/intellectualcrafters/json/JSONException.java b/src/main/java/com/intellectualcrafters/json/JSONException.java index 090d4e4f7..b30bd7425 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONException.java +++ b/src/main/java/com/intellectualcrafters/json/JSONException.java @@ -6,7 +6,8 @@ package com.intellectualcrafters.json; * @author JSON.org * @version 2014-05-03 */ -public class JSONException extends RuntimeException { +public class JSONException extends RuntimeException +{ private static final long serialVersionUID = 0; private Throwable cause; @@ -15,7 +16,8 @@ public class JSONException extends RuntimeException { * * @param message Detail about the reason for the exception. */ - public JSONException(final String message) { + public JSONException(final String message) + { super(message); } @@ -24,7 +26,8 @@ public class JSONException extends RuntimeException { * * @param cause The cause. */ - public JSONException(final Throwable cause) { + public JSONException(final Throwable cause) + { super(cause.getMessage()); this.cause = cause; } @@ -35,7 +38,8 @@ public class JSONException extends RuntimeException { * @return the cause of this exception or null if the cause is nonexistent or unknown. */ @Override - public Throwable getCause() { - return this.cause; + public Throwable getCause() + { + return cause; } } diff --git a/src/main/java/com/intellectualcrafters/json/JSONML.java b/src/main/java/com/intellectualcrafters/json/JSONML.java index c63a5670b..0153d1e0c 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONML.java +++ b/src/main/java/com/intellectualcrafters/json/JSONML.java @@ -9,7 +9,8 @@ import java.util.Iterator; * @author JSON.org * @version 2014-05-03 */ -public class JSONML { +public class JSONML +{ /** * Parse XML values and store them in a JSONArray. * @@ -21,7 +22,8 @@ public class JSONML { * * @throws JSONException */ - private static Object parse(final XMLTokener x, final boolean arrayForm, final JSONArray ja) throws JSONException { + private static Object parse(final XMLTokener x, final boolean arrayForm, final JSONArray ja) throws JSONException + { String attribute; char c; String closeTag = null; @@ -35,149 +37,188 @@ public class JSONML { // // // - while (true) { - if (!x.more()) { - throw x.syntaxError("Bad XML"); - } + while (true) + { + if (!x.more()) { throw x.syntaxError("Bad XML"); } token = x.nextContent(); - if (token == XML.LT) { + if (token == XML.LT) + { token = x.nextToken(); - if (token instanceof Character) { - if (token == XML.SLASH) { + if (token instanceof Character) + { + if (token == XML.SLASH) + { // Close tag "); - } else { + } + else + { x.back(); } - } else if (c == '[') { + } + else if (c == '[') + { token = x.nextToken(); - if (token.equals("CDATA") && (x.next() == '[')) { - if (ja != null) { + if (token.equals("CDATA") && (x.next() == '[')) + { + if (ja != null) + { ja.put(x.nextCDATA()); } - } else { + } + else + { throw x.syntaxError("Expected 'CDATA['"); } - } else { + } + else + { i = 1; - do { + do + { token = x.nextMeta(); - if (token == null) { + if (token == null) + { throw x.syntaxError("Missing '>' after ' 0); + } + while (i > 0); } - } else if (token == XML.QUEST) { + } + else if (token == XML.QUEST) + { // "); - } else { + } + else + { throw x.syntaxError("Misshaped tag"); } // Open tag < - } else { - if (!(token instanceof String)) { - throw x.syntaxError("Bad tagName '" + token + "'."); - } + } + else + { + if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String) token; newja = new JSONArray(); newjo = new JSONObject(); - if (arrayForm) { + if (arrayForm) + { newja.put(tagName); - if (ja != null) { + if (ja != null) + { ja.put(newja); } - } else { + } + else + { newjo.put("tagName", tagName); - if (ja != null) { + if (ja != null) + { ja.put(newjo); } } token = null; - for (;;) { - if (token == null) { + for (;;) + { + if (token == null) + { token = x.nextToken(); } - if (token == null) { - throw x.syntaxError("Misshaped tag"); - } - if (!(token instanceof String)) { + if (token == null) { throw x.syntaxError("Misshaped tag"); } + if (!(token instanceof String)) + { break; } // attribute = value attribute = (String) token; - if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { - throw x.syntaxError("Reserved attribute."); - } + if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); - if (token == XML.EQ) { + if (token == XML.EQ) + { token = x.nextToken(); - if (!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } + if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, XML.stringToValue((String) token)); token = null; - } else { + } + else + { newjo.accumulate(attribute, ""); } } - if (arrayForm && (newjo.length() > 0)) { + if (arrayForm && (newjo.length() > 0)) + { newja.put(newjo); } // Empty tag <.../> - if (token == XML.SLASH) { - if (x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - if (ja == null) { - if (arrayForm) { + if (token == XML.SLASH) + { + if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } + if (ja == null) + { + if (arrayForm) + { return newja; - } else { + } + else + { return newjo; } } // Content, between <...> and - } else { - if (token != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } + } + else + { + if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String) parse(x, arrayForm, newja); - if (closeTag != null) { - if (!closeTag.equals(tagName)) { - throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); - } + if (closeTag != null) + { + if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; - if (!arrayForm && (newja.length() > 0)) { + if (!arrayForm && (newja.length() > 0)) + { newjo.put("childNodes", newja); } - if (ja == null) { - if (arrayForm) { + if (ja == null) + { + if (arrayForm) + { return newja; - } else { + } + else + { return newjo; } } } } } - } else { - if (ja != null) { + } + else + { + if (ja != null) + { ja.put(token instanceof String ? XML.stringToValue((String) token) : token); } } @@ -195,7 +236,8 @@ public class JSONML { * * @throws JSONException */ - public static JSONArray toJSONArray(final String string) throws JSONException { + public static JSONArray toJSONArray(final String string) throws JSONException + { return toJSONArray(new XMLTokener(string)); } @@ -212,7 +254,8 @@ public class JSONML { * * @throws JSONException */ - public static JSONArray toJSONArray(final XMLTokener x) throws JSONException { + public static JSONArray toJSONArray(final XMLTokener x) throws JSONException + { return (JSONArray) parse(x, true, null); } @@ -221,7 +264,7 @@ public class JSONML { * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * property which will be an array of strings and JsonML JSONObjects. - * + * * Comments, prologs, DTDs, and <[ [ ]]> are ignored. * * @param x An XMLTokener of the XML source text. @@ -230,7 +273,8 @@ public class JSONML { * * @throws JSONException */ - public static JSONObject toJSONObject(final XMLTokener x) throws JSONException { + public static JSONObject toJSONObject(final XMLTokener x) throws JSONException + { return (JSONObject) parse(x, false, null); } @@ -239,7 +283,7 @@ public class JSONML { * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * property which will be an array of strings and JsonML JSONObjects. - * + * * Comments, prologs, DTDs, and <[ [ ]]> are ignored. * * @param string The XML source text. @@ -248,7 +292,8 @@ public class JSONML { * * @throws JSONException */ - public static JSONObject toJSONObject(final String string) throws JSONException { + public static JSONObject toJSONObject(final String string) throws JSONException + { return toJSONObject(new XMLTokener(string)); } @@ -261,7 +306,8 @@ public class JSONML { * * @throws JSONException */ - public static String toString(final JSONArray ja) throws JSONException { + public static String toString(final JSONArray ja) throws JSONException + { int i; JSONObject jo; String key; @@ -278,16 +324,19 @@ public class JSONML { sb.append('<'); sb.append(tagName); object = ja.opt(1); - if (object instanceof JSONObject) { + if (object instanceof JSONObject) + { i = 2; jo = (JSONObject) object; // Emit the attributes keys = jo.keys(); - while (keys.hasNext()) { + while (keys.hasNext()) + { key = keys.next(); XML.noSpace(key); value = jo.optString(key); - if (value != null) { + if (value != null) + { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); @@ -296,29 +345,42 @@ public class JSONML { sb.append('"'); } } - } else { + } + else + { i = 1; } // Emit content in body length = ja.length(); - if (i >= length) { + if (i >= length) + { sb.append('/'); sb.append('>'); - } else { + } + else + { sb.append('>'); - do { + do + { object = ja.get(i); i += 1; - if (object != null) { - if (object instanceof String) { + if (object != null) + { + if (object instanceof String) + { sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { + } + else if (object instanceof JSONObject) + { sb.append(toString((JSONObject) object)); - } else if (object instanceof JSONArray) { + } + else if (object instanceof JSONArray) + { sb.append(toString((JSONArray) object)); } } - } while (i < length); + } + while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); @@ -338,7 +400,8 @@ public class JSONML { * * @throws JSONException */ - public static String toString(final JSONObject jo) throws JSONException { + public static String toString(final JSONObject jo) throws JSONException + { final StringBuilder sb = new StringBuilder(); int i; JSONArray ja; @@ -350,21 +413,22 @@ public class JSONML { String value; // Emit '); - } else { + } + else + { sb.append('>'); length = ja.length(); - for (i = 0; i < length; i += 1) { + for (i = 0; i < length; i += 1) + { object = ja.get(i); - if (object != null) { - if (object instanceof String) { + if (object != null) + { + if (object instanceof String) + { sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { + } + else if (object instanceof JSONObject) + { sb.append(toString((JSONObject) object)); - } else if (object instanceof JSONArray) { + } + else if (object instanceof JSONArray) + { sb.append(toString((JSONArray) object)); - } else { + } + else + { sb.append(object.toString()); } } diff --git a/src/main/java/com/intellectualcrafters/json/JSONObject.java b/src/main/java/com/intellectualcrafters/json/JSONObject.java index 3cac13db7..2f126f21d 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONObject.java +++ b/src/main/java/com/intellectualcrafters/json/JSONObject.java @@ -27,21 +27,21 @@ import java.util.Set; * values into a JSON text using the put and toString methods. A get method * returns a value if one can be found, and throws an exception if one cannot be found. An opt method * returns a default value instead of throwing an exception, and so is useful for obtaining optional values. - * + * * The generic get() and opt() methods return an object, which you can cast or query for type. * There are also typed get and opt methods that do type checking and type coercion for you. * The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such * as null. - * + * * The put methods add or replace values in an object. For example, - * - * + * + * *
      * myString = new JSONObject().put("JSON", "Hello, World!").toString();
      * 
    - * + * * produces the string {"JSON": "Hello, World"}. - * + * * The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors * are more forgiving in the texts they will accept:
    • An extra , (comma) may * appear just before the closing brace.
    • Strings may be quoted with ' (single @@ -53,7 +53,8 @@ import java.util.Set; * @author JSON.org * @version 2014-05-03 */ -public class JSONObject { +public class JSONObject +{ /** * It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's * null value. JSONObject.NULL.equals(null) returns true. @@ -68,8 +69,9 @@ public class JSONObject { /** * Construct an empty JSONObject. */ - public JSONObject() { - this.map = new HashMap(); + public JSONObject() + { + map = new HashMap(); } /** @@ -82,13 +84,17 @@ public class JSONObject { * @throws JSONException * @throws JSONException If a value is a non-finite number or if a name is duplicated. */ - public JSONObject(final JSONObject jo, final String[] names) { + public JSONObject(final JSONObject jo, final String[] names) + { this(); - for (final String name : names) { - try { - this.putOnce(name, jo.opt(name)); - } catch (final Exception ignore) { + for (final String name : names) + { + try + { + putOnce(name, jo.opt(name)); } + catch (final Exception ignore) + {} } } @@ -99,16 +105,17 @@ public class JSONObject { * * @throws JSONException If there is a syntax error in the source string or a duplicated key. */ - public JSONObject(final JSONTokener x) throws JSONException { + public JSONObject(final JSONTokener x) throws JSONException + { this(); char c; String key; - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { + if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } + for (;;) + { c = x.nextClean(); - switch (c) { + switch (c) + { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': @@ -119,17 +126,14 @@ public class JSONObject { } // The key is followed by ':'. c = x.nextClean(); - if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - this.putOnce(key, x.nextValue()); + if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } + putOnce(key, x.nextValue()); // Pairs are separated by ','. - switch (x.nextClean()) { + switch (x.nextClean()) + { case ';': case ',': - if (x.nextClean() == '}') { - return; - } + if (x.nextClean() == '}') { return; } x.back(); break; case '}': @@ -147,12 +151,16 @@ public class JSONObject { * * @throws JSONException */ - public JSONObject(final Map map) { + public JSONObject(final Map map) + { this.map = new HashMap(); - if (map != null) { - for (final Entry entry : map.entrySet()) { + if (map != null) + { + for (final Entry entry : map.entrySet()) + { final Object value = entry.getValue(); - if (value != null) { + if (value != null) + { this.map.put(entry.getKey(), wrap(value)); } } @@ -164,19 +172,20 @@ public class JSONObject { * For each of the methods with no parameters and a name starting with "get" or "is" * followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. - * + * * The key is formed by removing the "get" or "is" prefix. If the second remaining * character is not upper case, then the first character is converted to lower case. - * + * * For example, if an object has a method named "getName", and if the result of calling * object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry * Fine". * * @param bean An object that has getter methods that should be used to make a JSONObject. */ - public JSONObject(final Object bean) { + public JSONObject(final Object bean) + { this(); - this.populateMap(bean); + populateMap(bean); } /** @@ -187,14 +196,18 @@ public class JSONObject { * @param object An object that has fields that should be used to make a JSONObject. * @param names An array of strings, the names of the fields to be obtained from the object. */ - public JSONObject(final Object object, final String names[]) { + public JSONObject(final Object object, final String names[]) + { this(); final Class c = object.getClass(); - for (final String name : names) { - try { - this.putOpt(name, c.getField(name).get(object)); - } catch (final Exception ignore) { + for (final String name : names) + { + try + { + putOpt(name, c.getField(name).get(object)); } + catch (final Exception ignore) + {} } } @@ -206,7 +219,8 @@ public class JSONObject { * * @throws JSONException If there is a syntax error in the source string or a duplicated key. */ - public JSONObject(final String source) throws JSONException { + public JSONObject(final String source) throws JSONException + { this(new JSONTokener(source)); } @@ -218,14 +232,17 @@ public class JSONObject { * * @throws JSONException If any JSONExceptions are detected. */ - public JSONObject(final String baseName, final Locale locale) throws JSONException { + public JSONObject(final String baseName, final Locale locale) throws JSONException + { this(); final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. final Enumeration keys = bundle.getKeys(); - while (keys.hasMoreElements()) { + while (keys.hasMoreElements()) + { final Object key = keys.nextElement(); - if (key != null) { + if (key != null) + { // Go through the path, ensuring that there is a nested // JSONObject for each // segment except the last. Add the value using the last @@ -234,10 +251,12 @@ public class JSONObject { final String[] path = ((String) key).split("\\."); final int last = path.length - 1; JSONObject target = this; - for (int i = 0; i < last; i += 1) { + for (int i = 0; i < last; i += 1) + { final String segment = path[i]; JSONObject nextTarget = target.optJSONObject(segment); - if (nextTarget == null) { + if (nextTarget == null) + { nextTarget = new JSONObject(); target.put(segment, nextTarget); } @@ -255,17 +274,19 @@ public class JSONObject { * * @return A String. */ - public static String doubleToString(final double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } + public static String doubleToString(final double d) + { + if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); - if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) { - while (string.endsWith("0")) { + if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) + { + while (string.endsWith("0")) + { string = string.substring(0, string.length() - 1); } - if (string.endsWith(".")) { + if (string.endsWith(".")) + { string = string.substring(0, string.length() - 1); } } @@ -277,15 +298,15 @@ public class JSONObject { * * @return An array of field names, or null if there are no names. */ - public static String[] getNames(final JSONObject jo) { + public static String[] getNames(final JSONObject jo) + { final int length = jo.length(); - if (length == 0) { - return null; - } + if (length == 0) { return null; } final Iterator iterator = jo.keys(); final String[] names = new String[length]; int i = 0; - while (iterator.hasNext()) { + while (iterator.hasNext()) + { names[i] = iterator.next(); i += 1; } @@ -297,18 +318,16 @@ public class JSONObject { * * @return An array of field names, or null if there are no names. */ - public static String[] getNames(final Object object) { - if (object == null) { - return null; - } + public static String[] getNames(final Object object) + { + if (object == null) { return null; } final Class klass = object.getClass(); final Field[] fields = klass.getFields(); final int length = fields.length; - if (length == 0) { - return null; - } + if (length == 0) { return null; } final String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { + for (int i = 0; i < length; i += 1) + { names[i] = fields[i].getName(); } return names; @@ -323,18 +342,20 @@ public class JSONObject { * * @throws JSONException If n is a non-finite number. */ - public static String numberToString(final Number number) throws JSONException { - if (number == null) { - throw new JSONException("Null pointer"); - } + public static String numberToString(final Number number) throws JSONException + { + if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); - if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) { - while (string.endsWith("0")) { + if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) + { + while (string.endsWith("0")) + { string = string.substring(0, string.length() - 1); } - if (string.endsWith(".")) { + if (string.endsWith(".")) + { string = string.substring(0, string.length() - 1); } } @@ -349,20 +370,27 @@ public class JSONObject { * * @return A String correctly formatted for insertion in a JSON text. */ - public static String quote(final String string) { + public static String quote(final String string) + { final StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - try { + synchronized (sw.getBuffer()) + { + try + { return quote(string, sw).toString(); - } catch (final IOException ignored) { + } + catch (final IOException ignored) + { // will never happen - we are writing to a string writer return ""; } } } - public static Writer quote(final String string, final Writer w) throws IOException { - if ((string == null) || (string.length() == 0)) { + public static Writer quote(final String string, final Writer w) throws IOException + { + if ((string == null) || (string.length() == 0)) + { w.write("\"\""); return w; } @@ -372,17 +400,20 @@ public class JSONObject { int i; final int len = string.length(); w.write('"'); - for (i = 0; i < len; i += 1) { + for (i = 0; i < len; i += 1) + { b = c; c = string.charAt(i); - switch (c) { + switch (c) + { case '\\': case '"': w.write('\\'); w.write(c); break; case '/': - if (b == '<') { + if (b == '<') + { w.write('\\'); } w.write(c); @@ -403,12 +434,15 @@ public class JSONObject { w.write("\\r"); break; default: - if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) { + if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) + { w.write("\\u"); hhhh = Integer.toHexString(c); w.write("0000", 0, 4 - hhhh.length()); w.write(hhhh); - } else { + } + else + { w.write(c); } } @@ -424,44 +458,45 @@ public class JSONObject { * * @return A simple JSON value. */ - public static Object stringToValue(final String string) { + public static Object stringToValue(final String string) + { Double d; - if (string.equals("")) { - return string; - } - if (string.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if (string.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if (string.equalsIgnoreCase("null")) { - return JSONObject.NULL; - } + if (string.equals("")) { return string; } + if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } + if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } + if (string.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* * If it might be a number, try converting it. If a number cannot be * produced, then the value will just be a string. */ final char b = string.charAt(0); - if (((b >= '0') && (b <= '9')) || (b == '-')) { - try { - if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1)) { + if (((b >= '0') && (b <= '9')) || (b == '-')) + { + try + { + if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1)) + { d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { + if (!d.isInfinite() && !d.isNaN()) { return d; } + } + else + { final Long myLong = new Long(string); - if (string.equals(myLong.toString())) { - if (myLong == myLong.intValue()) { + if (string.equals(myLong.toString())) + { + if (myLong == myLong.intValue()) + { return myLong.intValue(); - } else { + } + else + { return myLong; } } } - } catch (final Exception ignore) { } + catch (final Exception ignore) + {} } return string; } @@ -473,16 +508,17 @@ public class JSONObject { * * @throws JSONException If o is a non-finite number. */ - public static void testValidity(final Object o) throws JSONException { - if (o != null) { - if (o instanceof Double) { - if (((Double) o).isInfinite() || ((Double) o).isNaN()) { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } else if (o instanceof Float) { - if (((Float) o).isInfinite() || ((Float) o).isNaN()) { - throw new JSONException("JSON does not allow non-finite numbers."); - } + public static void testValidity(final Object o) throws JSONException + { + if (o != null) + { + if (o instanceof Double) + { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); } + } + else if (o instanceof Float) + { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); } } } } @@ -494,8 +530,8 @@ public class JSONObject { * If the value is an array or Collection, then a JSONArray will be made from it and its toJSONString method will be * called. If the value is a MAP, then a JSONObject will be made from it and its toJSONString method will be called. * Otherwise, the value's toString method will be called, and the result will be quoted. - * - * + * + * * Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. @@ -506,37 +542,28 @@ public class JSONObject { * * @throws JSONException If the value is or contains an invalid number. */ - public static String valueToString(final Object value) throws JSONException { - if ((value == null) || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { + public static String valueToString(final Object value) throws JSONException + { + if ((value == null) || value.equals(null)) { return "null"; } + if (value instanceof JSONString) + { Object object; - try { + try + { object = ((JSONString) value).toJSONString(); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException(e); } - if (object instanceof String) { - return (String) object; - } + if (object instanceof String) { return (String) object; } throw new JSONException("Bad value from toJSONString: " + object); } - if (value instanceof Number) { - return numberToString((Number) value); - } - if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map) value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection) value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } + if (value instanceof Number) { return numberToString((Number) value); } + if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { return value.toString(); } + if (value instanceof Map) { return new JSONObject((Map) value).toString(); } + if (value instanceof Collection) { return new JSONArray((Collection) value).toString(); } + if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } @@ -550,67 +577,96 @@ public class JSONObject { * * @return The wrapped value */ - public static Object wrap(final Object object) { - try { - if (object == null) { - return NULL; - } - if ((object instanceof JSONObject) || (object instanceof JSONArray) || NULL.equals(object) || (object instanceof JSONString) || (object instanceof Byte) || (object instanceof Character) || (object instanceof Short) || (object instanceof Integer) || (object instanceof Long) || (object instanceof Boolean) || (object instanceof Float) || (object instanceof Double) || (object instanceof String)) { - return object; - } - if (object instanceof Collection) { - return new JSONArray((Collection) object); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - return new JSONObject((Map) object); - } + public static Object wrap(final Object object) + { + try + { + if (object == null) { return NULL; } + if ((object instanceof JSONObject) + || (object instanceof JSONArray) + || NULL.equals(object) + || (object instanceof JSONString) + || (object instanceof Byte) + || (object instanceof Character) + || (object instanceof Short) + || (object instanceof Integer) + || (object instanceof Long) + || (object instanceof Boolean) + || (object instanceof Float) + || (object instanceof Double) + || (object instanceof String)) { return object; } + if (object instanceof Collection) { return new JSONArray((Collection) object); } + if (object.getClass().isArray()) { return new JSONArray(object); } + if (object instanceof Map) { return new JSONObject((Map) object); } final Package objectPackage = object.getClass().getPackage(); final String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; - if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) { - return object.toString(); - } + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) { return object.toString(); } return new JSONObject(object); - } catch (final Exception exception) { + } + catch (final Exception exception) + { return null; } } - static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException { - if ((value == null) || value.equals(null)) { + static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException + { + if ((value == null) || value.equals(null)) + { writer.write("null"); - } else if (value instanceof JSONObject) { + } + else if (value instanceof JSONObject) + { ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { + } + else if (value instanceof JSONArray) + { ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { + } + else if (value instanceof Map) + { new JSONObject((Map) value).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { + } + else if (value instanceof Collection) + { new JSONArray((Collection) value).write(writer, indentFactor, indent); - } else if (value.getClass().isArray()) { + } + else if (value.getClass().isArray()) + { new JSONArray(value).write(writer, indentFactor, indent); - } else if (value instanceof Number) { + } + else if (value instanceof Number) + { writer.write(numberToString((Number) value)); - } else if (value instanceof Boolean) { + } + else if (value instanceof Boolean) + { writer.write(value.toString()); - } else if (value instanceof JSONString) { + } + else if (value instanceof JSONString) + { Object o; - try { + try + { o = ((JSONString) value).toJSONString(); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException(e); } writer.write(o != null ? o.toString() : quote(value.toString())); - } else { + } + else + { quote(value.toString(), writer); } return writer; } - static final void indent(final Writer writer, final int indent) throws IOException { - for (int i = 0; i < indent; i += 1) { + static final void indent(final Writer writer, final int indent) throws IOException + { + for (int i = 0; i < indent; i += 1) + { writer.write(' '); } } @@ -619,7 +675,7 @@ public class JSONObject { * Accumulate values under a key. It is similar to the put method except that if there is already an object stored * under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already * a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. - * + * * If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if * multiple values are accumulated, then the result will be like append. * @@ -630,14 +686,20 @@ public class JSONObject { * * @throws JSONException If the value is an invalid number or if the key is null. */ - public JSONObject accumulate(final String key, final Object value) throws JSONException { + public JSONObject accumulate(final String key, final Object value) throws JSONException + { testValidity(value); - final Object object = this.opt(key); - if (object == null) { + final Object object = opt(key); + if (object == null) + { this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); - } else if (object instanceof JSONArray) { + } + else if (object instanceof JSONArray) + { ((JSONArray) object).put(value); - } else { + } + else + { this.put(key, new JSONArray().put(object).put(value)); } return this; @@ -655,14 +717,20 @@ public class JSONObject { * * @throws JSONException If the key is null or if the current value associated with the key is not a JSONArray. */ - public JSONObject append(final String key, final Object value) throws JSONException { + public JSONObject append(final String key, final Object value) throws JSONException + { testValidity(value); - final Object object = this.opt(key); - if (object == null) { + final Object object = opt(key); + if (object == null) + { this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { + } + else if (object instanceof JSONArray) + { this.put(key, ((JSONArray) object).put(value)); - } else { + } + else + { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; @@ -677,14 +745,11 @@ public class JSONObject { * * @throws JSONException if the key is not found. */ - public Object get(final String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - final Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } + public Object get(final String key) throws JSONException + { + if (key == null) { throw new JSONException("Null key."); } + final Object object = opt(key); + if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return object; } @@ -697,13 +762,14 @@ public class JSONObject { * * @throws JSONException if the value is not a Boolean or the String "true" or "false". */ - public boolean getBoolean(final String key) throws JSONException { - final Object object = this.get(key); - if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { + public boolean getBoolean(final String key) throws JSONException + { + final Object object = get(key); + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) + { return false; - } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { - return true; } + else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } @@ -717,11 +783,15 @@ public class JSONObject { * @throws JSONException if the key is not found or if the value is not a Number object and cannot be converted to a * number. */ - public double getDouble(final String key) throws JSONException { - final Object object = this.get(key); - try { + public double getDouble(final String key) throws JSONException + { + final Object object = get(key); + try + { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } @@ -735,11 +805,15 @@ public class JSONObject { * * @throws JSONException if the key is not found or if the value cannot be converted to an integer. */ - public int getInt(final String key) throws JSONException { - final Object object = this.get(key); - try { + public int getInt(final String key) throws JSONException + { + final Object object = get(key); + try + { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } } @@ -753,11 +827,10 @@ public class JSONObject { * * @throws JSONException if the key is not found or if the value is not a JSONArray. */ - public JSONArray getJSONArray(final String key) throws JSONException { - final Object object = this.get(key); - if (object instanceof JSONArray) { - return (JSONArray) object; - } + public JSONArray getJSONArray(final String key) throws JSONException + { + final Object object = get(key); + if (object instanceof JSONArray) { return (JSONArray) object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } @@ -770,11 +843,10 @@ public class JSONObject { * * @throws JSONException if the key is not found or if the value is not a JSONObject. */ - public JSONObject getJSONObject(final String key) throws JSONException { - final Object object = this.get(key); - if (object instanceof JSONObject) { - return (JSONObject) object; - } + public JSONObject getJSONObject(final String key) throws JSONException + { + final Object object = get(key); + if (object instanceof JSONObject) { return (JSONObject) object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } @@ -787,11 +859,15 @@ public class JSONObject { * * @throws JSONException if the key is not found or if the value cannot be converted to a long. */ - public long getLong(final String key) throws JSONException { - final Object object = this.get(key); - try { + public long getLong(final String key) throws JSONException + { + final Object object = get(key); + try + { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); - } catch (final Exception e) { + } + catch (final Exception e) + { throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } } @@ -805,11 +881,10 @@ public class JSONObject { * * @throws JSONException if there is no string value for the key. */ - public String getString(final String key) throws JSONException { - final Object object = this.get(key); - if (object instanceof String) { - return (String) object; - } + public String getString(final String key) throws JSONException + { + final Object object = get(key); + if (object instanceof String) { return (String) object; } throw new JSONException("JSONObject[" + quote(key) + "] not a string."); } @@ -820,8 +895,9 @@ public class JSONObject { * * @return true if the key exists in the JSONObject. */ - public boolean has(final String key) { - return this.map.containsKey(key); + public boolean has(final String key) + { + return map.containsKey(key); } /** @@ -835,19 +911,31 @@ public class JSONObject { * @throws JSONException If there is already a property with this name that is not an Integer, Long, Double, or * Float. */ - public JSONObject increment(final String key) throws JSONException { - final Object value = this.opt(key); - if (value == null) { + public JSONObject increment(final String key) throws JSONException + { + final Object value = opt(key); + if (value == null) + { this.put(key, 1); - } else if (value instanceof Integer) { + } + else if (value instanceof Integer) + { this.put(key, (Integer) value + 1); - } else if (value instanceof Long) { + } + else if (value instanceof Long) + { this.put(key, (Long) value + 1); - } else if (value instanceof Double) { + } + else if (value instanceof Double) + { this.put(key, (Double) value + 1); - } else if (value instanceof Float) { + } + else if (value instanceof Float) + { this.put(key, (Float) value + 1); - } else { + } + else + { throw new JSONException("Unable to increment [" + quote(key) + "]."); } return this; @@ -860,8 +948,9 @@ public class JSONObject { * * @return true if there is no value associated with the key or if the value is the JSONObject.NULL object. */ - public boolean isNull(final String key) { - return JSONObject.NULL.equals(this.opt(key)); + public boolean isNull(final String key) + { + return JSONObject.NULL.equals(opt(key)); } /** @@ -869,8 +958,9 @@ public class JSONObject { * * @return An iterator of the keys. */ - public Iterator keys() { - return this.keySet().iterator(); + public Iterator keys() + { + return keySet().iterator(); } /** @@ -878,8 +968,9 @@ public class JSONObject { * * @return A keySet. */ - public Set keySet() { - return this.map.keySet(); + public Set keySet() + { + return map.keySet(); } /** @@ -887,8 +978,9 @@ public class JSONObject { * * @return The number of keys in the JSONObject. */ - public int length() { - return this.map.size(); + public int length() + { + return map.size(); } /** @@ -896,10 +988,12 @@ public class JSONObject { * * @return A JSONArray containing the key strings, or null if the JSONObject is empty. */ - public JSONArray names() { + public JSONArray names() + { final JSONArray ja = new JSONArray(); - final Iterator keys = this.keys(); - while (keys.hasNext()) { + final Iterator keys = keys(); + while (keys.hasNext()) + { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; @@ -912,8 +1006,9 @@ public class JSONObject { * * @return An object which is the value, or null if there is no value. */ - public Object opt(final String key) { - return key == null ? null : this.map.get(key); + public Object opt(final String key) + { + return key == null ? null : map.get(key); } /** @@ -924,7 +1019,8 @@ public class JSONObject { * * @return The truth. */ - public boolean optBoolean(final String key) { + public boolean optBoolean(final String key) + { return this.optBoolean(key, false); } @@ -937,10 +1033,14 @@ public class JSONObject { * * @return The truth. */ - public boolean optBoolean(final String key, final boolean defaultValue) { - try { - return this.getBoolean(key); - } catch (final Exception e) { + public boolean optBoolean(final String key, final boolean defaultValue) + { + try + { + return getBoolean(key); + } + catch (final Exception e) + { return defaultValue; } } @@ -953,7 +1053,8 @@ public class JSONObject { * * @return An object which is the value. */ - public double optDouble(final String key) { + public double optDouble(final String key) + { return this.optDouble(key, Double.NaN); } @@ -966,10 +1067,14 @@ public class JSONObject { * * @return An object which is the value. */ - public double optDouble(final String key, final double defaultValue) { - try { - return this.getDouble(key); - } catch (final Exception e) { + public double optDouble(final String key, final double defaultValue) + { + try + { + return getDouble(key); + } + catch (final Exception e) + { return defaultValue; } } @@ -982,7 +1087,8 @@ public class JSONObject { * * @return An object which is the value. */ - public int optInt(final String key) { + public int optInt(final String key) + { return this.optInt(key, 0); } @@ -995,10 +1101,14 @@ public class JSONObject { * * @return An object which is the value. */ - public int optInt(final String key, final int defaultValue) { - try { - return this.getInt(key); - } catch (final Exception e) { + public int optInt(final String key, final int defaultValue) + { + try + { + return getInt(key); + } + catch (final Exception e) + { return defaultValue; } } @@ -1011,8 +1121,9 @@ public class JSONObject { * * @return A JSONArray which is the value. */ - public JSONArray optJSONArray(final String key) { - final Object o = this.opt(key); + public JSONArray optJSONArray(final String key) + { + final Object o = opt(key); return o instanceof JSONArray ? (JSONArray) o : null; } @@ -1024,8 +1135,9 @@ public class JSONObject { * * @return A JSONObject which is the value. */ - public JSONObject optJSONObject(final String key) { - final Object object = this.opt(key); + public JSONObject optJSONObject(final String key) + { + final Object object = opt(key); return object instanceof JSONObject ? (JSONObject) object : null; } @@ -1037,7 +1149,8 @@ public class JSONObject { * * @return An object which is the value. */ - public long optLong(final String key) { + public long optLong(final String key) + { return this.optLong(key, 0); } @@ -1050,10 +1163,14 @@ public class JSONObject { * * @return An object which is the value. */ - public long optLong(final String key, final long defaultValue) { - try { - return this.getLong(key); - } catch (final Exception e) { + public long optLong(final String key, final long defaultValue) + { + try + { + return getLong(key); + } + catch (final Exception e) + { return defaultValue; } } @@ -1066,7 +1183,8 @@ public class JSONObject { * * @return A string which is the value. */ - public String optString(final String key) { + public String optString(final String key) + { return this.optString(key, ""); } @@ -1078,44 +1196,61 @@ public class JSONObject { * * @return A string which is the value. */ - public String optString(final String key, final String defaultValue) { - final Object object = this.opt(key); + public String optString(final String key, final String defaultValue) + { + final Object object = opt(key); return NULL.equals(object) ? defaultValue : object.toString(); } - private void populateMap(final Object bean) { + private void populateMap(final Object bean) + { final Class klass = bean.getClass(); // If klass is a System class then set includeSuperClass to false. final boolean includeSuperClass = klass.getClassLoader() != null; final Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for (final Method method : methods) { - try { - if (Modifier.isPublic(method.getModifiers())) { + for (final Method method : methods) + { + try + { + if (Modifier.isPublic(method.getModifiers())) + { final String name = method.getName(); String key = ""; - if (name.startsWith("get")) { - if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { + if (name.startsWith("get")) + { + if ("getClass".equals(name) || "getDeclaringClass".equals(name)) + { key = ""; - } else { + } + else + { key = name.substring(3); } - } else if (name.startsWith("is")) { + } + else if (name.startsWith("is")) + { key = name.substring(2); } - if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) { - if (key.length() == 1) { + if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) + { + if (key.length() == 1) + { key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { + } + else if (!Character.isUpperCase(key.charAt(1))) + { key = key.substring(0, 1).toLowerCase() + key.substring(1); } final Object result = method.invoke(bean, (Object[]) null); - if (result != null) { - this.map.put(key, wrap(result)); + if (result != null) + { + map.put(key, wrap(result)); } } } - } catch (final Exception ignore) { } + catch (final Exception ignore) + {} } } @@ -1129,7 +1264,8 @@ public class JSONObject { * * @throws JSONException If the key is null. */ - public JSONObject put(final String key, final boolean value) throws JSONException { + public JSONObject put(final String key, final boolean value) throws JSONException + { this.put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -1144,7 +1280,8 @@ public class JSONObject { * * @throws JSONException */ - public JSONObject put(final String key, final Collection value) throws JSONException { + public JSONObject put(final String key, final Collection value) throws JSONException + { this.put(key, new JSONArray(value)); return this; } @@ -1159,7 +1296,8 @@ public class JSONObject { * * @throws JSONException If the key is null or if the number is invalid. */ - public JSONObject put(final String key, final double value) throws JSONException { + public JSONObject put(final String key, final double value) throws JSONException + { this.put(key, new Double(value)); return this; } @@ -1174,7 +1312,8 @@ public class JSONObject { * * @throws JSONException If the key is null. */ - public JSONObject put(final String key, final int value) throws JSONException { + public JSONObject put(final String key, final int value) throws JSONException + { this.put(key, new Integer(value)); return this; } @@ -1189,7 +1328,8 @@ public class JSONObject { * * @throws JSONException If the key is null. */ - public JSONObject put(final String key, final long value) throws JSONException { + public JSONObject put(final String key, final long value) throws JSONException + { this.put(key, new Long(value)); return this; } @@ -1204,7 +1344,8 @@ public class JSONObject { * * @throws JSONException */ - public JSONObject put(final String key, final Map value) throws JSONException { + public JSONObject put(final String key, final Map value) throws JSONException + { this.put(key, new JSONObject(value)); return this; } @@ -1221,15 +1362,17 @@ public class JSONObject { * * @throws JSONException If the value is non-finite number or if the key is null. */ - public JSONObject put(final String key, final Object value) throws JSONException { - if (key == null) { - throw new NullPointerException("Null key."); - } - if (value != null) { + public JSONObject put(final String key, final Object value) throws JSONException + { + if (key == null) { throw new NullPointerException("Null key."); } + if (value != null) + { testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); + map.put(key, value); + } + else + { + remove(key); } return this; } @@ -1245,11 +1388,11 @@ public class JSONObject { * * @throws JSONException if the key is a duplicate */ - public JSONObject putOnce(final String key, final Object value) throws JSONException { - if ((key != null) && (value != null)) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } + public JSONObject putOnce(final String key, final Object value) throws JSONException + { + if ((key != null) && (value != null)) + { + if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } this.put(key, value); } return this; @@ -1266,8 +1409,10 @@ public class JSONObject { * * @throws JSONException If the value is a non-finite number. */ - public JSONObject putOpt(final String key, final Object value) throws JSONException { - if ((key != null) && (value != null)) { + public JSONObject putOpt(final String key, final Object value) throws JSONException + { + if ((key != null) && (value != null)) + { this.put(key, value); } return this; @@ -1280,8 +1425,9 @@ public class JSONObject { * * @return The value that was associated with the name, or null if there was no value. */ - public Object remove(final String key) { - return this.map.remove(key); + public Object remove(final String key) + { + return map.remove(key); } /** @@ -1292,32 +1438,31 @@ public class JSONObject { * * @return true if they are equal */ - public boolean similar(final Object other) { - try { - if (!(other instanceof JSONObject)) { - return false; - } - final Set set = this.keySet(); - if (!set.equals(((JSONObject) other).keySet())) { - return false; - } - for (final String name : set) { - final Object valueThis = this.get(name); + public boolean similar(final Object other) + { + try + { + if (!(other instanceof JSONObject)) { return false; } + final Set set = keySet(); + if (!set.equals(((JSONObject) other).keySet())) { return false; } + for (final String name : set) + { + final Object valueThis = get(name); final Object valueOther = ((JSONObject) other).get(name); - if (valueThis instanceof JSONObject) { - if (!((JSONObject) valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray) valueThis).similar(valueOther)) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; + if (valueThis instanceof JSONObject) + { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } } + else if (valueThis instanceof JSONArray) + { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } + } + else if (!valueThis.equals(valueOther)) { return false; } } return true; - } catch (final Throwable exception) { + } + catch (final Throwable exception) + { return false; } } @@ -1332,13 +1477,13 @@ public class JSONObject { * * @throws JSONException If any of the values are non-finite numbers. */ - public JSONArray toJSONArray(final JSONArray names) throws JSONException { - if ((names == null) || (names.length() == 0)) { - return null; - } + public JSONArray toJSONArray(final JSONArray names) throws JSONException + { + if ((names == null) || (names.length() == 0)) { return null; } final JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); + for (int i = 0; i < names.length(); i += 1) + { + ja.put(opt(names.getString(i))); } return ja; } @@ -1346,7 +1491,7 @@ public class JSONObject { /** * Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a * syntactically correct JSON text, then null will be returned instead. - * + * * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable representation of the object, beginning with @@ -1354,17 +1499,21 @@ public class JSONObject { * brace). */ @Override - public String toString() { - try { + public String toString() + { + try + { return this.toString(0); - } catch (final Exception e) { + } + catch (final Exception e) + { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. - * + * * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. @@ -1375,76 +1524,92 @@ public class JSONObject { * * @throws JSONException If the object contains an invalid number. */ - public String toString(final int indentFactor) throws JSONException { + public String toString(final int indentFactor) throws JSONException + { final StringWriter w = new StringWriter(); - synchronized (w.getBuffer()) { + synchronized (w.getBuffer()) + { return this.write(w, indentFactor, 0).toString(); } } /** * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. - * + * * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * * @throws JSONException */ - public Writer write(final Writer writer) throws JSONException { + public Writer write(final Writer writer) throws JSONException + { return this.write(writer, 0, 0); } /** * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. - * + * * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * * @throws JSONException */ - Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { - try { + Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException + { + try + { boolean commanate = false; - final int length = this.length(); - final Iterator keys = this.keys(); + final int length = length(); + final Iterator keys = keys(); writer.write('{'); - if (length == 1) { + if (length == 1) + { final Object key = keys.next(); writer.write(quote(key.toString())); writer.write(':'); - if (indentFactor > 0) { + if (indentFactor > 0) + { writer.write(' '); } - writeValue(writer, this.map.get(key), indentFactor, indent); - } else if (length != 0) { + writeValue(writer, map.get(key), indentFactor, indent); + } + else if (length != 0) + { final int newindent = indent + indentFactor; - while (keys.hasNext()) { + while (keys.hasNext()) + { final Object key = keys.next(); - if (commanate) { + if (commanate) + { writer.write(','); } - if (indentFactor > 0) { + if (indentFactor > 0) + { writer.write('\n'); } indent(writer, newindent); writer.write(quote(key.toString())); writer.write(':'); - if (indentFactor > 0) { + if (indentFactor > 0) + { writer.write(' '); } - writeValue(writer, this.map.get(key), indentFactor, newindent); + writeValue(writer, map.get(key), indentFactor, newindent); commanate = true; } - if (indentFactor > 0) { + if (indentFactor > 0) + { writer.write('\n'); } indent(writer, indent); } writer.write('}'); return writer; - } catch (final IOException exception) { + } + catch (final IOException exception) + { throw new JSONException(exception); } } @@ -1453,17 +1618,22 @@ public class JSONObject { * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the * value that JavaScript calls undefined. */ - private static final class Null { + private static final class Null + { /** * There is only intended to be a single instance of the NULL object, so the clone method returns itself. * * @return NULL. */ @Override - protected final Object clone() { - try { + protected final Object clone() + { + try + { return super.clone(); - } catch (final Exception e) { + } + catch (final Exception e) + { return this; } } @@ -1476,7 +1646,8 @@ public class JSONObject { * @return true if the object parameter is the JSONObject.NULL object or null. */ @Override - public boolean equals(final Object object) { + public boolean equals(final Object object) + { return (object == null) || (object == this); } @@ -1486,7 +1657,8 @@ public class JSONObject { * @return The string "null". */ @Override - public String toString() { + public String toString() + { return "null"; } } diff --git a/src/main/java/com/intellectualcrafters/json/JSONString.java b/src/main/java/com/intellectualcrafters/json/JSONString.java index 2cf8273a9..c8494287f 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONString.java +++ b/src/main/java/com/intellectualcrafters/json/JSONString.java @@ -6,7 +6,8 @@ package com.intellectualcrafters.json; * JSONWriter.value(Object). The toJSONString method will be used instead of the * default behavior of using the Object's toString() method and quoting the result. */ -public interface JSONString { +public interface JSONString +{ /** * The toJSONString method allows a class to produce its own JSON serialization. * diff --git a/src/main/java/com/intellectualcrafters/json/JSONStringer.java b/src/main/java/com/intellectualcrafters/json/JSONStringer.java index 56d67ad6f..fbc59094a 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONStringer.java +++ b/src/main/java/com/intellectualcrafters/json/JSONStringer.java @@ -6,38 +6,40 @@ import java.io.StringWriter; * JSONStringer provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. - * + * * A JSONStringer instance provides a value method for appending values to the text, and a key * method for adding keys before values in objects. There are array and endArray methods that * make and bound array values, and object and endObject methods which make and bound object * values. All of these methods return the JSONWriter instance, permitting cascade style. For example, - * - * + * + * *
        * myString = new JSONStringer().object().key("JSON").value("Hello,
        * World!").endObject().toString();
        * 
      - * + * * which produces the string - * - * + * + * *
        * {"JSON":"Hello, World!"}
        * 
      - * + * * The first method called must be array or object. There are no methods for adding commas or * colons. JSONStringer adds them for you. Objects and arrays can be nested up to 20 levels deep. - * + * * This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org * @version 2008-09-18 */ -public class JSONStringer extends JSONWriter { +public class JSONStringer extends JSONWriter +{ /** * Make a fresh JSONStringer. It can be used to build one JSON text. */ - public JSONStringer() { + public JSONStringer() + { super(new StringWriter()); } @@ -49,7 +51,8 @@ public class JSONStringer extends JSONWriter { * @return The JSON text. */ @Override - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; + public String toString() + { + return mode == 'd' ? writer.toString() : null; } } diff --git a/src/main/java/com/intellectualcrafters/json/JSONTokener.java b/src/main/java/com/intellectualcrafters/json/JSONTokener.java index 0c86068ea..3391e1255 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONTokener.java +++ b/src/main/java/com/intellectualcrafters/json/JSONTokener.java @@ -14,7 +14,8 @@ import java.io.StringReader; * @author JSON.org * @version 2014-05-03 */ -public class JSONTokener { +public class JSONTokener +{ private final Reader reader; private long character; private boolean eof; @@ -28,14 +29,15 @@ public class JSONTokener { * * @param reader A reader. */ - public JSONTokener(final Reader reader) { + public JSONTokener(final Reader reader) + { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; + eof = false; + usePrevious = false; + previous = 0; + index = 0; + character = 1; + line = 1; } /** @@ -43,7 +45,8 @@ public class JSONTokener { * * @param inputStream The source. */ - public JSONTokener(final InputStream inputStream) throws JSONException { + public JSONTokener(final InputStream inputStream) throws JSONException + { this(new InputStreamReader(inputStream)); } @@ -52,7 +55,8 @@ public class JSONTokener { * * @param s A source string. */ - public JSONTokener(final String s) { + public JSONTokener(final String s) + { this(new StringReader(s)); } @@ -63,16 +67,11 @@ public class JSONTokener { * * @return An int between 0 and 15, or -1 if c was not a hex digit. */ - public static int dehexchar(final char c) { - if ((c >= '0') && (c <= '9')) { - return c - '0'; - } - if ((c >= 'A') && (c <= 'F')) { - return c - ('A' - 10); - } - if ((c >= 'a') && (c <= 'f')) { - return c - ('a' - 10); - } + public static int dehexchar(final char c) + { + if ((c >= '0') && (c <= '9')) { return c - '0'; } + if ((c >= 'A') && (c <= 'F')) { return c - ('A' - 10); } + if ((c >= 'a') && (c <= 'f')) { return c - ('a' - 10); } return -1; } @@ -80,18 +79,18 @@ public class JSONTokener { * Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter * before attempting to parse the next number or identifier. */ - public void back() throws JSONException { - if (this.usePrevious || (this.index <= 0)) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; + public void back() throws JSONException + { + if (usePrevious || (index <= 0)) { throw new JSONException("Stepping back two steps is not supported"); } + index -= 1; + character -= 1; + usePrevious = true; + eof = false; } - public boolean end() { - return this.eof && !this.usePrevious; + public boolean end() + { + return eof && !usePrevious; } /** @@ -99,12 +98,11 @@ public class JSONTokener { * * @return true if not yet at the end of the source. */ - public boolean more() throws JSONException { + public boolean more() throws JSONException + { this.next(); - if (this.end()) { - return false; - } - this.back(); + if (end()) { return false; } + back(); return true; } @@ -113,34 +111,47 @@ public class JSONTokener { * * @return The next character, or 0 if past the end of the source string. */ - public char next() throws JSONException { + public char next() throws JSONException + { int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch (final IOException exception) { + if (usePrevious) + { + usePrevious = false; + c = previous; + } + else + { + try + { + c = reader.read(); + } + catch (final IOException exception) + { throw new JSONException(exception); } - if (c <= 0) { // End of stream - this.eof = true; + if (c <= 0) + { // End of stream + eof = true; c = 0; } } - this.index += 1; - if (this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; + index += 1; + if (previous == '\r') + { + line += 1; + character = c == '\n' ? 0 : 1; } - this.previous = (char) c; - return this.previous; + else if (c == '\n') + { + line += 1; + character = 0; + } + else + { + character += 1; + } + previous = (char) c; + return previous; } /** @@ -152,11 +163,10 @@ public class JSONTokener { * * @throws JSONException if the character does not match. */ - public char next(final char c) throws JSONException { + public char next(final char c) throws JSONException + { final char n = this.next(); - if (n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); - } + if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } @@ -169,17 +179,15 @@ public class JSONTokener { * * @throws JSONException Substring bounds error if there are not n characters remaining in the source string. */ - public String next(final int n) throws JSONException { - if (n == 0) { - return ""; - } + public String next(final int n) throws JSONException + { + if (n == 0) { return ""; } final char[] chars = new char[n]; int pos = 0; - while (pos < n) { + while (pos < n) + { chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } + if (end()) { throw syntaxError("Substring bounds error"); } pos += 1; } return new String(chars); @@ -192,12 +200,12 @@ public class JSONTokener { * * @throws JSONException */ - public char nextClean() throws JSONException { - for (;;) { + public char nextClean() throws JSONException + { + for (;;) + { final char c = this.next(); - if ((c == 0) || (c > ' ')) { - return c; - } + if ((c == 0) || (c > ' ')) { return c; } } } @@ -212,19 +220,23 @@ public class JSONTokener { * * @throws JSONException Unterminated string. */ - public String nextString(final char quote) throws JSONException { + public String nextString(final char quote) throws JSONException + { char c; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (;;) + { c = this.next(); - switch (c) { + switch (c) + { case 0: case '\n': case '\r': - throw this.syntaxError("Unterminated string"); + throw syntaxError("Unterminated string"); case '\\': c = this.next(); - switch (c) { + switch (c) + { case 'b': sb.append('\b'); break; @@ -250,13 +262,11 @@ public class JSONTokener { sb.append(c); break; default: - throw this.syntaxError("Illegal escape."); + throw syntaxError("Illegal escape."); } break; default: - if (c == quote) { - return sb.toString(); - } + if (c == quote) { return sb.toString(); } sb.append(c); } } @@ -269,13 +279,17 @@ public class JSONTokener { * * @return A string. */ - public String nextTo(final char delimiter) throws JSONException { + public String nextTo(final char delimiter) throws JSONException + { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (;;) + { final char c = this.next(); - if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) { - if (c != 0) { - this.back(); + if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) + { + if (c != 0) + { + back(); } return sb.toString().trim(); } @@ -291,14 +305,18 @@ public class JSONTokener { * * @return A string, trimmed. */ - public String nextTo(final String delimiters) throws JSONException { + public String nextTo(final String delimiters) throws JSONException + { char c; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (;;) + { c = this.next(); - if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) { - if (c != 0) { - this.back(); + if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) + { + if (c != 0) + { + back(); } return sb.toString().trim(); } @@ -314,18 +332,20 @@ public class JSONTokener { * * @throws JSONException If syntax error. */ - public Object nextValue() throws JSONException { - char c = this.nextClean(); + public Object nextValue() throws JSONException + { + char c = nextClean(); String string; - switch (c) { + switch (c) + { case '"': case '\'': - return this.nextString(c); + return nextString(c); case '{': - this.back(); + back(); return new JSONObject(this); case '[': - this.back(); + back(); return new JSONArray(this); } /* @@ -336,15 +356,14 @@ public class JSONTokener { * formatting character. */ final StringBuilder sb = new StringBuilder(); - while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0)) { + while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0)) + { sb.append(c); c = this.next(); } - this.back(); + back(); string = sb.toString().trim(); - if ("".equals(string)) { - throw this.syntaxError("Missing value"); - } + if ("".equals(string)) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(string); } @@ -356,27 +375,34 @@ public class JSONTokener { * * @return The requested character, or zero if the requested character is not found. */ - public char skipTo(final char to) throws JSONException { + public char skipTo(final char to) throws JSONException + { char c; - try { - final long startIndex = this.index; - final long startCharacter = this.character; - final long startLine = this.line; - this.reader.mark(1000000); - do { + try + { + final long startIndex = index; + final long startCharacter = character; + final long startLine = line; + reader.mark(1000000); + do + { c = this.next(); - if (c == 0) { - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; + if (c == 0) + { + reader.reset(); + index = startIndex; + character = startCharacter; + line = startLine; return c; } - } while (c != to); - } catch (final IOException exception) { + } + while (c != to); + } + catch (final IOException exception) + { throw new JSONException(exception); } - this.back(); + back(); return c; } @@ -387,8 +413,9 @@ public class JSONTokener { * * @return A JSONException object, suitable for throwing */ - public JSONException syntaxError(final String message) { - return new JSONException(message + this.toString()); + public JSONException syntaxError(final String message) + { + return new JSONException(message + toString()); } /** @@ -397,7 +424,8 @@ public class JSONTokener { * @return " at {index} [character {character} line {line}]" */ @Override - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; + public String toString() + { + return " at " + index + " [character " + character + " line " + line + "]"; } } diff --git a/src/main/java/com/intellectualcrafters/json/JSONWriter.java b/src/main/java/com/intellectualcrafters/json/JSONWriter.java index 7530c40f2..52ac862ce 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONWriter.java +++ b/src/main/java/com/intellectualcrafters/json/JSONWriter.java @@ -7,33 +7,34 @@ import java.io.Writer; * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. - * + * * A JSONWriter instance provides a value method for appending values to the text, and a key * method for adding keys before values in objects. There are array and endArray methods that * make and bound array values, and object and endObject methods which make and bound object * values. All of these methods return the JSONWriter instance, permitting a cascade style. For example, - * - * + * + * *
        * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
        * 
      - * + * * which writes - * - * + * + * *
        * {"JSON":"Hello, World!"}
        * 
      - * + * * The first method called must be array or object. There are no methods for adding commas or * colons. JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep. - * + * * This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org * @version 2011-11-24 */ -public class JSONWriter { +public class JSONWriter +{ private static final int maxdepth = 200; /** * The writer that will receive the output. @@ -59,12 +60,13 @@ public class JSONWriter { /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ - public JSONWriter(final Writer w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; + public JSONWriter(final Writer w) + { + comma = false; + mode = 'i'; + stack = new JSONObject[maxdepth]; + top = 0; + writer = w; } /** @@ -76,23 +78,28 @@ public class JSONWriter { * * @throws JSONException If the value is out of sequence. */ - private JSONWriter append(final String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if ((this.mode == 'o') || (this.mode == 'a')) { - try { - if (this.comma && (this.mode == 'a')) { - this.writer.write(','); + private JSONWriter append(final String string) throws JSONException + { + if (string == null) { throw new JSONException("Null pointer"); } + if ((mode == 'o') || (mode == 'a')) + { + try + { + if (comma && (mode == 'a')) + { + writer.write(','); } - this.writer.write(string); - } catch (final IOException e) { + writer.write(string); + } + catch (final IOException e) + { throw new JSONException(e); } - if (this.mode == 'o') { - this.mode = 'k'; + if (mode == 'o') + { + mode = 'k'; } - this.comma = true; + comma = true; return this; } throw new JSONException("Value out of sequence."); @@ -107,11 +114,13 @@ public class JSONWriter { * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as * a key or after the end of the outermost array or object). */ - public JSONWriter array() throws JSONException { - if ((this.mode == 'i') || (this.mode == 'o') || (this.mode == 'a')) { - this.push(null); - this.append("["); - this.comma = false; + public JSONWriter array() throws JSONException + { + if ((mode == 'i') || (mode == 'o') || (mode == 'a')) + { + push(null); + append("["); + comma = false; return this; } throw new JSONException("Misplaced array."); @@ -127,17 +136,19 @@ public class JSONWriter { * * @throws JSONException If unbalanced. */ - private JSONWriter end(final char mode, final char c) throws JSONException { - if (this.mode != mode) { - throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); + private JSONWriter end(final char mode, final char c) throws JSONException + { + if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } + pop(mode); + try + { + writer.write(c); } - this.pop(mode); - try { - this.writer.write(c); - } catch (final IOException e) { + catch (final IOException e) + { throw new JSONException(e); } - this.comma = true; + comma = true; return this; } @@ -148,8 +159,9 @@ public class JSONWriter { * * @throws JSONException If incorrectly nested. */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); + public JSONWriter endArray() throws JSONException + { + return end('a', ']'); } /** @@ -159,8 +171,9 @@ public class JSONWriter { * * @throws JSONException If incorrectly nested. */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); + public JSONWriter endObject() throws JSONException + { + return end('k', '}'); } /** @@ -174,22 +187,26 @@ public class JSONWriter { * @throws JSONException If the key is out of place. For example, keys do not belong in arrays or if the key is * null. */ - public JSONWriter key(final String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); - if (this.comma) { - this.writer.write(','); + public JSONWriter key(final String string) throws JSONException + { + if (string == null) { throw new JSONException("Null key."); } + if (mode == 'k') + { + try + { + stack[top - 1].putOnce(string, Boolean.TRUE); + if (comma) + { + writer.write(','); } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; + writer.write(JSONObject.quote(string)); + writer.write(':'); + comma = false; + mode = 'o'; return this; - } catch (final IOException e) { + } + catch (final IOException e) + { throw new JSONException(e); } } @@ -205,14 +222,17 @@ public class JSONWriter { * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as * a key or after the end of the outermost array or object). */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; + public JSONWriter object() throws JSONException + { + if (mode == 'i') + { + mode = 'o'; } - if ((this.mode == 'o') || (this.mode == 'a')) { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; + if ((mode == 'o') || (mode == 'a')) + { + append("{"); + push(new JSONObject()); + comma = false; return this; } throw new JSONException("Misplaced object."); @@ -225,16 +245,13 @@ public class JSONWriter { * * @throws JSONException If nesting is wrong. */ - private void pop(final char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - final char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; + private void pop(final char c) throws JSONException + { + if (top <= 0) { throw new JSONException("Nesting error."); } + final char m = stack[top - 1] == null ? 'a' : 'k'; + if (m != c) { throw new JSONException("Nesting error."); } + top -= 1; + mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k'; } /** @@ -244,13 +261,12 @@ public class JSONWriter { * * @throws JSONException If nesting is too deep. */ - private void push(final JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; + private void push(final JSONObject jo) throws JSONException + { + if (top >= maxdepth) { throw new JSONException("Nesting too deep."); } + stack[top] = jo; + mode = jo == null ? 'a' : 'k'; + top += 1; } /** @@ -262,8 +278,9 @@ public class JSONWriter { * * @throws JSONException */ - public JSONWriter value(final boolean b) throws JSONException { - return this.append(b ? "true" : "false"); + public JSONWriter value(final boolean b) throws JSONException + { + return append(b ? "true" : "false"); } /** @@ -275,7 +292,8 @@ public class JSONWriter { * * @throws JSONException If the number is not finite. */ - public JSONWriter value(final double d) throws JSONException { + public JSONWriter value(final double d) throws JSONException + { return this.value(new Double(d)); } @@ -288,8 +306,9 @@ public class JSONWriter { * * @throws JSONException */ - public JSONWriter value(final long l) throws JSONException { - return this.append(Long.toString(l)); + public JSONWriter value(final long l) throws JSONException + { + return append(Long.toString(l)); } /** @@ -302,7 +321,8 @@ public class JSONWriter { * * @throws JSONException If the value is out of sequence. */ - public JSONWriter value(final Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); + public JSONWriter value(final Object object) throws JSONException + { + return append(JSONObject.valueToString(object)); } } diff --git a/src/main/java/com/intellectualcrafters/json/Kim.java b/src/main/java/com/intellectualcrafters/json/Kim.java index e8e90a7a8..391bcf4e2 100644 --- a/src/main/java/com/intellectualcrafters/json/Kim.java +++ b/src/main/java/com/intellectualcrafters/json/Kim.java @@ -5,28 +5,29 @@ package com.intellectualcrafters.json; * byte. The last byte of a character never has the MSB reset. Every byte that is not the last byte has the MSB set. Kim * stands for "Keep it minimal". A Unicode character is never longer than 3 bytes. Every byte contributes 7 bits to the * character. ASCII is unmodified. - * + * * Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF U+FFFF four bytes U+10FFFF - * + * * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one byte smaller when encoded in Kim compared * to UTF-8. - * + * * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, Avestan, Balinese, Batak, Bopomofo, * Buginese, Buhid, Carian, Cherokee, Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, Glagolitic, * Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, * Lycian, Lydian, Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old Turkic, Oriya, * Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. - * + * * A kim object can be constructed from an ordinary UTF-16 string, or from a byte array. A kim object can produce a * UTF-16 string. - * + * * As with UTF-8, it is possible to detect character boundaries within a byte sequence. UTF-8 is one of the world's * great inventions. While Kim is more efficient, it is not clear that it is worth the expense of transition. * * @version 2013-04-18 */ -public class Kim { +public class Kim +{ /** * The number of bytes in the kim. The number of bytes can be as much as three times the number of characters. */ @@ -51,23 +52,26 @@ public class Kim { * @param from The index of the first byte. * @param thru The index of the last byte plus one. */ - public Kim(final byte[] bytes, final int from, final int thru) { + public Kim(final byte[] bytes, final int from, final int thru) + { // As the bytes are copied into the new kim, a hashcode is computed // using a // modified Fletcher code. int sum = 1; int value; - this.hashcode = 0; - this.length = thru - from; - if (this.length > 0) { - this.bytes = new byte[this.length]; - for (int at = 0; at < this.length; at += 1) { + hashcode = 0; + length = thru - from; + if (length > 0) + { + this.bytes = new byte[length]; + for (int at = 0; at < length; at += 1) + { value = bytes[at + from] & 0xFF; sum += value; - this.hashcode += sum; + hashcode += sum; this.bytes[at] = (byte) value; } - this.hashcode += sum << 16; + hashcode += sum << 16; } } @@ -77,7 +81,8 @@ public class Kim { * @param bytes The byte array. * @param length The number of bytes. */ - public Kim(final byte[] bytes, final int length) { + public Kim(final byte[] bytes, final int length) + { this(bytes, 0, length); } @@ -88,7 +93,8 @@ public class Kim { * @param from The point at which to take bytes. * @param thru The point at which to stop taking bytes. */ - public Kim(final Kim kim, final int from, final int thru) { + public Kim(final Kim kim, final int from, final int thru) + { this(kim.bytes, from, thru); } @@ -99,78 +105,92 @@ public class Kim { * * @throws JSONException if surrogate pair mismatch. */ - public Kim(final String string) throws JSONException { + public Kim(final String string) throws JSONException + { final int stringLength = string.length(); - this.hashcode = 0; - this.length = 0; + hashcode = 0; + length = 0; // First pass: Determine the length of the kim, allowing for the UTF-16 // to UTF-32 conversion, and then the UTF-32 to Kim conversion. - if (stringLength > 0) { - for (int i = 0; i < stringLength; i += 1) { + if (stringLength > 0) + { + for (int i = 0; i < stringLength; i += 1) + { final int c = string.charAt(i); - if (c <= 0x7F) { - this.length += 1; - } else if (c <= 0x3FFF) { - this.length += 2; - } else { - if ((c >= 0xD800) && (c <= 0xDFFF)) { + if (c <= 0x7F) + { + length += 1; + } + else if (c <= 0x3FFF) + { + length += 2; + } + else + { + if ((c >= 0xD800) && (c <= 0xDFFF)) + { i += 1; final int d = string.charAt(i); - if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) { - throw new JSONException("Bad UTF16"); - } + if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) { throw new JSONException("Bad UTF16"); } } - this.length += 3; + length += 3; } } // Second pass: Allocate a byte array and fill that array with the // conversion // while computing the hashcode. - this.bytes = new byte[this.length]; + bytes = new byte[length]; int at = 0; int b; int sum = 1; - for (int i = 0; i < stringLength; i += 1) { + for (int i = 0; i < stringLength; i += 1) + { int character = string.charAt(i); - if (character <= 0x7F) { - this.bytes[at] = (byte) character; + if (character <= 0x7F) + { + bytes[at] = (byte) character; sum += character; - this.hashcode += sum; + hashcode += sum; at += 1; - } else if (character <= 0x3FFF) { + } + else if (character <= 0x3FFF) + { b = 0x80 | (character >>> 7); - this.bytes[at] = (byte) b; + bytes[at] = (byte) b; sum += b; - this.hashcode += sum; + hashcode += sum; at += 1; b = character & 0x7F; - this.bytes[at] = (byte) b; + bytes[at] = (byte) b; sum += b; - this.hashcode += sum; + hashcode += sum; at += 1; - } else { - if ((character >= 0xD800) && (character <= 0xDBFF)) { + } + else + { + if ((character >= 0xD800) && (character <= 0xDBFF)) + { i += 1; character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; } b = 0x80 | (character >>> 14); - this.bytes[at] = (byte) b; + bytes[at] = (byte) b; sum += b; - this.hashcode += sum; + hashcode += sum; at += 1; b = 0x80 | ((character >>> 7) & 0xFF); - this.bytes[at] = (byte) b; + bytes[at] = (byte) b; sum += b; - this.hashcode += sum; + hashcode += sum; at += 1; b = character & 0x7F; - this.bytes[at] = (byte) b; + bytes[at] = (byte) b; sum += b; - this.hashcode += sum; + hashcode += sum; at += 1; } } - this.hashcode += sum << 16; + hashcode += sum << 16; } } @@ -183,10 +203,9 @@ public class Kim { * * @throws JSONException if the character is not representable in a kim. */ - public static int characterSize(final int character) throws JSONException { - if ((character < 0) || (character > 0x10FFFF)) { - throw new JSONException("Bad character " + character); - } + public static int characterSize(final int character) throws JSONException + { + if ((character < 0) || (character > 0x10FFFF)) { throw new JSONException("Bad character " + character); } return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; } @@ -199,24 +218,22 @@ public class Kim { * @throws JSONException if at does not point to a valid character. * @return a Unicode character between 0 and 0x10FFFF. */ - public int characterAt(final int at) throws JSONException { + public int characterAt(final int at) throws JSONException + { final int c = get(at); - if ((c & 0x80) == 0) { - return c; - } + if ((c & 0x80) == 0) { return c; } int character; final int c1 = get(at + 1); - if ((c1 & 0x80) == 0) { + if ((c1 & 0x80) == 0) + { character = ((c & 0x7F) << 7) | c1; - if (character > 0x7F) { - return character; - } - } else { + if (character > 0x7F) { return character; } + } + else + { final int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; - if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) { - return character; - } + if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) { return character; } } throw new JSONException("Bad character at " + at); } @@ -229,9 +246,10 @@ public class Kim { * * @return The position immediately after the copy. */ - public int copy(final byte[] bytes, final int at) { - System.arraycopy(this.bytes, 0, bytes, at, this.length); - return at + this.length; + public int copy(final byte[] bytes, final int at) + { + System.arraycopy(this.bytes, 0, bytes, at, length); + return at + length; } /** @@ -242,18 +260,13 @@ public class Kim { * @return true if this and obj are both kim objects containing identical byte sequences. */ @Override - public boolean equals(final Object obj) { - if (!(obj instanceof Kim)) { - return false; - } + public boolean equals(final Object obj) + { + if (!(obj instanceof Kim)) { return false; } final Kim that = (Kim) obj; - if (this == that) { - return true; - } - if (this.hashcode != that.hashcode) { - return false; - } - return java.util.Arrays.equals(this.bytes, that.bytes); + if (this == that) { return true; } + if (hashcode != that.hashcode) { return false; } + return java.util.Arrays.equals(bytes, that.bytes); } /** @@ -265,19 +278,19 @@ public class Kim { * * @throws JSONException if there is no byte at that position. */ - public int get(final int at) throws JSONException { - if ((at < 0) || (at > this.length)) { - throw new JSONException("Bad character at " + at); - } - return (this.bytes[at]) & 0xFF; + public int get(final int at) throws JSONException + { + if ((at < 0) || (at > length)) { throw new JSONException("Bad character at " + at); } + return (bytes[at]) & 0xFF; } /** * Returns a hash code value for the kim. */ @Override - public int hashCode() { - return this.hashcode; + public int hashCode() + { + return hashcode; } /** @@ -289,25 +302,31 @@ public class Kim { * @throws JSONException if the kim is not valid. */ @Override - public String toString() throws JSONException { - if (this.string == null) { + public String toString() throws JSONException + { + if (string == null) + { int c; int length = 0; final char chars[] = new char[this.length]; - for (int at = 0; at < this.length; at += characterSize(c)) { - c = this.characterAt(at); - if (c < 0x10000) { + for (int at = 0; at < this.length; at += characterSize(c)) + { + c = characterAt(at); + if (c < 0x10000) + { chars[length] = (char) c; length += 1; - } else { + } + else + { chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10)); length += 1; chars[length] = (char) (0xDC00 | (c & 0x03FF)); length += 1; } } - this.string = new String(chars, 0, length); + string = new String(chars, 0, length); } - return this.string; + return string; } } diff --git a/src/main/java/com/intellectualcrafters/json/Property.java b/src/main/java/com/intellectualcrafters/json/Property.java index cdbaba42d..db31b325d 100644 --- a/src/main/java/com/intellectualcrafters/json/Property.java +++ b/src/main/java/com/intellectualcrafters/json/Property.java @@ -30,7 +30,8 @@ import java.util.Properties; * @author JSON.org * @version 2014-05-03 */ -public class Property { +public class Property +{ /** * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. * @@ -40,11 +41,14 @@ public class Property { * * @throws JSONException */ - public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException { + public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException + { final JSONObject jo = new JSONObject(); - if ((properties != null) && !properties.isEmpty()) { + if ((properties != null) && !properties.isEmpty()) + { final Enumeration enumProperties = properties.propertyNames(); - while (enumProperties.hasMoreElements()) { + while (enumProperties.hasMoreElements()) + { final String name = (String) enumProperties.nextElement(); jo.put(name, properties.getProperty(name)); } @@ -61,11 +65,14 @@ public class Property { * * @throws JSONException */ - public static Properties toProperties(final JSONObject jo) throws JSONException { + public static Properties toProperties(final JSONObject jo) throws JSONException + { final Properties properties = new Properties(); - if (jo != null) { + if (jo != null) + { final Iterator keys = jo.keys(); - while (keys.hasNext()) { + while (keys.hasNext()) + { final String name = keys.next(); properties.put(name, jo.getString(name)); } diff --git a/src/main/java/com/intellectualcrafters/json/XML.java b/src/main/java/com/intellectualcrafters/json/XML.java index 52f6ea71e..594660570 100644 --- a/src/main/java/com/intellectualcrafters/json/XML.java +++ b/src/main/java/com/intellectualcrafters/json/XML.java @@ -8,7 +8,8 @@ import java.util.Iterator; * @author JSON.org * @version 2014-05-03 */ -public class XML { +public class XML +{ public static final Character AMP = '&'; public static final Character APOS = '\''; public static final Character BANG = '!'; @@ -19,11 +20,14 @@ public class XML { public static final Character QUOT = '"'; public static final Character SLASH = '/'; - public static String escape(final String string) { + public static String escape(final String string) + { final StringBuilder sb = new StringBuilder(string.length()); - for (int i = 0, length = string.length(); i < length; i++) { + for (int i = 0, length = string.length(); i < length; i++) + { final char c = string.charAt(i); - switch (c) { + switch (c) + { case '&': sb.append("&"); break; @@ -53,16 +57,14 @@ public class XML { * * @throws JSONException */ - public static void noSpace(final String string) throws JSONException { + public static void noSpace(final String string) throws JSONException + { int i; final int length = string.length(); - if (length == 0) { - throw new JSONException("Empty string."); - } - for (i = 0; i < length; i += 1) { - if (Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + "' contains a space character."); - } + if (length == 0) { throw new JSONException("Empty string."); } + for (i = 0; i < length; i += 1) + { + if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } @@ -77,7 +79,8 @@ public class XML { * * @throws JSONException */ - private static boolean parse(final XMLTokener x, final JSONObject context, final String name) throws JSONException { + private static boolean parse(final XMLTokener x, final JSONObject context, final String name) throws JSONException + { char c; int i; JSONObject jsonobject = null; @@ -95,20 +98,28 @@ public class XML { // << token = x.nextToken(); // "); return false; } x.back(); - } else if (c == '[') { + } + else if (c == '[') + { token = x.nextToken(); - if ("CDATA".equals(token)) { - if (x.next() == '[') { + if ("CDATA".equals(token)) + { + if (x.next() == '[') + { string = x.nextCDATA(); - if (string.length() > 0) { + if (string.length() > 0) + { context.accumulate("content", string); } return false; @@ -117,99 +128,130 @@ public class XML { throw x.syntaxError("Expected 'CDATA['"); } i = 1; - do { + do + { token = x.nextMeta(); - if (token == null) { + if (token == null) + { throw x.syntaxError("Missing '>' after ' 0); + } + while (i > 0); return false; - } else if (token == QUEST) { + } + else if (token == QUEST) + { // "); return false; - } else if (token == SLASH) { + } + else if (token == SLASH) + { // Close tag - } else if (token == SLASH) { - if (x.nextToken() != GT) { - throw x.syntaxError("Misshaped tag"); - } - if (jsonobject.length() > 0) { + } + else if (token == SLASH) + { + if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } + if (jsonobject.length() > 0) + { context.accumulate(tagName, jsonobject); - } else { + } + else + { context.accumulate(tagName, ""); } return false; // Content, between <...> and - } else if (token == GT) { - for (;;) { + } + else if (token == GT) + { + for (;;) + { token = x.nextContent(); - if (token == null) { - if (tagName != null) { - throw x.syntaxError("Unclosed tag " + tagName); - } + if (token == null) + { + if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); } return false; - } else if (token instanceof String) { + } + else if (token instanceof String) + { string = (String) token; - if (string.length() > 0) { + if (string.length() > 0) + { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element - } else if (token == LT) { - if (parse(x, jsonobject, tagName)) { - if (jsonobject.length() == 0) { + } + else if (token == LT) + { + if (parse(x, jsonobject, tagName)) + { + if (jsonobject.length() == 0) + { context.accumulate(tagName, ""); - } else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) { + } + else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) + { context.accumulate(tagName, jsonobject.opt("content")); - } else { + } + else + { context.accumulate(tagName, jsonobject); } return false; } } } - } else { + } + else + { throw x.syntaxError("Misshaped tag"); } } @@ -225,43 +267,42 @@ public class XML { * * @return A simple JSON value. */ - public static Object stringToValue(final String string) { - if ("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if ("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if ("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } + public static Object stringToValue(final String string) + { + if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } + if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } + if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } // If it might be a number, try converting it, first as a Long, and then // as a // Double. If that doesn't work, return the string. - try { + try + { final char initial = string.charAt(0); - if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) { + if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) + { final Long value = new Long(string); - if (value.toString().equals(string)) { - return value; - } + if (value.toString().equals(string)) { return value; } } - } catch (final Exception ignore) { - try { + } + catch (final Exception ignore) + { + try + { final Double value = new Double(string); - if (value.toString().equals(string)) { - return value; - } - } catch (final Exception ignoreAlso) { + if (value.toString().equals(string)) { return value; } } + catch (final Exception ignoreAlso) + {} } return string; } - public static JSONObject toJSONObject(final String string) throws JSONException { + public static JSONObject toJSONObject(final String string) throws JSONException + { final JSONObject jo = new JSONObject(); final XMLTokener x = new XMLTokener(string); - while (x.more() && x.skipPast("<")) { + while (x.more() && x.skipPast("<")) + { parse(x, jo, null); } return jo; @@ -276,7 +317,8 @@ public class XML { * * @throws JSONException */ - public static String toString(final Object object) throws JSONException { + public static String toString(final Object object) throws JSONException + { return toString(object, null); } @@ -290,7 +332,8 @@ public class XML { * * @throws JSONException */ - public static String toString(Object object, final String tagName) throws JSONException { + public static String toString(Object object, final String tagName) throws JSONException + { final StringBuilder sb = new StringBuilder(); int i; JSONArray ja; @@ -300,9 +343,11 @@ public class XML { int length; String string; Object value; - if (object instanceof JSONObject) { + if (object instanceof JSONObject) + { // Emit - if (tagName != null) { + if (tagName != null) + { sb.append('<'); sb.append(tagName); sb.append('>'); @@ -310,34 +355,46 @@ public class XML { // Loop thru the keys. jo = (JSONObject) object; keys = jo.keys(); - while (keys.hasNext()) { + while (keys.hasNext()) + { key = keys.next(); value = jo.opt(key); - if (value == null) { + if (value == null) + { value = ""; } string = value instanceof String ? (String) value : null; // Emit content in body - if ("content".equals(key)) { - if (value instanceof JSONArray) { + if ("content".equals(key)) + { + if (value instanceof JSONArray) + { ja = (JSONArray) value; length = ja.length(); - for (i = 0; i < length; i += 1) { - if (i > 0) { + for (i = 0; i < length; i += 1) + { + if (i > 0) + { sb.append('\n'); } sb.append(escape(ja.get(i).toString())); } - } else { + } + else + { sb.append(escape(value.toString())); } // Emit an array of similar keys - } else if (value instanceof JSONArray) { + } + else if (value instanceof JSONArray) + { ja = (JSONArray) value; length = ja.length(); - for (i = 0; i < length; i += 1) { + for (i = 0; i < length; i += 1) + { value = ja.get(i); - if (value instanceof JSONArray) { + if (value instanceof JSONArray) + { sb.append('<'); sb.append(key); sb.append('>'); @@ -345,20 +402,27 @@ public class XML { sb.append("'); - } else { + } + else + { sb.append(toString(value, key)); } } - } else if ("".equals(value)) { + } + else if ("".equals(value)) + { sb.append('<'); sb.append(key); sb.append("/>"); // Emit a new tag - } else { + } + else + { sb.append(toString(value, key)); } } - if (tagName != null) { + if (tagName != null) + { // Emit the close tag sb.append(" element. - } else { - if (object.getClass().isArray()) { + } + else + { + if (object.getClass().isArray()) + { object = new JSONArray(object); } - if (object instanceof JSONArray) { + if (object instanceof JSONArray) + { ja = (JSONArray) object; length = ja.length(); - for (i = 0; i < length; i += 1) { + for (i = 0; i < length; i += 1) + { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); - } else { + } + else + { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; } diff --git a/src/main/java/com/intellectualcrafters/json/XMLTokener.java b/src/main/java/com/intellectualcrafters/json/XMLTokener.java index 94edd5792..e34e6dbe2 100644 --- a/src/main/java/com/intellectualcrafters/json/XMLTokener.java +++ b/src/main/java/com/intellectualcrafters/json/XMLTokener.java @@ -6,12 +6,14 @@ package com.intellectualcrafters.json; * @author JSON.org * @version 2014-05-03 */ -public class XMLTokener extends JSONTokener { +public class XMLTokener extends JSONTokener +{ /** * The table of entity values. It initially contains Character values for amp, apos, gt, lt, quot. */ public static final java.util.HashMap entity; - static { + static + { entity = new java.util.HashMap(8); entity.put("amp", XML.AMP); entity.put("apos", XML.APOS); @@ -25,7 +27,8 @@ public class XMLTokener extends JSONTokener { * * @param s A source string. */ - public XMLTokener(final String s) { + public XMLTokener(final String s) + { super(s); } @@ -36,18 +39,19 @@ public class XMLTokener extends JSONTokener { * * @throws JSONException If the ]]> is not found. */ - public String nextCDATA() throws JSONException { + public String nextCDATA() throws JSONException + { char c; int i; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (;;) + { c = next(); - if (end()) { - throw syntaxError("Unclosed CDATA"); - } + if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; - if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) { + if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) + { sb.setLength(i); return sb.toString(); } @@ -62,27 +66,31 @@ public class XMLTokener extends JSONTokener { * * @throws JSONException */ - public Object nextContent() throws JSONException { + public Object nextContent() throws JSONException + { char c; StringBuilder sb; - do { + do + { c = next(); - } while (Character.isWhitespace(c)); - if (c == 0) { - return null; - } - if (c == '<') { - return XML.LT; } + while (Character.isWhitespace(c)); + if (c == 0) { return null; } + if (c == '<') { return XML.LT; } sb = new StringBuilder(); - for (;;) { - if ((c == '<') || (c == 0)) { + for (;;) + { + if ((c == '<') || (c == 0)) + { back(); return sb.toString().trim(); } - if (c == '&') { + if (c == '&') + { sb.append(nextEntity(c)); - } else { + } + else + { sb.append(c); } c = next(); @@ -99,15 +107,22 @@ public class XMLTokener extends JSONTokener { * * @throws JSONException If missing ';' in XML entity. */ - public Object nextEntity(final char ampersand) throws JSONException { + public Object nextEntity(final char ampersand) throws JSONException + { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (;;) + { final char c = next(); - if (Character.isLetterOrDigit(c) || (c == '#')) { + if (Character.isLetterOrDigit(c) || (c == '#')) + { sb.append(Character.toLowerCase(c)); - } else if (c == ';') { + } + else if (c == ';') + { break; - } else { + } + else + { throw syntaxError("Missing ';' in XML entity: &" + sb); } } @@ -124,13 +139,17 @@ public class XMLTokener extends JSONTokener { * * @throws JSONException If a string is not properly closed or if the XML is badly structured. */ - public Object nextMeta() throws JSONException { + public Object nextMeta() throws JSONException + { char c; char q; - do { + do + { c = next(); - } while (Character.isWhitespace(c)); - switch (c) { + } + while (Character.isWhitespace(c)); + switch (c) + { case 0: throw syntaxError("Misshaped meta tag"); case '<': @@ -148,22 +167,19 @@ public class XMLTokener extends JSONTokener { case '"': case '\'': q = c; - for (;;) { + for (;;) + { c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return Boolean.TRUE; - } + if (c == 0) { throw syntaxError("Unterminated string"); } + if (c == q) { return Boolean.TRUE; } } default: - for (;;) { + for (;;) + { c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { + if (Character.isWhitespace(c)) { return Boolean.TRUE; } + switch (c) + { case 0: case '<': case '>': @@ -188,14 +204,18 @@ public class XMLTokener extends JSONTokener { * * @throws JSONException If the XML is not well formed. */ - public Object nextToken() throws JSONException { + public Object nextToken() throws JSONException + { char c; char q; StringBuilder sb; - do { + do + { c = next(); - } while (Character.isWhitespace(c)); - switch (c) { + } + while (Character.isWhitespace(c)); + switch (c) + { case 0: throw syntaxError("Misshaped element"); case '<': @@ -215,30 +235,30 @@ public class XMLTokener extends JSONTokener { case '\'': q = c; sb = new StringBuilder(); - for (;;) { + for (;;) + { c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return sb.toString(); - } - if (c == '&') { + if (c == 0) { throw syntaxError("Unterminated string"); } + if (c == q) { return sb.toString(); } + if (c == '&') + { sb.append(nextEntity(c)); - } else { + } + else + { sb.append(c); } } default: // Name sb = new StringBuilder(); - for (;;) { + for (;;) + { sb.append(c); c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); - } - switch (c) { + if (Character.isWhitespace(c)) { return sb.toString(); } + switch (c) + { case 0: return sb.toString(); case '>': @@ -267,7 +287,8 @@ public class XMLTokener extends JSONTokener { * * @throws JSONException */ - public boolean skipPast(final String to) throws JSONException { + public boolean skipPast(final String to) throws JSONException + { boolean b; char c; int i; @@ -279,44 +300,44 @@ public class XMLTokener extends JSONTokener { * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ - for (i = 0; i < length; i += 1) { + for (i = 0; i < length; i += 1) + { c = next(); - if (c == 0) { - return false; - } + if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ - for (;;) { + for (;;) + { j = offset; b = true; /* Compare the circle buffer with the to string. */ - for (i = 0; i < length; i += 1) { - if (circle[j] != to.charAt(i)) { + for (i = 0; i < length; i += 1) + { + if (circle[j] != to.charAt(i)) + { b = false; break; } j += 1; - if (j >= length) { + if (j >= length) + { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ - if (b) { - return true; - } + if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); - if (c == 0) { - return false; - } + if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; - if (offset >= length) { + if (offset >= length) + { offset -= length; } } diff --git a/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/src/main/java/com/intellectualcrafters/plot/IPlotMain.java index 6988fd6a9..81facb35b 100644 --- a/src/main/java/com/intellectualcrafters/plot/IPlotMain.java +++ b/src/main/java/com/intellectualcrafters/plot/IPlotMain.java @@ -16,29 +16,29 @@ import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.sk89q.worldedit.WorldEdit; -public interface IPlotMain { - +public interface IPlotMain +{ + /** * Log a message to console * @param message */ - void log(String message); + void log(final String message); /** * Get the `PlotSquared` directory (e.g. /plugins/PlotSquared or /mods/PlotSquared) * @return */ File getDirectory(); - + /** * Wrap a player into a PlotPlayer object * @param obj * @return */ - PlotPlayer wrapPlayer(Object obj); - + PlotPlayer wrapPlayer(final Object obj); + /** * Disable the implementation * - If a full disable isn't feasibly, just disable what it can @@ -50,32 +50,32 @@ public interface IPlotMain { * @return */ int[] getPluginVersion(); - + /** * Get the version of Minecraft that is running * (used to check what protocols and such are supported) * @return */ int[] getServerVersion(); - + /** * Get the nms package prefix * @return */ String getNMSPackage(); - + /** * Get the schematic handler * @return */ SchematicHandler initSchematicHandler(); - + /** * Get the schematic handler * @return */ ChatManager initChatManager(); - + /** * The task manager will run and manage minecraft tasks * @return @@ -116,7 +116,7 @@ public interface IPlotMain { * Register the WorldEdit hook */ boolean initWorldEdit(); - + /** * Register TNT related events (if TNT protection is enabled) */ @@ -133,7 +133,7 @@ public interface IPlotMain { * @return */ BlockManager initBlockManager(); - + /** * Get the EventUtil class * @return @@ -157,24 +157,24 @@ public interface IPlotMain { * @return */ HybridUtils initHybridUtils(); - + /** * Start the metrics task */ void startMetrics(); - + /** * If a world is already loaded, set the generator (use NMS if required) * @param world */ - void setGenerator(String world); + void setGenerator(final String world); /** * Get the UUIDHandlerImplementation which will cache and provide UUIDs * @return */ UUIDHandlerImplementation initUUIDHandler(); - + /** * Get the InventoryUtil class (used for implementation specific inventory guis) * @return @@ -186,12 +186,12 @@ public interface IPlotMain { * @return */ boolean initPlotMeConverter(); - + /** * Unregister a PlotPlayer from cache e.g. if they have logged off * @param player */ - void unregister(PlotPlayer player); + void unregister(final PlotPlayer player); /** * Get the generator wrapper for a world (world) and generator (name) @@ -199,7 +199,7 @@ public interface IPlotMain { * @param name * @return */ - PlotGenerator getGenerator(String world, String name); + PlotGenerator getGenerator(final String world, final String name); /** * Register the chunk processor which will clean out chunks that have too many blockstates or entities @@ -216,7 +216,7 @@ public interface IPlotMain { * @return */ String getServerName(); - + /** * Get the class that will manage player titles * @return diff --git a/src/main/java/com/intellectualcrafters/plot/PS.java b/src/main/java/com/intellectualcrafters/plot/PS.java index 13a0cc60c..998e4d118 100644 --- a/src/main/java/com/intellectualcrafters/plot/PS.java +++ b/src/main/java/com/intellectualcrafters/plot/PS.java @@ -90,11 +90,12 @@ import com.sk89q.worldedit.WorldEdit; * @author Sauilitired | Citymonstret * @author boy0001 | Empire92 */ -public class PS { +public class PS +{ // protected static: public static PS instance; - + // private final: private final HashMap plotworlds = new HashMap<>(); private final HashMap plotmanagers = new HashMap<>(); @@ -127,57 +128,68 @@ public class PS { * Initialize PlotSquared with the desired Implementation class * @param imp_class */ - public PS(final IPlotMain imp_class, String platform) { - try { + public PS(final IPlotMain imp_class, final String platform) + { + try + { instance = this; - this.thread = Thread.currentThread(); + thread = Thread.currentThread(); SetupUtils.generators = new HashMap<>(); IMP = imp_class; new ReflectionUtils(IMP.getNMSPackage()); URL url; - try { + try + { url = PS.class.getProtectionDomain().getCodeSource().getLocation(); FILE = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); - } catch (Exception e) { + } + catch (final Exception e) + { e.printStackTrace(); FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared.jar"); - if (!FILE.exists()) { + if (!FILE.exists()) + { FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar"); } } VERSION = IMP.getPluginVersion(); PLATFORM = platform; EconHandler.manager = IMP.getEconomyHandler(); - if (getJavaVersion() < 1.7) { + if (getJavaVersion() < 1.7) + { log(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 1.7."); // Didn't know of any other link :D log(C.PREFIX.s() + "&cURL: &6https://java.com/en/download/index.jsp"); IMP.disable(); return; } - if (getJavaVersion() < 1.8) { + if (getJavaVersion() < 1.8) + { log(C.PREFIX.s() + "&cIt's really recommended to run Java 1.8, as it increases performance"); } - this.TASK = IMP.getTaskManager(); - if (C.ENABLED.s().length() > 0) { + TASK = IMP.getTaskManager(); + if (C.ENABLED.s().length() > 0) + { log(C.ENABLED.s()); } setupConfigs(); - this.translationFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "PlotSquared.use_THIS.yml"); + translationFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "PlotSquared.use_THIS.yml"); C.load(translationFile); setupDefaultFlags(); setupDatabase(); CommentManager.registerDefaultInboxes(); // Tasks - if (Settings.KILL_ROAD_MOBS || Settings.KILL_ROAD_VEHICLES) { + if (Settings.KILL_ROAD_MOBS || Settings.KILL_ROAD_VEHICLES) + { IMP.runEntityTask(); } - if (IMP.initWorldEdit()) { + if (IMP.initWorldEdit()) + { worldedit = WorldEdit.getInstance(); WorldEdit.getInstance().getEventBus().register(new WESubscriber()); MainCommand.getInstance().createCommand(new WE_Anywhere()); } - + // Events IMP.registerCommands(); IMP.registerPlayerEvents(); @@ -185,30 +197,42 @@ public class PS { IMP.registerPlotPlusEvents(); IMP.registerForceFieldEvents(); IMP.registerWorldEvents(); - if (Settings.METRICS) { + if (Settings.METRICS) + { IMP.startMetrics(); - } else { + } + else + { log("&dUsing metrics will allow us to improve the plugin, please consider it :)"); } IMP.startMetrics(); - if (Settings.TNT_LISTENER) { + if (Settings.TNT_LISTENER) + { IMP.registerTNTListener(); } - if (Settings.CHUNK_PROCESSOR) { + if (Settings.CHUNK_PROCESSOR) + { IMP.registerChunkProcessor(); } // create UUIDWrapper UUIDHandler.implementation = IMP.initUUIDHandler(); - TaskManager.runTaskLater(new Runnable() { + TaskManager.runTaskLater(new Runnable() + { @Override - public void run() { + public void run() + { PS.debug("Starting UUID caching"); - UUIDHandler.startCaching(new Runnable() { + UUIDHandler.startCaching(new Runnable() + { @Override - public void run() { - for (Plot plot : getPlots()) { - if (plot.owner != null && plot.temp != -1) { - if (UUIDHandler.getName(plot.owner) == null) { + public void run() + { + for (final Plot plot : getPlots()) + { + if ((plot.owner != null) && (plot.temp != -1)) + { + if (UUIDHandler.getName(plot.owner) == null) + { UUIDHandler.implementation.unknown.add(plot.owner); } } @@ -235,27 +259,36 @@ public class PS { AbstractTitle.TITLE_CLASS = IMP.initTitleManager(); // Chat ChatManager.manager = IMP.initChatManager(); - + // Check for updates - TaskManager.runTaskAsync(new Runnable() { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - URL url = getUpdate(); - if (url != null) { + public void run() + { + final URL url = getUpdate(); + if (url != null) + { update = url; } - else if (LAST_VERSION != null && !StringMan.join(VERSION,".").equals(LAST_VERSION)) { + else if ((LAST_VERSION != null) && !StringMan.join(VERSION, ".").equals(LAST_VERSION)) + { log("&aThanks for updating from: " + LAST_VERSION + " to " + StringMan.join(VERSION, ".")); } } }); - + // PlotMe - if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME) { - TaskManager.runTaskLater(new Runnable() { - - public void run() { - if (IMP.initPlotMeConverter()) { + if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME) + { + TaskManager.runTaskLater(new Runnable() + { + + @Override + public void run() + { + if (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)!"); @@ -265,31 +298,41 @@ public class PS { } }, 200); } - + // Auto clearing - if (Settings.AUTO_CLEAR) { + if (Settings.AUTO_CLEAR) + { ExpireManager.runTask(); } - + // World generators: final ConfigurationSection section = config.getConfigurationSection("worlds"); - if (section != null) { - for (String world : section.getKeys(false)) { - if (world.equals("CheckingPlotSquaredGenerator")) { + if (section != null) + { + for (final String world : section.getKeys(false)) + { + if (world.equals("CheckingPlotSquaredGenerator")) + { continue; } - if (BlockManager.manager.isWorld(world)) { + if (BlockManager.manager.isWorld(world)) + { IMP.setGenerator(world); } } - TaskManager.runTaskLater(new Runnable() { + TaskManager.runTaskLater(new Runnable() + { @Override - public void run() { - for (String world : section.getKeys(false)) { - if (world.equals("CheckingPlotSquaredGenerator")) { + public void run() + { + for (final String world : section.getKeys(false)) + { + if (world.equals("CheckingPlotSquaredGenerator")) + { continue; } - if (!BlockManager.manager.isWorld(world) || (BlockManager.manager.isWorld(world) && !isPlotWorld(world))) { + if (!BlockManager.manager.isWorld(world) || (BlockManager.manager.isWorld(world) && !isPlotWorld(world))) + { 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 as well"); PS.debug("&8 - &7Your world management plugin may be faulty. Consider using an up to date plugin."); @@ -299,7 +342,7 @@ public class PS { } }, 1); } - + // Copy files copyFile("automerge.js", "scripts"); copyFile("town.template", "templates"); @@ -310,49 +353,56 @@ public class PS { copyFile("italian.yml", "translations"); showDebug(); } - catch (Throwable e) { + catch (final Throwable e) + { e.printStackTrace(); } } - - public boolean isMainThread(Thread thread) { + + public boolean isMainThread(final Thread thread) + { return this.thread == thread; } - - public boolean checkVersion(int[] version, int major, int minor, int minor2) { + + public boolean checkVersion(final int[] version, final int major, final int minor, final int minor2) + { return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && (version[2] >= minor2)); } - + /** * Get the instance of PlotSquared * * @return the instance created by IPlotMain */ - public static PS get() { + public static PS get() + { return instance; } - + /** * Get the last PlotSquared version * @return last version in config or null */ - public String getLastVersion() { + public String getLastVersion() + { return LAST_VERSION; } - + /** * Get the current PlotSquared version * @return current version in config or null */ - public int[] getVersion() { + public int[] getVersion() + { return VERSION; } - + /** * Get the platform this is running on (Bukkit, Sponge) * @return */ - public String getPlatform() { + public String getPlatform() + { return PLATFORM; } @@ -362,18 +412,21 @@ public class PS { * @param message Message to log * @see IPlotMain#log(String) */ - public static void log(Object message) { + public static void log(final Object message) + { get().IMP.log(StringMan.getString(message)); } - + /** * Log a message to the IPlotMain logger * * @param message Message to log * @see IPlotMain#log(String) */ - public static void debug(final Object message) { - if (Settings.DEBUG) { + public static void debug(final Object message) + { + if (Settings.DEBUG) + { log(message); } } @@ -384,7 +437,8 @@ public class PS { * @return Database object * @see #getConnection() Get the database connection */ - public Database getDatabase() { + public Database getDatabase() + { return database; } @@ -394,9 +448,11 @@ public class PS { * * @param plot Plot Object to update */ - public void updatePlot(final Plot plot) { + public void updatePlot(final Plot plot) + { final String world = plot.world; - if (!plots.containsKey(world)) { + if (!plots.containsKey(world)) + { plots.put(world, new ConcurrentHashMap()); } plots.get(world).put(plot.id, plot); @@ -410,10 +466,9 @@ public class PS { * @return plot world | null if not existing * @see #getPlotWorldsString() Get all plot world names */ - public PlotWorld getPlotWorld(final String world) { - if (plotworlds.containsKey(world)) { - return plotworlds.get(world); - } + public PlotWorld getPlotWorld(final String world) + { + if (plotworlds.containsKey(world)) { return plotworlds.get(world); } return null; } @@ -425,10 +480,12 @@ public class PS { * @param manager PlotManager * @see #removePlotWorld(String) To remove the reference */ - public void addPlotWorld(final String world, final PlotWorld plotworld, final PlotManager manager) { + public void addPlotWorld(final String world, final PlotWorld plotworld, final PlotManager manager) + { plotworlds.put(world, plotworld); plotmanagers.put(world, manager); - if (!plots.containsKey(world)) { + if (!plots.containsKey(world)) + { plots.put(world, new ConcurrentHashMap()); } } @@ -439,7 +496,8 @@ public class PS { * @param world World name * @see #addPlotWorld(String, PlotWorld, PlotManager) To add a reference */ - public void removePlotWorld(final String world) { + public void removePlotWorld(final String world) + { plots.remove(world); plotmanagers.remove(world); plotworlds.remove(world); @@ -448,7 +506,8 @@ public class PS { /** * @param world World Name */ - public void removePlotWorldAbs(final String world) { + public void removePlotWorldAbs(final String world) + { plotmanagers.remove(world); plotworlds.remove(world); } @@ -462,26 +521,34 @@ public class PS { * @return HashMap containing the world name, and another map with the plot id and the plot object */ @Deprecated - public Map> getAllPlotsRaw() { + public Map> getAllPlotsRaw() + { return plots; } - + /** * A more generic way to filter plots - make your own method if you need complex filters * @param filters * @return */ - public Set getPlots(PlotFilter... filters) { - HashSet set = new HashSet<>(); - for (Entry> entry : plots.entrySet()) { - for (PlotFilter filter : filters) { - if (!filter.allowsWorld(entry.getKey())) { + public Set getPlots(final PlotFilter... filters) + { + final HashSet set = new HashSet<>(); + for (final Entry> entry : plots.entrySet()) + { + for (final PlotFilter filter : filters) + { + if (!filter.allowsWorld(entry.getKey())) + { continue; } } - for (Plot plot : entry.getValue().values()) { - for (PlotFilter filter : filters) { - if (!filter.allowsPlot(plot)) { + for (final Plot plot : entry.getValue().values()) + { + for (final PlotFilter filter : filters) + { + if (!filter.allowsPlot(plot)) + { continue; } } @@ -490,9 +557,6 @@ public class PS { } return set; } - - - /** * Set all the plots as a raw object @@ -500,48 +564,60 @@ public class PS { * @param plots */ @Deprecated - public void setAllPlotsRaw(final ConcurrentHashMap> plots) { + public void setAllPlotsRaw(final ConcurrentHashMap> plots) + { this.plots = plots; } - /** * Get all the plots in a single set * @return Set of Plot */ - public Set getPlots() { + public Set getPlots() + { int size = 0; - for (Entry> entry : plots.entrySet()) { - if (isPlotWorld(entry.getKey())) { + for (final Entry> entry : plots.entrySet()) + { + if (isPlotWorld(entry.getKey())) + { size += entry.getValue().size(); } } - Set result = new HashSet<>(size); - for (Entry> entry : plots.entrySet()) { - if (isPlotWorld(entry.getKey())) { + final Set result = new HashSet<>(size); + for (final Entry> entry : plots.entrySet()) + { + if (isPlotWorld(entry.getKey())) + { result.addAll(entry.getValue().values()); } } return result; } - + /** * Get all the base plots in a single set (for merged plots it just returns the bottom plot) * @return Set of base Plot */ - public Set getBasePlots() { + public Set getBasePlots() + { int size = 0; - for (Entry> entry : plots.entrySet()) { - if (isPlotWorld(entry.getKey())) { + for (final Entry> entry : plots.entrySet()) + { + if (isPlotWorld(entry.getKey())) + { size += entry.getValue().size(); } } - Set result = new HashSet<>(size); - for (Entry> entry : plots.entrySet()) { - if (isPlotWorld(entry.getKey())) { - for (Entry entry2 : entry.getValue().entrySet()) { - Plot plot = entry2.getValue(); - if (plot.getMerged(0) || plot.getMerged(3)) { + final Set result = new HashSet<>(size); + for (final Entry> entry : plots.entrySet()) + { + if (isPlotWorld(entry.getKey())) + { + for (final Entry entry2 : entry.getValue().entrySet()) + { + final Plot plot = entry2.getValue(); + if (plot.getMerged(0) || plot.getMerged(3)) + { continue; } result.add(plot); @@ -551,26 +627,27 @@ public class PS { return result; } - /** * Get the raw plot object * @return set of plot * @see #setAllPlotsRaw(LinkedHashMap) to set the raw plot object */ @Deprecated - public Set getPlotsRaw() { + public Set getPlotsRaw() + { int size = 0; - for (Entry> entry : plots.entrySet()) { + for (final Entry> entry : plots.entrySet()) + { size += entry.getValue().size(); } - Set result = new HashSet<>(size); - for (Entry> entry : plots.entrySet()) { + final Set result = new HashSet<>(size); + for (final Entry> entry : plots.entrySet()) + { result.addAll(entry.getValue().values()); } return result; } - /** * Sort a collection of plots by the hashcode (assumes that all plots are in the same world) * @param plots @@ -578,42 +655,55 @@ public class PS { * @deprecated use sortPlot */ @Deprecated - public ArrayList sortPlots(Collection plots) { + public ArrayList sortPlots(final Collection plots) + { return sortPlots(plots, SortType.DISTANCE_FROM_ORIGIN, null); } - - public ArrayList sortPlotsByTemp(Collection plots) { + + public ArrayList sortPlotsByTemp(final Collection plots) + { int max = 0; int overflowCount = 0; - for (Plot plot : plots) { - if (plot.temp > 0) { - if (plot.temp > max) { + for (final Plot plot : plots) + { + if (plot.temp > 0) + { + if (plot.temp > max) + { max = plot.temp; } } - else { + else + { overflowCount++; } } - Plot[] array = new Plot[max + 1]; - List overflow = new ArrayList<>(overflowCount); - for (Plot plot : plots) { - if (plot.temp <= 0) { + final Plot[] array = new Plot[max + 1]; + final List overflow = new ArrayList<>(overflowCount); + for (final Plot plot : plots) + { + if (plot.temp <= 0) + { overflow.add(plot); } - else { + else + { array[plot.temp] = plot; } } - ArrayList result = new ArrayList<>(plots.size()); - for (Plot plot : array) { - if (plot != null) { + final ArrayList result = new ArrayList<>(plots.size()); + for (final Plot plot : array) + { + if (plot != null) + { result.add(plot); } } - Collections.sort(overflow, new Comparator() { + Collections.sort(overflow, new Comparator() + { @Override - public int compare(Plot a, Plot b) { + public int compare(final Plot a, final Plot b) + { return a.hashCode() - b.hashCode(); } }); @@ -628,59 +718,74 @@ public class PS { * @deprecated Unchecked, please use {@link #sortPlots(Collection, SortType, String)} which has additional checks before calling this */ @Deprecated - public ArrayList sortPlotsByHash(Collection plots) { + public ArrayList sortPlotsByHash(final Collection plots) + { int hardmax = 256000; int max = 0; int overflowSize = 0; - for (Plot plot : plots) { - int hash = MathMan.getPositiveId(plot.hashCode()); - if (hash > max) { - if (hash >= hardmax) { + for (final Plot plot : plots) + { + final int hash = MathMan.getPositiveId(plot.hashCode()); + if (hash > max) + { + if (hash >= hardmax) + { overflowSize++; } - else { + else + { max = hash; } } } hardmax = Math.min(hardmax, max); - 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) { + 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()); + if (hash < hardmax) + { + if (hash >= 0) + { cache[hash] = plot; } - else { + else + { extra.add(plot); } } - else if (Math.abs(plot.id.x) > 15446 || Math.abs(plot.id.y) > 15446) { + else if ((Math.abs(plot.id.x) > 15446) || (Math.abs(plot.id.y) > 15446)) + { extra.add(plot); } - else { + else + { overflow.add(plot); } } - Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); + final Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); sortPlotsByHash(overflowArray); - ArrayList result = new ArrayList(cache.length + overflowArray.length); - for (Plot plot : cache) { - if (plot != null) { + final ArrayList result = new ArrayList(cache.length + overflowArray.length); + for (final Plot plot : cache) + { + if (plot != null) + { result.add(plot); } } - for (Plot plot : overflowArray) { + for (final Plot plot : overflowArray) + { result.add(plot); } - for (Plot plot : extra) { + for (final Plot plot : extra) + { result.add(plot); } return result; } - + /** * Sort plots by creation timestamp * @param input @@ -688,57 +793,72 @@ public class PS { * @return */ @Deprecated - public ArrayList sortPlotsByTimestamp(Collection input) { + public ArrayList sortPlotsByTimestamp(final Collection input) + { List list; - if (input instanceof ArrayList) { + if (input instanceof ArrayList) + { list = (List) input; } - else { + else + { list = new ArrayList(input); } long min = Integer.MAX_VALUE; long max = 0; - int size = list.size(); - int limit = Math.min(1048576, size * 2); - for (int i = 0; i < size; i++) { - Plot plot = list.get(i); - long time = plot.getTimestamp(); - if (time < min) { + final int size = list.size(); + final int limit = Math.min(1048576, size * 2); + for (int i = 0; i < size; i++) + { + final Plot plot = list.get(i); + final long time = plot.getTimestamp(); + if (time < min) + { min = time; } - if (time > max) { + if (time > max) + { max = time; } } - long range = max - min; + final long range = max - min; Plot[] plots; - try { - ArrayList overflow = new ArrayList<>(); - if (range > limit && size > 1024) { + try + { + final ArrayList overflow = new ArrayList<>(); + if ((range > limit) && (size > 1024)) + { plots = new Plot[Math.min((int) range, limit)]; - int factor = (int) ((range / limit)); - for (int i = 0; i < size; i++) { + final int factor = (int) ((range / limit)); + for (int i = 0; i < size; i++) + { Plot plot = list.get(i); int index = (int) (plot.getTimestamp() - min) / factor; - if (index < 0) { + if (index < 0) + { index = 0; } - if (index >= plots.length) { + if (index >= plots.length) + { overflow.add(plot); continue; } Plot current = plots[index]; - while (true) { - if (current == null) { + while (true) + { + if (current == null) + { plots[index] = plot; break; } - if (current.getTimestamp() > plot.getTimestamp()) { + if (current.getTimestamp() > plot.getTimestamp()) + { plots[index] = plot; plot = current; } index++; - if (index >= plots.length) { + if (index >= plots.length) + { overflow.add(plot); break; } @@ -746,43 +866,54 @@ public class PS { } } } - else if (range < size || size < 1024) { - ArrayList result = new ArrayList(list); - Collections.sort(result, new Comparator() { + else if ((range < size) || (size < 1024)) + { + final ArrayList result = new ArrayList(list); + Collections.sort(result, new Comparator() + { @Override - public int compare(Plot a, Plot b) { - if (a.getTimestamp() > b.getTimestamp()) { + public int compare(final Plot a, final Plot b) + { + if (a.getTimestamp() > b.getTimestamp()) + { return -1; } else if (b.getTimestamp() > a.getTimestamp()) { - return 1; + return 1; } return 0; } }); return result; } - else if (min != 0) { + else if (min != 0) + { plots = new Plot[(int) range]; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { Plot plot = list.get(i); int index = (int) (plot.getTimestamp() - min); - if (index >= plots.length) { + if (index >= plots.length) + { overflow.add(plot); continue; } Plot current = plots[index]; - while (true) { - if (current == null) { + while (true) + { + if (current == null) + { plots[index] = plot; break; } - if (current.getTimestamp() > plot.getTimestamp()) { + if (current.getTimestamp() > plot.getTimestamp()) + { plots[index] = plot; plot = current; } index++; - if (index >= plots.length) { + if (index >= plots.length) + { overflow.add(plot); break; } @@ -790,28 +921,35 @@ public class PS { } } } - else { + else + { plots = new Plot[(int) range]; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { Plot plot = list.get(i); int index = (int) (plot.getTimestamp()); - if (index >= plots.length) { + if (index >= plots.length) + { overflow.add(plot); continue; } Plot current = plots[index]; // Move everything along until a free spot is found - while (true) { - if (current == null) { + while (true) + { + if (current == null) + { plots[index] = plot; break; } - if (current.getTimestamp() > plot.getTimestamp()) { + if (current.getTimestamp() > plot.getTimestamp()) + { plots[index] = plot; plot = current; } index++; - if (index >= plots.length) { + if (index >= plots.length) + { overflow.add(plot); break; } @@ -819,42 +957,53 @@ public class PS { } } } - ArrayList result = new ArrayList<>(size); - if (overflow.size() > 0) { - Collections.sort(overflow, new Comparator() { + final ArrayList result = new ArrayList<>(size); + if (overflow.size() > 0) + { + Collections.sort(overflow, new Comparator() + { @Override - public int compare(Plot a, Plot b) { - if (a.getTimestamp() > b.getTimestamp()) { + public int compare(final Plot a, final Plot b) + { + if (a.getTimestamp() > b.getTimestamp()) + { return -1; } else if (b.getTimestamp() > a.getTimestamp()) { - return 1; + return 1; } return 0; } }); - for (Plot plot : overflow) { + for (final Plot plot : overflow) + { result.add(plot); } } - for (int i = plots.length - 1; i >= 0; i--) { - if (plots[i] != null) { + for (int i = plots.length - 1; i >= 0; i--) + { + if (plots[i] != null) + { result.add(plots[i]); } } return result; } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); - ArrayList result = new ArrayList(list); - Collections.sort(result, new Comparator() { + final ArrayList result = new ArrayList(list); + Collections.sort(result, new Comparator() + { @Override - public int compare(Plot a, Plot b) { - if (a.getTimestamp() > b.getTimestamp()) { + public int compare(final Plot a, final Plot b) + { + if (a.getTimestamp() > b.getTimestamp()) + { return -1; } else if (b.getTimestamp() > a.getTimestamp()) { - return 1; + return 1; } return 0; } @@ -862,30 +1011,38 @@ public class PS { return result; } } - + /** * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this * @param input */ - public void sortPlotsByHash(Plot[] input) { - List[] bucket = new ArrayList[64]; - for (int i = 0; i < bucket.length; i++) { + @Deprecated + public void sortPlotsByHash(final Plot[] input) + { + final List[] bucket = new ArrayList[64]; + for (int i = 0; i < bucket.length; i++) + { bucket[i] = new ArrayList(); } boolean maxLength = false; int tmp = -1, placement = 1; - while (!maxLength) { + while (!maxLength) + { maxLength = true; - for (Plot i : input) { + for (final Plot i : input) + { tmp = MathMan.getPositiveId(i.hashCode()) / placement; bucket[tmp & 63].add(i); - if (maxLength && tmp > 0) { + if (maxLength && (tmp > 0)) + { maxLength = false; } } int a = 0; - for (int b = 0; b < 64; b++) { - for (Plot i : bucket[b]) { + for (int b = 0; b < 64; b++) + { + for (final Plot i : bucket[b]) + { input[a++] = i; } bucket[b].clear(); @@ -893,33 +1050,40 @@ public class PS { placement *= 64; } } - + /** * Sort plots by timestamp * @param input * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this */ @Deprecated - public void sortPlotsByTimestamp(Plot[] input) { + public void sortPlotsByTimestamp(final Plot[] input) + { final int SIZE = 100; - List[] bucket = new ArrayList[SIZE]; - for (int i = 0; i < bucket.length; i++) { + final List[] bucket = new ArrayList[SIZE]; + for (int i = 0; i < bucket.length; i++) + { bucket[i] = new ArrayList(); } boolean maxLength = false; int tmp = -1, placement = 1; - while (!maxLength) { + while (!maxLength) + { maxLength = true; - for (Plot i : input) { + for (final Plot i : input) + { tmp = MathMan.getPositiveId(i.hashCode()) / placement; bucket[tmp % SIZE].add(i); - if (maxLength && tmp > 0) { + if (maxLength && (tmp > 0)) + { maxLength = false; } } int a = 0; - for (int b = 0; b < SIZE; b++) { - for (Plot i : bucket[b]) { + for (int b = 0; b < SIZE; b++) + { + for (final Plot i : bucket[b]) + { input[a++] = i; } bucket[b].clear(); @@ -927,9 +1091,12 @@ public class PS { placement *= SIZE; } } - - public enum SortType { CREATION_DATE, CREATION_DATE_TIMESTAMP, DISTANCE_FROM_ORIGIN; } - + + public enum SortType + { + CREATION_DATE, CREATION_DATE_TIMESTAMP, DISTANCE_FROM_ORIGIN; + } + /** * Sort a collection of plots by world (with a priority world), then by hashcode * @param plots @@ -937,49 +1104,62 @@ public class PS { * @param priorityWorld - Use null, "world" or "gibberish" if you want default world order * @return ArrayList of plot */ - public ArrayList sortPlots(Collection plots, final SortType type, final String priorityWorld) { + public ArrayList sortPlots(final Collection plots, final SortType type, final String priorityWorld) + { // group by world // sort each - HashMap> map = new HashMap<>(); - ArrayList worlds = new ArrayList(getPlotWorlds()); + final HashMap> map = new HashMap<>(); + final ArrayList worlds = new ArrayList(getPlotWorlds()); int totalSize = 0; - for (Entry> entry : this.plots.entrySet()) { + for (final Entry> entry : this.plots.entrySet()) + { totalSize += entry.getValue().size(); } - if (plots.size() == totalSize) { - for (Entry> entry : this.plots.entrySet()) { + if (plots.size() == totalSize) + { + for (final Entry> entry : this.plots.entrySet()) + { map.put(entry.getKey(), entry.getValue().values()); } } - else { - for (String world : worlds) { + else + { + for (final String world : worlds) + { map.put(world, new ArrayList(plots.size() / worlds.size())); } Collection lastList = null; String lastWorld = ""; - for (Plot plot : plots) { - if (StringMan.isEqual(lastWorld, plot.world)) { + for (final Plot plot : plots) + { + if (StringMan.isEqual(lastWorld, plot.world)) + { lastList.add(plot); } - else { + else + { lastWorld = plot.world; lastList = map.get(lastWorld); lastList.add(plot); } } } - Collections.sort(worlds, new Comparator() { + Collections.sort(worlds, new Comparator() + { @Override - public int compare(String a, String b) { - if (priorityWorld != null && StringMan.isEqual(a, priorityWorld)) { - return -1; + public int compare(final String a, final String b) + { + if ((priorityWorld != null) && StringMan.isEqual(a, priorityWorld)) { + return -1; } return a.hashCode() - b.hashCode(); } }); - ArrayList toReturn = new ArrayList(plots.size()); - for (String world : worlds) { - switch (type) { + final ArrayList toReturn = new ArrayList(plots.size()); + for (final String world : worlds) + { + switch (type) + { case CREATION_DATE: toReturn.addAll(sortPlotsByTemp(map.get(world))); break; @@ -991,13 +1171,12 @@ public class PS { break; default: break; - + } } return toReturn; } - /** * Sort a collection of plots by world, then by hashcode * @param plots @@ -1005,14 +1184,18 @@ public class PS { * @return ArrayList of plot */ @Deprecated - public ArrayList sortPlotsByWorld(Collection plots) { - ArrayList newPlots = new ArrayList<>(); - ArrayList worlds = new ArrayList<>(this.plotworlds.keySet()); - HashSet set = new HashSet<>(plots); + public ArrayList sortPlotsByWorld(final Collection plots) + { + final ArrayList newPlots = new ArrayList<>(); + final ArrayList worlds = new ArrayList<>(plotworlds.keySet()); + final HashSet set = new HashSet<>(plots); Collections.sort(worlds); - for (String world : worlds) { - for (Plot plot : this.plots.get(world).values()) { - if (set.contains(plot)) { + for (final String world : worlds) + { + for (final Plot plot : this.plots.get(world).values()) + { + if (set.contains(plot)) + { newPlots.add(plot); } } @@ -1020,14 +1203,14 @@ public class PS { return newPlots; } - /** * 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) { + public Set getPlots(final String world, final String player) + { final UUID uuid = UUIDHandler.getUUID(player, null); return getPlots(world, uuid); } @@ -1038,7 +1221,8 @@ public class PS { * @param player * @return Set of plot */ - public Set getPlots(final String world, final PlotPlayer player) { + public Set getPlots(final String world, final PlotPlayer player) + { final UUID uuid = player.getUUID(); return getPlots(world, uuid); } @@ -1049,11 +1233,15 @@ public class PS { * @param uuid * @return Set of plot */ - public Set getPlots(final String world, final UUID uuid) { + public Set getPlots(final String world, final UUID uuid) + { final ArrayList myplots = new ArrayList<>(); - for (final Plot plot : getPlotsInWorld(world)) { - if (plot.hasOwner()) { - if (PlotHandler.isOwner(plot, uuid)) { + for (final Plot plot : getPlotsInWorld(world)) + { + if (plot.hasOwner()) + { + if (PlotHandler.isOwner(plot, uuid)) + { myplots.add(plot); } } @@ -1061,14 +1249,14 @@ public class PS { return new HashSet<>(myplots); } - /** * Check if a plot world * @param world * @see #getPlotWorld(String) to get the PlotWorld object * @return if a plot world is registered */ - public boolean isPlotWorld(final String world) { + public boolean isPlotWorld(final String world) + { return (plotworlds.containsKey(world)); } @@ -1077,10 +1265,9 @@ public class PS { * @param world * @return the PlotManager object, or null if no registered PlotManager */ - public PlotManager getPlotManager(final String world) { - if (plotmanagers.containsKey(world)) { - return plotmanagers.get(world); - } + public PlotManager getPlotManager(final String world) + { + if (plotmanagers.containsKey(world)) { return plotmanagers.get(world); } return null; } @@ -1088,82 +1275,85 @@ public class PS { * Get a list of the plot worlds * @return A String array of the plot world names */ - public String[] getPlotWorldsString() { + public String[] getPlotWorldsString() + { final Set strings = plotworlds.keySet(); return strings.toArray(new String[strings.size()]); } - private String lastWorld; private Map lastMap; - + /** * Get a map of the plots for a world * @param world * @return HashMap of PlotId to Plot */ @Deprecated - public HashMap getPlots(final String world) { - ConcurrentHashMap myplots = plots.get(world); - if (myplots != null) { - if (world == lastWorld) { - return new HashMap<>(lastMap); - } + public HashMap getPlots(final String world) + { + final ConcurrentHashMap myplots = plots.get(world); + if (myplots != null) + { + if (world == lastWorld) { return new HashMap<>(lastMap); } return new HashMap<>(myplots); } return new HashMap<>(); } - - public Collection getPlotsInWorld(final String world) { - ConcurrentHashMap map = plots.get(world); - if (map == null) { - return new HashSet<>(); - } + + public Collection getPlotsInWorld(final String world) + { + final ConcurrentHashMap map = plots.get(world); + if (map == null) { return new HashSet<>(); } return map.values(); } - - public Plot getPlot(final String world, final PlotId id) { - if (world == lastWorld) { - if (lastMap != null) { - return lastMap.get(id); - } + + public Plot getPlot(final String world, final PlotId id) + { + if (world == lastWorld) + { + if (lastMap != null) { return lastMap.get(id); } return null; } lastWorld = world; - if (plots.containsKey(world)) { + if (plots.containsKey(world)) + { lastMap = plots.get(world); - if (lastMap != null) { - return lastMap.get(id); - } + if (lastMap != null) { return lastMap.get(id); } return null; } return null; } - /** * Get the plots for a PlotPlayer * @param player * @return Set of Plot */ - public Set getPlots(final PlotPlayer player) { + public Set getPlots(final PlotPlayer player) + { return getPlots(player.getUUID()); } - /** * Get the plots for a UUID * @param uuid * @return Set of Plot */ - public Set getPlots(final UUID uuid) { + public Set getPlots(final UUID uuid) + { final ArrayList myplots = new ArrayList<>(); - for (Entry> entry : plots.entrySet()) { - if (isPlotWorld(entry.getKey())) { - for (Entry entry2 : entry.getValue().entrySet()) { - Plot plot = entry2.getValue(); - if (plot.hasOwner()) { - if (PlotHandler.isOwner(plot, uuid)) { + for (final Entry> entry : plots.entrySet()) + { + if (isPlotWorld(entry.getKey())) + { + for (final Entry entry2 : entry.getValue().entrySet()) + { + final Plot plot = entry2.getValue(); + if (plot.hasOwner()) + { + if (PlotHandler.isOwner(plot, uuid)) + { myplots.add(plot); } } @@ -1173,35 +1363,35 @@ public class PS { return new HashSet<>(myplots); } - /** * Unregister a plot from local memory (does not call DB) * @param world * @param id * @param callEvent If to call an event about the plot being removed - * @return true if plot existed | false if it didn't + * @return true if plot existed | false if it didn't */ - public boolean removePlot(final String world, final PlotId id, final boolean callEvent) { - if (callEvent) { + public boolean removePlot(final String world, final PlotId id, final boolean callEvent) + { + if (callEvent) + { EventUtil.manager.callDelete(world, id); } - ConcurrentHashMap allPlots = plots.get(world); - if (allPlots == null) { - return false; - } - Plot plot = allPlots.remove(id); - if (MainUtil.lastPlot.containsKey(world)) { + final ConcurrentHashMap allPlots = plots.get(world); + if (allPlots == null) { return false; } + final Plot plot = allPlots.remove(id); + if (MainUtil.lastPlot.containsKey(world)) + { final PlotId last = MainUtil.lastPlot.get(world); final int last_max = Math.max(last.x, last.y); final int this_max = Math.max(id.x, id.y); - if (this_max < last_max) { + if (this_max < last_max) + { MainUtil.lastPlot.put(world, id); } } return plot != null; } - /** * This method is called by the PlotGenerator class normally
      * - Initializes the PlotWorld and PlotManager classes
      @@ -1214,10 +1404,13 @@ public class PS { * @param world The world to load * @param generator The generator for that world, or null if no generator */ - public void loadWorld(final String world, PlotGenerator generator) { + public void loadWorld(final String world, final PlotGenerator generator) + { PlotWorld plotWorld = getPlotWorld(world); - if (plotWorld != null) { - if (generator != null) { + if (plotWorld != null) + { + if (generator != null) + { generator.initialize(plotWorld); } return; @@ -1226,58 +1419,73 @@ public class PS { final PlotGenerator plotGenerator; final PlotManager plotManager; final String path = "worlds." + world; - if (!LOADING_WORLD && (generator.isFull())) { + if (!LOADING_WORLD && (generator.isFull())) + { plotGenerator = generator; plotWorld = plotGenerator.getNewPlotWorld(world); plotManager = plotGenerator.getPlotManager(); - if (!world.equals("CheckingPlotSquaredGenerator")) { + if (!world.equals("CheckingPlotSquaredGenerator")) + { log(C.PREFIX.s() + "&aDetected world load for '" + world + "'"); log(C.PREFIX.s() + "&3 - generator: &7" + plotGenerator.getClass().getName()); log(C.PREFIX.s() + "&3 - plotworld: &7" + plotWorld.getClass().getName()); log(C.PREFIX.s() + "&3 - manager: &7" + plotManager.getClass().getName()); } - if (!config.contains(path)) { + if (!config.contains(path)) + { config.createSection(path); } plotWorld.saveConfiguration(config.getConfigurationSection(path)); plotWorld.loadDefaultConfiguration(config.getConfigurationSection(path)); - try { + try + { config.save(configFile); - } catch (final IOException e) { + } + catch (final IOException e) + { e.printStackTrace(); } // Now add it addPlotWorld(world, plotWorld, plotManager); generator.initialize(plotWorld); MainUtil.setupBorder(world); - } else { - if (!worlds.contains(world)) { - return; - } - if (!LOADING_WORLD) { + } + else + { + if (!worlds.contains(world)) { return; } + if (!LOADING_WORLD) + { LOADING_WORLD = true; - try { + try + { final String gen_string = config.getString("worlds." + world + "." + "generator.plugin"); generator.setGenerator(gen_string); -// if (gen_string == null) { -// generator = new HybridGen(world); -// } else { -// generator = (PlotGenerator) IMP.getGenerator(world, gen_string); -// } + // if (gen_string == null) { + // generator = new HybridGen(world); + // } else { + // generator = (PlotGenerator) IMP.getGenerator(world, gen_string); + // } loadWorld(world, generator); - } catch (final Exception e) { + } + catch (final Exception e) + { log("&d=== Oh no! Please set the generator for the " + world + " ==="); e.printStackTrace(); LOADING_WORLD = false; removePlotWorld(world); - } finally { + } + finally + { LOADING_WORLD = false; } - } else { + } + else + { LOADING_WORLD = false; plotWorld = generator.getNewPlotWorld(world); plotManager = generator.getPlotManager(); - if (!config.contains(path)) { + if (!config.contains(path)) + { config.createSection(path); } plotWorld.TYPE = generator.isFull() ? 0 : 2; @@ -1285,12 +1493,16 @@ public class PS { plotWorld.saveConfiguration(config.getConfigurationSection(path)); plotWorld.loadDefaultConfiguration(config.getConfigurationSection(path)); - try { + try + { config.save(configFile); - } catch (final IOException e) { + } + catch (final IOException e) + { e.printStackTrace(); } - if (((plotWorld.TYPE == 2) && !Settings.ENABLE_CLUSTERS) || !(plotManager instanceof SquarePlotManager)) { + if (((plotWorld.TYPE == 2) && !Settings.ENABLE_CLUSTERS) || !(plotManager instanceof SquarePlotManager)) + { log("&c[ERROR] World '" + world + "' in settings.yml is not using PlotSquared generator! Please set the generator correctly or delete the world from the 'settings.yml'!"); return; } @@ -1300,35 +1512,41 @@ public class PS { log(C.PREFIX.s() + "&3 - manager: &7" + plotManager.getClass().getName()); log(C.PREFIX.s() + "&3 - | terrain: &7" + plotWorld.TERRAIN); log(C.PREFIX.s() + "&3 - | type: &7" + plotWorld.TYPE); - + addPlotWorld(world, plotWorld, plotManager); - if (plotWorld.TYPE == 2) { - if (ClusterManager.getClusters(world).size() > 0) { - for (final PlotCluster cluster : ClusterManager.getClusters(world)) { + if (plotWorld.TYPE == 2) + { + if (ClusterManager.getClusters(world).size() > 0) + { + for (final PlotCluster cluster : ClusterManager.getClusters(world)) + { log(C.PREFIX.s() + "&3 - &7| cluster: " + cluster); generator.augment(cluster, plotWorld); -// new AugmentedPopulator(world, generator, cluster, plotWorld.TERRAIN == 2, plotWorld.TERRAIN != 2); + // new AugmentedPopulator(world, generator, cluster, plotWorld.TERRAIN == 2, plotWorld.TERRAIN != 2); } } - } else if (plotWorld.TYPE == 1) { + } + else if (plotWorld.TYPE == 1) + { generator.augment(null, plotWorld); -// new AugmentedPopulator(world, gen_class, null, plotWorld.TERRAIN == 2, plotWorld.TERRAIN != 2); + // new AugmentedPopulator(world, gen_class, null, plotWorld.TERRAIN == 2, plotWorld.TERRAIN != 2); } generator.initialize(plotWorld); } } } - /** * Setup the configuration for a plot world based on world arguments
      * e.g. /mv create normal -g PlotSquared: * @param world The name of the world * @param args The arguments - * @return boolean | if valid arguments were provided + * @return boolean | if valid arguments were provided */ - public boolean setupPlotWorld(final String world, final String args) { - if ((args != null) && (args.length() > 0)) { + public boolean setupPlotWorld(final String world, final String args) + { + if ((args != null) && (args.length() > 0)) + { // save configuration final String[] split = args.split(","); final HybridPlotWorld plotworld = new HybridPlotWorld(world); @@ -1339,67 +1557,83 @@ public class PS { final PlotBlock[] main = ClassicPlotWorld.MAIN_BLOCK_DEFAULT; final PlotBlock wall = ClassicPlotWorld.WALL_FILLING_DEFAULT; final PlotBlock border = ClassicPlotWorld.WALL_BLOCK_DEFAULT; - for (final String element : split) { + for (final String element : split) + { final String[] pair = element.split("="); - if (pair.length != 2) { + if (pair.length != 2) + { log("&cNo value provided for: &7" + element); return false; } final String key = pair[0].toLowerCase(); final String value = pair[1]; - try { - switch (key) { + try + { + switch (key) + { case "s": - case "size": { + case "size": + { SquarePlotWorld.PLOT_WIDTH_DEFAULT = Configuration.INTEGER.parseString(value).shortValue(); break; } case "g": - case "gap": { + case "gap": + { SquarePlotWorld.ROAD_WIDTH_DEFAULT = Configuration.INTEGER.parseString(value).shortValue(); break; } case "h": - case "height": { + case "height": + { ClassicPlotWorld.PLOT_HEIGHT_DEFAULT = Configuration.INTEGER.parseString(value); ClassicPlotWorld.ROAD_HEIGHT_DEFAULT = Configuration.INTEGER.parseString(value); ClassicPlotWorld.WALL_HEIGHT_DEFAULT = Configuration.INTEGER.parseString(value); break; } case "f": - case "floor": { + case "floor": + { ClassicPlotWorld.TOP_BLOCK_DEFAULT = Configuration.BLOCKLIST.parseString(value); break; } case "m": - case "main": { + case "main": + { ClassicPlotWorld.MAIN_BLOCK_DEFAULT = Configuration.BLOCKLIST.parseString(value); break; } case "w": - case "wall": { + case "wall": + { ClassicPlotWorld.WALL_FILLING_DEFAULT = Configuration.BLOCK.parseString(value); break; } case "b": - case "border": { + case "border": + { ClassicPlotWorld.WALL_BLOCK_DEFAULT = Configuration.BLOCK.parseString(value); break; } - default: { + default: + { log("&cKey not found: &7" + element); return false; } } - } catch (final Exception e) { + } + catch (final Exception e) + { e.printStackTrace(); log("&cInvalid value: &7" + value + " in arg " + element); return false; } } - try { + try + { final String root = "worlds." + world; - if (!config.contains(root)) { + if (!config.contains(root)) + { config.createSection(root); } plotworld.saveConfiguration(config.getConfigurationSection(root)); @@ -1412,56 +1646,67 @@ public class PS { ClassicPlotWorld.WALL_FILLING_DEFAULT = wall; SquarePlotWorld.PLOT_WIDTH_DEFAULT = width; SquarePlotWorld.ROAD_WIDTH_DEFAULT = gap; - } catch (final Exception e) { + } + catch (final Exception e) + { e.printStackTrace(); } } return true; } - - public boolean canUpdate(String current, String other) { - String s1 = normalisedVersion(current); - String s2 = normalisedVersion(other); - int cmp = s1.compareTo(s2); + + 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); return cmp < 0; } - public String normalisedVersion(String version) { + public String normalisedVersion(final String version) + { return normalisedVersion(version, ".", 4); } - public String normalisedVersion(String version, String sep, int maxWidth) { - String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version); - StringBuilder sb = new StringBuilder(); - for (String s : split) { + public String normalisedVersion(final String version, final String sep, final int maxWidth) + { + final String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version); + final StringBuilder sb = new StringBuilder(); + for (final String s : split) + { sb.append(String.format("%" + maxWidth + 's', s)); } return sb.toString(); } - + /** * Gets the default update URL, or null if the plugin is up to date * @return */ - public URL getUpdate() { - String pom = "https://raw.githubusercontent.com/IntellectualSites/PlotSquared/master/pom.xml"; + public URL getUpdate() + { + final String pom = "https://raw.githubusercontent.com/IntellectualSites/PlotSquared/master/pom.xml"; String dl = "https://raw.githubusercontent.com/IntellectualSites/PlotSquared/master/target/PlotSquared-${PLATFORM}.jar"; - String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1"; - try { - URL page = new URL(pom); - URLConnection con = page.openConnection(); + final String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1"; + try + { + final URL page = new URL(pom); + final URLConnection con = page.openConnection(); con.addRequestProperty("User-Agent", agent); - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; - while ((line = in.readLine()) != null) { + while ((line = in.readLine()) != null) + { line = line.trim(); - if (line.startsWith("")) { + if (line.startsWith("")) + { line = line.replaceAll("[^\\d.]", ""); break; } } in.close(); - if (!canUpdate(config.getString("version"), line) ) { + if (!canUpdate(config.getString("version"), line)) + { PS.debug("&7PlotSquared is already up to date!"); return null; } @@ -1470,38 +1715,42 @@ public class PS { log("&8 - &3Use: &7/plot update"); log("&8 - &3Or: &7" + dl); return new URL(dl); - } catch (Exception e) { + } + catch (final Exception e) + { e.printStackTrace(); log("&dCould not check for updates (0)"); log("&7 - Manually check for updates: " + pom); } return null; } - - public boolean update(PlotPlayer sender, URL url) { - if (url == null) { - return false; - } - try { - String name = FILE.getName(); - File newJar = new File("plugins/update/" + name); + + public boolean update(final PlotPlayer sender, final URL url) + { + if (url == null) { return false; } + try + { + final String name = FILE.getName(); + final File newJar = new File("plugins/update/" + name); MainUtil.sendMessage(sender, "$1Downloading from provided URL: &7" + url); MainUtil.sendMessage(sender, "$2 - User-Agent: " + "Mozilla/4.0"); - URLConnection con = url.openConnection(); + final URLConnection con = url.openConnection(); con.addRequestProperty("User-Agent", "Mozilla/4.0"); - InputStream stream = con.getInputStream(); - File parent = newJar.getParentFile(); - if (!parent.exists()) { + final InputStream stream = con.getInputStream(); + final File parent = newJar.getParentFile(); + if (!parent.exists()) + { parent.mkdirs(); } MainUtil.sendMessage(sender, "$2 - Output: " + newJar); newJar.delete(); Files.copy(stream, newJar.toPath()); stream.close(); - MainUtil.sendMessage(sender, "$1The update will take effect when the server is restarted next"); + MainUtil.sendMessage(sender, "$1The update will take effect when the server is restarted next"); return true; } - catch (Exception e) { + catch (final Exception e) + { MainUtil.sendMessage(sender, "Failed to update PlotSquared"); MainUtil.sendMessage(sender, " - Please update manually"); log("============ Stacktrace ============"); @@ -1511,49 +1760,54 @@ public class PS { return false; } - /** * Get the database connection * @return The database connection */ - public Connection getConnection() { + public Connection getConnection() + { return connection; } - /** * Copy a file from inside the jar to a location * @param file Name of the file inside PlotSquared.jar * @param folder The output location relative to /plugins/PlotSquared/ */ - public void copyFile(String file, String folder) { - try { - File output = IMP.getDirectory(); - if (!output.exists()) { + public void copyFile(final String file, final String folder) + { + try + { + final File output = IMP.getDirectory(); + if (!output.exists()) + { output.mkdirs(); } - File newFile = new File((output + File.separator + folder + File.separator + file)); - if (newFile.exists()) { - return; - } - InputStream stream = IMP.getClass().getResourceAsStream(file); - byte[] buffer = new byte[2048]; - if (stream == null) { - ZipInputStream zis = new ZipInputStream(new FileInputStream(FILE)); + final File newFile = new File((output + File.separator + folder + File.separator + file)); + if (newFile.exists()) { return; } + final InputStream stream = IMP.getClass().getResourceAsStream(file); + final byte[] buffer = new byte[2048]; + if (stream == null) + { + final ZipInputStream zis = new ZipInputStream(new FileInputStream(FILE)); ZipEntry ze = zis.getNextEntry(); - while (ze != null) { - String name = ze.getName(); - if (name.equals(file)) { + while (ze != null) + { + final String name = ze.getName(); + if (name.equals(file)) + { new File(newFile.getParent()).mkdirs(); - FileOutputStream fos = new FileOutputStream(newFile); + final FileOutputStream fos = new FileOutputStream(newFile); int len; - while ((len = zis.read(buffer)) > 0) { + while ((len = zis.read(buffer)) > 0) + { fos.write(buffer, 0, len); } fos.close(); ze = null; } - else { + else + { ze = zis.getNextEntry(); } } @@ -1562,35 +1816,40 @@ public class PS { return; } newFile.createNewFile(); - FileOutputStream fos = new FileOutputStream(newFile); + final FileOutputStream fos = new FileOutputStream(newFile); int len; - while ((len = stream.read(buffer)) > 0) { + while ((len = stream.read(buffer)) > 0) + { fos.write(buffer, 0, len); } fos.close(); stream.close(); } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); log("&cCould not save " + file); } } - /** * Close the database connection */ - public void disable() { - try { + public void disable() + { + try + { TASK = null; database = null; // Validate that all data in the db is correct DBFunc.validatePlots(getPlotsRaw()); - + // Close the connection DBFunc.close(); UUIDHandler.handleShutdown(); - } catch (NullPointerException e) { + } + catch (final NullPointerException e) + { log("&cCould not close database connection!"); } } @@ -1598,22 +1857,29 @@ public class PS { /** * Setup the database connection */ - public void setupDatabase() { - try { - if (Settings.DB.USE_MONGO) { + public void setupDatabase() + { + try + { + if (Settings.DB.USE_MONGO) + { log(C.PREFIX.s() + "MongoDB is not yet implemented"); log(C.PREFIX + "&cNo storage type is set!"); IMP.disable(); return; } - if (DBFunc.dbManager == null) { - if (Settings.DB.USE_MYSQL) { + 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); } - else if (Settings.DB.USE_SQLITE) { + else if (Settings.DB.USE_SQLITE) + { database = new SQLite(IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db"); } - else { + else + { log(C.PREFIX + "&cNo storage type is set!"); IMP.disable(); return; @@ -1621,19 +1887,24 @@ public class PS { } DBFunc.dbManager = new SQLManager(database, Settings.DB.PREFIX, false); plots = DBFunc.getPlots(); - if (Settings.ENABLE_CLUSTERS) { + if (Settings.ENABLE_CLUSTERS) + { ClusterManager.clusters = DBFunc.getClusters(); } } - catch (Exception e) { + catch (final Exception e) + { log(C.PREFIX.s() + "&cFailed to open DATABASE connection. The plugin will disable itself."); - if (Settings.DB.USE_MONGO) { + if (Settings.DB.USE_MONGO) + { log("$4MONGO"); } - else if (Settings.DB.USE_MYSQL) { + else if (Settings.DB.USE_MYSQL) + { log("$4MYSQL"); } - else if (Settings.DB.USE_SQLITE) { + else if (Settings.DB.USE_SQLITE) + { log("$4SQLITE"); } log("&d==== Here is an ugly stacktrace, if you are interested in those things ==="); @@ -1645,33 +1916,40 @@ public class PS { } } - /** * Setup the default flags for PlotSquared
      * - Create the flags * - 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", "no-worldedit", "redstone", "keep"); + public void setupDefaultFlags() + { + final List booleanFlags = Arrays.asList("notify-enter", "notify-leave", "item-drop", "invincible", "instabreak", "drop-protection", "forcefield", "titles", "pve", "pvp", + "no-worldedit", "redstone", "keep"); final List intervalFlags = Arrays.asList("feed", "heal"); final List stringFlags = Arrays.asList("greeting", "farewell"); final List intFlags = Arrays.asList("entity-cap", "mob-cap", "animal-cap", "hostile-cap", "vehicle-cap", "music"); - for (final String flag : stringFlags) { + for (final String flag : stringFlags) + { FlagManager.addFlag(new AbstractFlag(flag)); } - for (final String flag : intervalFlags) { + for (final String flag : intervalFlags) + { FlagManager.addFlag(new AbstractFlag(flag, new FlagValue.IntervalValue())); } - for (final String flag : booleanFlags) { + for (final String flag : booleanFlags) + { FlagManager.addFlag(new AbstractFlag(flag, new FlagValue.BooleanValue())); } - for (final String flag : intFlags) { + for (final String flag : intFlags) + { FlagManager.addFlag(new AbstractFlag(flag, new FlagValue.UnsignedIntegerValue())); } - FlagManager.addFlag(new AbstractFlag("cluster") { + FlagManager.addFlag(new AbstractFlag("cluster") + { @Override - public Object parseValueRaw(String value) { - String[] split = value.split(";"); + public Object parseValueRaw(final String value) + { + final String[] split = value.split(";"); return ClusterManager.getCluster(split[0], split[1]); } }, true); @@ -1703,10 +1981,14 @@ public class PS { FlagManager.addFlag(new AbstractFlag("use", new FlagValue.PlotBlockListValue())); FlagManager.addFlag(new AbstractFlag("blocked-cmds", new FlagValue.StringListValue())); FlagManager.addFlag(new AbstractFlag("ice-met", new FlagValue.BooleanValue())); - FlagManager.addFlag(new AbstractFlag("gamemode") { + FlagManager.addFlag(new AbstractFlag("gamemode") + { - public PlotGamemode parseValueRaw(final String value) { - switch (value.toLowerCase()) { + @Override + public PlotGamemode parseValueRaw(final String value) + { + switch (value.toLowerCase()) + { case "survival": case "s": case "0": @@ -1727,17 +2009,22 @@ public class PS { } } - - public String getValueDesc() { + @Override + public String getValueDesc() + { return "Flag value must be a gamemode: 'creative' , 'survival', 'adventure' or 'spectator'"; } }); FlagManager.addFlag(new AbstractFlag("price", new FlagValue.UnsignedDoubleValue())); FlagManager.addFlag(new AbstractFlag("time", new FlagValue.LongValue())); - FlagManager.addFlag(new AbstractFlag("weather") { + FlagManager.addFlag(new AbstractFlag("weather") + { - public PlotWeather parseValueRaw(final String value) { - switch (value.toLowerCase()) { + @Override + public PlotWeather parseValueRaw(final String value) + { + switch (value.toLowerCase()) + { case "rain": case "storm": case "on": @@ -1753,54 +2040,55 @@ public class PS { } } - - public String getValueDesc() { + @Override + public String getValueDesc() + { return "Flag value must be weather type: 'clear' or 'rain'"; } }); FlagManager.addFlag(new AbstractFlag("description", new FlagValue.StringValue()), true); } - /** * Setup the default configuration (settings.yml) */ - public void setupConfig() { + public void setupConfig() + { LAST_VERSION = config.getString("version"); - config.set("version", StringMan.join(VERSION,".")); + config.set("version", StringMan.join(VERSION, ".")); config.set("platform", PLATFORM); - + final Map options = new HashMap<>(); // Command confirmation options.put("confirmation.clear", Settings.CONFIRM_CLEAR); options.put("confirmation.delete", Settings.CONFIRM_DELETE); options.put("confirmation.unlink", Settings.CONFIRM_UNLINK); - + // Protection options.put("protection.redstone.disable-offline", Settings.REDSTONE_DISABLER); options.put("protection.redstone.disable-unoccupied", Settings.REDSTONE_DISABLER_UNOCCUPIED); options.put("protection.tnt-listener.enabled", Settings.TNT_LISTENER); options.put("protection.piston.falling-blocks", Settings.PISTON_FALLING_BLOCK_CHECK); - + // Clusters options.put("clusters.enabled", Settings.ENABLE_CLUSTERS); - + // PlotMe options.put("plotme-alias", Settings.USE_PLOTME_ALIAS); options.put("plotme-convert.enabled", Settings.CONVERT_PLOTME); options.put("plotme-convert.cache-uuids", Settings.CACHE_PLOTME); - + // UUID options.put("uuid.use_sqluuidhandler", Settings.USE_SQLUUIDHANDLER); options.put("UUID.offline", Settings.OFFLINE_MODE); options.put("UUID.force-lowercase", Settings.UUID_LOWERCASE); options.put("uuid.read-from-disk", Settings.UUID_FROM_DISK); - + // Mob stuff options.put("kill_road_vehicles", Settings.KILL_ROAD_VEHICLES); options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); - + // Clearing + Expiry options.put("clear.fastmode", Settings.ENABLE_CLUSTERS); options.put("clear.on.ban", false); @@ -1817,10 +2105,11 @@ public class PS { options.put("clear.auto.calibration.data_sd", 1); options.put("clear.auto.calibration.air_sd", 0); options.put("clear.auto.calibration.variety_sd", 1); - - int keep = config.getInt("clear.keep-if-modified"); - int ignore = config.getInt("clear.ignore-if-modified"); - if (keep > 0 || ignore > 0) { + + final int keep = config.getInt("clear.keep-if-modified"); + final int ignore = config.getInt("clear.ignore-if-modified"); + if ((keep > 0) || (ignore > 0)) + { options.put("clear.auto.threshold", 1); log("&cIMPORTANT MESSAGE ABOUT THIS UPDATE!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); log("&cSorry for all the exclamation marks, but this could be important."); @@ -1832,12 +2121,13 @@ public class PS { log("&c - To just clear all expired plot, ignore this and set: &7threshold: -1"); log("&cMore information:&7 https://github.com/IntellectualSites/PlotSquared/wiki/Plot-analysis:"); } - else { + else + { options.put("clear.auto.threshold", Settings.CLEAR_THRESHOLD); } config.set("clear.keep-if-modified", null); config.set("clear.ignore-if-modified", null); - + // Done options.put("approval.ratings.require-done", Settings.REQUIRE_DONE); options.put("approval.done.counts-towards-limit", Settings.DONE_COUNTS_TOWARDS_LIMIT); @@ -1847,22 +2137,22 @@ public class PS { // Schematics options.put("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); options.put("bo3.save_path", Settings.BO3_SAVE_PATH); - + // Web options.put("web.url", Settings.WEB_URL); options.put("web.server-ip", Settings.WEB_IP); - + // Caching options.put("cache.permissions", Settings.PERMISSION_CACHING); options.put("cache.ratings", Settings.CACHE_RATINGS); - + // Titles options.put("titles", Settings.TITLES); - + // Teleportation options.put("teleport.on_login", Settings.TELEPORT_ON_LOGIN); options.put("teleport.delay", 0); - + // WorldEdit options.put("worldedit.require-selection-in-mask", Settings.REQUIRE_SELECTION); options.put("worldedit.queue-commands", Settings.QUEUE_COMMANDS); @@ -1870,7 +2160,7 @@ public class PS { options.put("worldedit.max-volume", Settings.WE_MAX_VOLUME); options.put("worldedit.max-iterations", Settings.WE_MAX_ITERATIONS); options.put("worldedit.blacklist", Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks")); - + // Chunk processor options.put("chunk-processor.enabled", Settings.CHUNK_PROCESSOR); options.put("chunk-processor.auto-unload", Settings.CHUNK_PROCESSOR_GC); @@ -1879,10 +2169,10 @@ public class PS { options.put("chunk-processor.max-blockstates", Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES); options.put("chunk-processor.max-entities", Settings.CHUNK_PROCESSOR_MAX_ENTITIES); options.put("chunk-processor.disable-physics", Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS); - + // Comments options.put("comments.notifications.enabled", Settings.COMMENT_NOTIFICATIONS); - + // Plot limits options.put("global_limit", Settings.GLOBAL_LIMIT); options.put("max_plots", Settings.MAX_PLOTS); @@ -1894,44 +2184,46 @@ public class PS { options.put("metrics", true); options.put("debug", true); options.put("update-notifications", true); - - for (final Entry node : options.entrySet()) { - if (!config.contains(node.getKey())) { + + for (final Entry node : options.entrySet()) + { + if (!config.contains(node.getKey())) + { config.set(node.getKey(), node.getValue()); } } - + // Command confirmation Settings.CONFIRM_CLEAR = config.getBoolean("confirmation.clear"); Settings.CONFIRM_DELETE = config.getBoolean("confirmation.delete"); Settings.CONFIRM_UNLINK = 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.TNT_LISTENER = config.getBoolean("protection.tnt-listener.enabled"); Settings.PISTON_FALLING_BLOCK_CHECK = config.getBoolean("protection.piston.falling-blocks"); - + // Clusters Settings.ENABLE_CLUSTERS = 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"); - + // 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"); - + // Mob stuff Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); Settings.KILL_ROAD_VEHICLES = config.getBoolean("kill_road_vehicles"); Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); - + // Clearing + Expiry Settings.FAST_CLEAR = config.getBoolean("clear.fastmode"); Settings.DELETE_PLOTS_ON_BAN = config.getBoolean("clear.on.ban"); @@ -1951,36 +2243,35 @@ public class PS { 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"); - + // 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"); - + // Schematics Settings.SCHEMATIC_SAVE_PATH = config.getString("schematics.save_path"); Settings.BO3_SAVE_PATH = config.getString("bo3.save_path"); - + // Web Settings.WEB_URL = config.getString("web.url"); Settings.WEB_IP = config.getString("web.server-ip"); - + // Caching Settings.PERMISSION_CACHING = config.getBoolean("cache.permissions"); Settings.CACHE_RATINGS = config.getBoolean("cache.ratings"); - + // Rating system Settings.RATING_CATEGORIES = config.getStringList("ratings.categories"); - - + // Titles Settings.TITLES = config.getBoolean("titles"); - + // Teleportation Settings.TELEPORT_DELAY = config.getInt("teleport.delay"); Settings.TELEPORT_ON_LOGIN = config.getBoolean("teleport.on_login"); - + // WorldEdit Settings.QUEUE_COMMANDS = config.getBoolean("worldedit.queue-commands"); Settings.REQUIRE_SELECTION = config.getBoolean("worldedit.require-selection-in-mask"); @@ -1988,7 +2279,7 @@ public class PS { 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"); - + // Chunk processor Settings.CHUNK_PROCESSOR = config.getBoolean("chunk-processor.enabled"); Settings.CHUNK_PROCESSOR_GC = config.getBoolean("chunk-processor.auto-unload"); @@ -1997,88 +2288,111 @@ public class PS { 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"); - + // Comments Settings.COMMENT_NOTIFICATIONS = config.getBoolean("comments.notifications.enabled"); - + // Plot limits Settings.MAX_AUTO_SIZE = config.getInt("claim.max-auto-area"); Settings.MAX_PLOTS = config.getInt("max_plots"); - if (Settings.MAX_PLOTS > 32767) { + 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"); - + // Misc Settings.DEBUG = config.getBoolean("debug"); - if (Settings.DEBUG) { + if (Settings.DEBUG) + { log(C.PREFIX.s() + "&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)) { + if (!config.getBoolean("chat.fancy") || !checkVersion(IMP.getServerVersion(), 1, 8, 0)) + { Settings.FANCY_CHAT = false; } Settings.METRICS = config.getBoolean("metrics"); } - /** * Setup all configuration files
      * - Config: settings.yml
      * - Storage: storage.yml
      * - Translation: PlotSquared.use_THIS.yml, style.yml
      */ - public void setupConfigs() { + public void setupConfigs() + { final File folder = new File(IMP.getDirectory() + File.separator + "config"); - if (!folder.exists() && !folder.mkdirs()) { + if (!folder.exists() && !folder.mkdirs()) + { log(C.PREFIX.s() + "&cFailed to create the /plugins/config folder. Please create it manually."); } - try { + try + { styleFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "style.yml"); - if (!styleFile.exists()) { - if (!styleFile.getParentFile().exists()) { + if (!styleFile.exists()) + { + if (!styleFile.getParentFile().exists()) + { styleFile.getParentFile().mkdirs(); } - if (!styleFile.createNewFile()) { + if (!styleFile.createNewFile()) + { log("Could not create the style file, please create \"translations/style.yml\" manually"); } } style = YamlConfiguration.loadConfiguration(styleFile); setupStyle(); - } catch (final Exception err) { + } + catch (final Exception err) + { err.printStackTrace(); log("failed to save style.yml"); } - try { + try + { configFile = new File(IMP.getDirectory() + File.separator + "config" + File.separator + "settings.yml"); - if (!configFile.exists()) { - if (!configFile.createNewFile()) { + if (!configFile.exists()) + { + if (!configFile.createNewFile()) + { log("Could not create the settings file, please create \"settings.yml\" manually."); } } config = YamlConfiguration.loadConfiguration(configFile); setupConfig(); - } catch (final Exception err_trans) { + } + catch (final Exception err_trans) + { log("Failed to save settings.yml"); } - try { + try + { storageFile = new File(IMP.getDirectory() + File.separator + "config" + File.separator + "storage.yml"); - if (!storageFile.exists()) { - if (!storageFile.createNewFile()) { + if (!storageFile.exists()) + { + if (!storageFile.createNewFile()) + { log("Could not the storage settings file, please create \"storage.yml\" manually."); } } storage = YamlConfiguration.loadConfiguration(storageFile); setupStorage(); - } catch (final Exception err_trans) { + } + catch (final Exception err_trans) + { log("Failed to save storage.yml"); } - try { + try + { style.save(styleFile); config.save(configFile); storage.save(storageFile); - } catch (final IOException e) { + } + catch (final IOException e) + { log("Configuration file saving failed"); e.printStackTrace(); } @@ -2087,8 +2401,9 @@ public class PS { /** * Setup the storage file (load + save missing nodes) */ - private void setupStorage() { - storage.set("version", StringMan.join(VERSION,".")); + private void setupStorage() + { + storage.set("version", StringMan.join(VERSION, ".")); final Map options = new HashMap<>(); options.put("mysql.use", false); options.put("sqlite.use", true); @@ -2099,8 +2414,10 @@ 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())) { + for (final Entry node : options.entrySet()) + { + if (!storage.contains(node.getKey())) + { storage.set(node.getKey(), node.getValue()); } } @@ -2119,12 +2436,13 @@ public class PS { Settings.DELETE_PLOTS_ON_BAN = config.getBoolean("clear.on.ban"); } - /** * Show startup debug information */ - public void showDebug() { - if (Settings.DEBUG) { + public void showDebug() + { + if (Settings.DEBUG) + { final Map settings = new HashMap<>(); settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); settings.put("Use Metrics", "" + Settings.METRICS); @@ -2136,7 +2454,8 @@ 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 (final Entry setting : settings.entrySet()) + { log(C.PREFIX.s() + String.format("&cKey: &6%s&c, Value: &6%s", setting.getKey(), setting.getValue())); } } @@ -2145,44 +2464,47 @@ public class PS { /** * Setup the style.yml file */ - private void setupStyle() { - style.set("version", StringMan.join(VERSION,".")); + private void setupStyle() + { + style.set("version", StringMan.join(VERSION, ".")); final 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()) { + if (!style.contains("color")) + { + for (final Entry node : o.entrySet()) + { style.set(node.getKey(), node.getValue()); } } } - /** * Get the java version * @return Java version as a double */ - public double getJavaVersion() { + public double getJavaVersion() + { return Double.parseDouble(System.getProperty("java.specification.version")); } - /** * Get the list of plot world names * @return Set of world names (String) */ - public Set getPlotWorlds() { + public Set getPlotWorlds() + { return plotworlds.keySet(); } - /** * Get a list of PlotWorld objects * @return Collection of PlotWorld objects */ - public Collection getPlotWorldObjects() { + public Collection getPlotWorldObjects() + { return plotworlds.values(); } } diff --git a/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java index b3f45a55e..d4d64ad32 100644 --- a/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java @@ -1,737 +1,803 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// - -package com.intellectualcrafters.plot.api; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.SubCommand; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.AbstractFlag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.PlotWorld; -import com.intellectualcrafters.plot.util.BlockManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.ClusterManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.util.BukkitSetBlockManager; -import com.plotsquared.bukkit.util.BukkitUtil; - -/** - * PlotSquared API - * - * @author Citymonstret - * @author Empire92 - * @version API 2.0 - * - */ - -public class PlotAPI { - - /** - * Permission that allows for admin access, this permission node will allow the player to use any part of the - * plugin, without limitations. - * @deprecated Use C.PERMISSION_ADMIN.s() instead - */ - @Deprecated - public static final String ADMIN_PERMISSION = C.PERMISSION_ADMIN.s(); - - /** - * @deprecated Use new PlotAPI() instead - */ - @Deprecated - public PlotAPI(final JavaPlugin plugin) { - } - - /** - * @param plugin Plugin used to access this method - * - * @throws com.intellectualcrafters.plot.util.PlotSquaredException if the program fails to fetch the PlotSquared - * instance - * @see com.intellectualcrafters.plot.PS - * - * @deprecated Use new PlotAPI() instead - */ - public PlotAPI() { - } - - /** - * Get all plots - * - * @return all plots - * - * @see com.intellectualcrafters.plot.PS#getPlots() - */ - public Set getAllPlots() { - return PS.get().getPlots(); - } - - /** - * Return all plots for a player - * - * @param player Player, whose plots to search for - * - * @return all plots that a player owns - */ - public Set getPlayerPlots(final Player player) { - return PS.get().getPlots(BukkitUtil.getPlayer(player)); - } - - /** - * Add a plot world - * - * @param world World Name - * @param plotWorld Plot World Object - * @param manager World Manager - * - * @see com.intellectualcrafters.plot.PS#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotWorld, - * com.intellectualcrafters.plot.object.PlotManager) - */ - public void addPlotWorld(final String world, final PlotWorld plotWorld, final PlotManager manager) { - PS.get().addPlotWorld(world, plotWorld, manager); - } - - /** - * @return main configuration - * - * @see com.intellectualcrafters.plot.PS#config - */ - public YamlConfiguration getConfig() { - return PS.get().config; - } - - /** - * @return storage configuration - * - * @see com.intellectualcrafters.plot.PS#storage - */ - public YamlConfiguration getStorage() { - return PS.get().storage; - } - - /** - * Get the main class for this plugin
      - Contains a lot of fields and methods - not very well organized
      - * Only use this if you really need it - * - * @return PlotSquared PlotSquared Main Class - * - * @see com.intellectualcrafters.plot.PS - */ - public PS getMain() { - return PS.get(); - } - - /** - * ChunkManager class contains several useful methods
      - * - Chunk deletion
      - * - Moving or copying regions
      - * - plot swapping
      - * - Entity tracking
      - * - region regeneration
      - * - * @return ChunkManager - * - * @see com.intellectualcrafters.plot.util.ChunkManager - */ - public ChunkManager getChunkManager() { - return ChunkManager.manager; - } - - /** - * BlockManager class contains useful methods relating to blocks. - * - * @return BlockManager - * - * @see com.intellectualcrafters.plot.util.BlockManager - */ - public BlockManager getBlockManager() { - return BlockManager.manager; - } - - /** - * BukkitSetBlockManager class contains useful methods relating to bukkit blocks. - * - * @return BukkitSetBlockManager - * - * @see com.plotsquared.bukkit.util.BukkitSetBlockManager - */ - public BukkitSetBlockManager getBukkitBlockManager() { - return BukkitSetBlockManager.setBlockManager; - } - - /** - * UUIDWrapper class has basic methods for getting UUIDS (it's recommended to use the UUIDHandler class instead) - * - * @return UUIDWrapper - * - * @see com.intellectualcrafters.plot.uuid.UUIDWrapper - */ - public UUIDWrapper getUUIDWrapper() { - return UUIDHandler.getUUIDWrapper(); - } - - /** - * Do not use this. Instead use FlagManager.[method] in your code. - * - Flag related stuff - * - * @return FlagManager - * - * @see com.intellectualcrafters.plot.flag.FlagManager - */ - @Deprecated - public FlagManager getFlagManager() { - return new FlagManager(); - } - - /** - * Do not use this. Instead use ClusterManager.[method] in your code. - * - Plot cluster related stuff - * - * @return ClusterManager - * - * @see com.intellectualcrafters.plot.util.ClusterManager - */ - @Deprecated - public ClusterManager getClusterManager() { - return new ClusterManager(); - } - - /** - * Do not use this. Instead use MainUtil.[method] in your code. - * - Basic plot management stuff - * - * @return MainUtil - * - * @see com.intellectualcrafters.plot.util.MainUtil - */ - @Deprecated - public MainUtil getMainUtil() { - return new MainUtil(); - } - - /** - * Do not use this. Instead use C.PERMISSION_[method] in your code. - * - Basic permission management stuff - * - * @return Array of strings - * - * @see com.intellectualcrafters.plot.util.Permissions - */ - @Deprecated - public String[] getPermissions() { - ArrayList perms = new ArrayList<>(); - for (C c : C.values()) { - if (c.getCat().equals("static.permissions")) { - perms.add(c.s()); - } - } - return perms.toArray(new String[0]); - } - - /** - * SchematicHandler class contains methods related to pasting, reading and writing schematics - * - * @return SchematicHandler - * - * @see com.intellectualcrafters.plot.util.SchematicHandler - */ - public SchematicHandler getSchematicHandler() { - return SchematicHandler.manager; - } - - /** - * Use C.[caption] instead - * - * @return C - * - * @see com.intellectualcrafters.plot.config.C - */ - @Deprecated - public C[] getCaptions() { - return C.values(); - } - - /** - * Get the plot manager for a world. - Most of these methods can be accessed through the MainUtil - * - * @param world Which manager to get - * - * @return PlotManager - * - * @see com.intellectualcrafters.plot.object.PlotManager - * @see PS#getPlotManager(String) - */ - public PlotManager getPlotManager(final World world) { - return PS.get().getPlotManager(world.getName()); - } - - /** - * Get the plot manager for a world. - Contains useful low level methods for plot merging, clearing, and - * tessellation - * - * @param world - * - * @return PlotManager - * - * @see PS#getPlotManager(String) - * @see com.intellectualcrafters.plot.object.PlotManager - */ - public PlotManager getPlotManager(final String world) { - return PS.get().getPlotManager(world); - } - - /** - * Get the settings for a world (settings bundled in PlotWorld class) - You will need to downcast for the specific - * settings a Generator has. e.g. DefaultPlotWorld class implements PlotWorld - * - * @param world (to get settings of) - * - * @return PlotWorld class for that world ! will return null if not a plot world world - * - * @see PS#getPlotWorld(String) - * @see com.intellectualcrafters.plot.object.PlotWorld - */ - public PlotWorld getWorldSettings(final World world) { - return PS.get().getPlotWorld(world.getName()); - } - - /** - * Get the settings for a world (settings bundled in PlotWorld class) - * - * @param world (to get settings of) - * - * @return PlotWorld class for that world ! will return null if not a plot world world - * - * @see PS#getPlotWorld(String) - * @see com.intellectualcrafters.plot.object.PlotWorld - */ - public PlotWorld getWorldSettings(final String world) { - return PS.get().getPlotWorld(world); - } - - /** - * Send a message to a player. - * - * @param player Player that will receive the message - * @param c (Caption) - * - * @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, C, String...) - * com.intellectualcrafters.plot.config.C, String...) - */ - public void sendMessage(final Player player, final C c) { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), c); - } - - /** - * Send a message to a player. - Supports color codes - * - * @param player Player that will receive the message - * @param string The message - * - * @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, String) - */ - public void sendMessage(final Player player, final String string) { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), string); - } - - /** - * Send a message to the console. - Supports color codes - * - * @param msg Message that should be sent to the console - * - * @see MainUtil#sendConsoleMessage(String) - */ - public void sendConsoleMessage(final String msg) { - MainUtil.sendConsoleMessage(msg); - } - - /** - * Send a message to the console - * - * @param c (Caption) - * - * @see #sendConsoleMessage(String) - * @see com.intellectualcrafters.plot.config.C - */ - public void sendConsoleMessage(final C c) { - sendConsoleMessage(c.s()); - } - - /** - * Register a flag for use in plots - * - * @param flag Flag that should be registered - * - * @see com.intellectualcrafters.plot.flag.FlagManager#addFlag(com.intellectualcrafters.plot.flag.AbstractFlag) - * @see com.intellectualcrafters.plot.flag.AbstractFlag - */ - public void addFlag(final AbstractFlag flag) { - FlagManager.addFlag(flag); - } - - /** - * get all the currently registered flags - * - * @return array of Flag[] - * - * @see com.intellectualcrafters.plot.flag.FlagManager#getFlags() - * @see com.intellectualcrafters.plot.flag.AbstractFlag - */ - public AbstractFlag[] getFlags() { - return FlagManager.getFlags().toArray(new AbstractFlag[FlagManager.getFlags().size()]); - } - - /** - * Get a plot based on the ID - * - * @param world World in which the plot is located - * @param x Plot Location X Co-ord - * @param z Plot Location Z Co-ord - * - * @return plot, null if ID is wrong - * - * @see MainUtil#getPlot(String, com.intellectualcrafters.plot.object.PlotId) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Plot getPlot(final World world, final int x, final int z) { - return MainUtil.getPlot(world.getName(), new PlotId(x, z)); - } - - /** - * Get a plot based on the location - * - * @param l The location that you want to to retrieve the plot from - * - * @return plot if found, otherwise it creates a temporary plot- - * - * @see MainUtil#getPlot(com.intellectualcrafters.plot.object.Location) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Plot getPlot(final Location l) { - return MainUtil.getPlot(BukkitUtil.getLocation(l)); - } - - /** - * Get a plot based on the player location - * - * @param player Get the current plot for the player location - * - * @return plot if found, otherwise it creates a temporary plot - * - * @see #getPlot(org.bukkit.Location) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Plot getPlot(final Player player) { - return this.getPlot(player.getLocation()); - } - - /** - * Check whether or not a player has a plot - * - * @param player Player that you want to check for - * - * @return true if player has a plot, false if not. - * - * @see #getPlots(World, Player, boolean) - */ - public boolean hasPlot(final World world, final Player player) { - return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); - } - - /** - * Get all plots for the player - * - * @param plr to search for - * @param just_owner should we just search for owner? Or with rights? - * - * @see com.intellectualcrafters.plot.object.Plot - */ - public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) { - final ArrayList pPlots = new ArrayList<>(); - for (final Plot plot : PS.get().getPlotsInWorld(world.getName())) { - if (just_owner) { - if ((plot.owner != null) && (plot.owner.equals(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr))))) { - pPlots.add(plot); - } - } else { - if (plot.isAdded(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr)))) { - pPlots.add(plot); - } - } - } - return pPlots.toArray(new Plot[pPlots.size()]); - } - - /** - * Get all plots for the world - * - * @param world to get plots of - * - * @return Plot[] - array of plot objects in world - * - * @see PS#getPlots(String) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Plot[] getPlots(final World world) { - Collection plots = PS.get().getPlotsInWorld(world.getName()); - return plots.toArray(new Plot[plots.size()]); - } - - /** - * Get all plot worlds - * - * @return World[] - array of plot worlds - * - * @see com.intellectualcrafters.plot.PS#getPlotWorlds() - */ - public String[] getPlotWorlds() { - Set worlds = PS.get().getPlotWorlds(); - return worlds.toArray(new String[worlds.size()]); - } - - /** - * Get if plot world - * - * @param world (to check if plot world) - * - * @return boolean (if plot world or not) - * - * @see com.intellectualcrafters.plot.PS#isPlotWorld(String) - */ - public boolean isPlotWorld(final World world) { - return PS.get().isPlotWorld(world.getName()); - } - - /** - * Get plot locations - * - * @param p Plot that you want to get the locations for - * - * @return [0] = bottomLc, [1] = topLoc, [2] = home - * - * @see com.intellectualcrafters.plot.util.MainUtil#getPlotBottomLoc(String, - * com.intellectualcrafters.plot.object.PlotId) - * @see com.intellectualcrafters.plot.util.MainUtil#getPlotTopLoc(String, - * com.intellectualcrafters.plot.object.PlotId) - * @see com.intellectualcrafters.plot.util.MainUtil#getPlotHome(String, - * com.intellectualcrafters.plot.object.Plot) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Location[] getLocations(final Plot p) { - return new Location[]{BukkitUtil.getLocation(MainUtil.getPlotBottomLoc(p.world, p.id)), BukkitUtil.getLocation(MainUtil.getPlotTopLoc(p.world, p.id)), BukkitUtil.getLocation(MainUtil.getPlotHome(p.world, p.id))}; - } - - /** - * Get home location - * - * @param p Plot that you want to get the location for - * - * @return plot bottom location - * - * @see com.intellectualcrafters.plot.util.MainUtil#getPlotHome(String, - * com.intellectualcrafters.plot.object.Plot) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Location getHomeLocation(final Plot p) { - return BukkitUtil.getLocation(MainUtil.getPlotHome(p.world, p.id)); - } - - /** - * Get Bottom Location (min, min, min) - * - * @param p Plot that you want to get the location for - * - * @return plot bottom location - * - * @see com.intellectualcrafters.plot.util.MainUtil#getPlotBottomLoc(String, - * com.intellectualcrafters.plot.object.PlotId) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Location getBottomLocation(final Plot p) { - return BukkitUtil.getLocation(MainUtil.getPlotBottomLoc(p.world, p.id)); - } - - /** - * Get Top Location (max, max, max) - * - * @param p Plot that you want to get the location for - * - * @return plot top location - * - * @see MainUtil#getPlotTopLoc(String, com.intellectualcrafters.plot.object.PlotId) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Location getTopLocation(final Plot p) { - return BukkitUtil.getLocation(MainUtil.getPlotTopLoc(p.world, p.id)); - } - - /** - * Check whether or not a player is in a plot - * - * @param player who we're checking for - * - * @return true if the player is in a plot, false if not- - * - * @see com.intellectualcrafters.plot.util.MainUtil#getPlot(com.intellectualcrafters.plot.object.Location) - */ - public boolean isInPlot(final Player player) { - return MainUtil.getPlot(BukkitUtil.getLocation(player)) != null; - } - - /** - * Register a subcommand - * - * @param c SubCommand, that we want to register - * - * @see com.intellectualcrafters.plot.commands.SubCommand - */ - public void registerCommand(final SubCommand c) { - if (c.getCommand() != null) { - MainCommand.getInstance().addCommand(c); - } else { - MainCommand.getInstance().createCommand(c); - } - } - - /** - * Get the PlotSquared class - * - * @return PlotSquared Class - * - * @see com.intellectualcrafters.plot.PS - */ - public PS getPlotSquared() { - return PS.get(); - } - - /** - * Get the player plot count - * - * @param world Specify the world we want to select the plots from - * @param player Player, for whom we're getting the plot count - * - * @return the number of plots the player has - * - * @see com.intellectualcrafters.plot.util.MainUtil#getPlayerPlotCount(String, PlotPlayer) - */ - public int getPlayerPlotCount(final World world, final Player player) { - return MainUtil.getPlayerPlotCount(world.getName(), BukkitUtil.getPlayer(player)); - } - - /** - * Get a collection containing the players plots - * - * @param world Specify the world we want to select the plots from - * @param player Player, for whom we're getting the plots - * - * @return a set containing the players plots - * - * @see com.intellectualcrafters.plot.PS#getPlots(String, PlotPlayer) - * org.bukkit.entity.Player) - * @see com.intellectualcrafters.plot.object.Plot - */ - public Set getPlayerPlots(final World world, final Player player) { - return PS.get().getPlots(world.getName(), BukkitUtil.getPlayer(player)); - } - - /** - * Get the numbers of plots, which the player is able to build in - * - * @param player Player, for whom we're getting the plots (trusted, member and owner) - * - * @return the number of allowed plots - * - */ - public int getAllowedPlots(final Player player) { - PlotPlayer pp = BukkitUtil.getPlayer(player); - return MainUtil.getAllowedPlots(pp); - } - - /** - * Get the PlotPlayer for a player
      - * - The PlotPlayer is usually cached and will provide useful functions relating to players - * - * @see PlotPlayer.wrap(Player|OfflinePlayer|String|UUID) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(Player player) { - return PlotPlayer.wrap(player); - } - - /** - * Get the PlotPlayer for a UUID (Please note that PlotSquared can be configured to provide different UUIDs than bukkit) - * - * @see PlotPlayer.wrap(UUID uuid) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(UUID uuid) { - return PlotPlayer.wrap(uuid); - } - - /** - * Get the PlotPlayer for a username - * - * @see PlotPlayer.wrap(String name) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(String player) { - return PlotPlayer.wrap(player); - } - - /** - * Get the PlotPlayer for an offline player
      - * Note that this will work if the player is offline, however not all functionality will work - * - * @see PlotPlayer.wrap(OfflinePlayer op) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(OfflinePlayer player) { - return PlotPlayer.wrap(player); - } -} \ No newline at end of file +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// + +package com.intellectualcrafters.plot.api; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.commands.SubCommand; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.flag.AbstractFlag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; +import com.intellectualcrafters.plot.util.BlockManager; +import com.intellectualcrafters.plot.util.ChunkManager; +import com.intellectualcrafters.plot.util.ClusterManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.SchematicHandler; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.uuid.UUIDWrapper; +import com.plotsquared.bukkit.util.BukkitSetBlockManager; +import com.plotsquared.bukkit.util.BukkitUtil; + +/** + * PlotSquared API + * + * @version API 2.0 + * + */ + +public class PlotAPI +{ + + /** + * Permission that allows for admin access, this permission node will allow the player to use any part of the + * plugin, without limitations. + * @deprecated Use C.PERMISSION_ADMIN.s() instead + */ + @Deprecated + public static final String ADMIN_PERMISSION = C.PERMISSION_ADMIN.s(); + + /** + * @deprecated Use new PlotAPI() instead + */ + @Deprecated + public PlotAPI(final JavaPlugin plugin) + {} + + /** + * @param plugin Plugin used to access this method + * + * @throws com.intellectualcrafters.plot.util.PlotSquaredException if the program fails to fetch the PlotSquared + * instance + * @see com.intellectualcrafters.plot.PS + * + * @deprecated Use this class if you just want to do a few simple things.
      + * - It will remain stable for future versions of the plugin + * - The PlotPlayer and Plot class should be considered relatively safe + * - For more advanced/intensive tasks you should consider using other classes + * + * + */ + @Deprecated + public PlotAPI() + {} + + /** + * Get all plots + * + * @return all plots + * + * @see com.intellectualcrafters.plot.PS#getPlots() + */ + public Set getAllPlots() + { + return PS.get().getPlots(); + } + + /** + * Return all plots for a player + * + * @param player Player, whose plots to search for + * + * @return all plots that a player owns + */ + public Set getPlayerPlots(final Player player) + { + return PS.get().getPlots(BukkitUtil.getPlayer(player)); + } + + /** + * Add a plot world + * + * @param world World Name + * @param plotWorld Plot World Object + * @param manager World Manager + * + * @see com.intellectualcrafters.plot.PS#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotWorld, + * com.intellectualcrafters.plot.object.PlotManager) + */ + public void addPlotWorld(final String world, final PlotWorld plotWorld, final PlotManager manager) + { + PS.get().addPlotWorld(world, plotWorld, manager); + } + + /** + * @return main configuration + * + * @see com.intellectualcrafters.plot.PS#config + */ + public YamlConfiguration getConfig() + { + return PS.get().config; + } + + /** + * @return storage configuration + * + * @see com.intellectualcrafters.plot.PS#storage + */ + public YamlConfiguration getStorage() + { + return PS.get().storage; + } + + /** + * Get the main class for this plugin
      - Contains a lot of fields and methods - not very well organized
      + * Only use this if you really need it + * + * @return PlotSquared PlotSquared Main Class + * + * @see com.intellectualcrafters.plot.PS + */ + public PS getMain() + { + return PS.get(); + } + + /** + * ChunkManager class contains several useful methods
      + * - Chunk deletion
      + * - Moving or copying regions
      + * - plot swapping
      + * - Entity tracking
      + * - region regeneration
      + * + * @return ChunkManager + * + * @see com.intellectualcrafters.plot.util.ChunkManager + */ + public ChunkManager getChunkManager() + { + return ChunkManager.manager; + } + + /** + * BlockManager class contains useful methods relating to blocks. + * + * @return BlockManager + * + * @see com.intellectualcrafters.plot.util.BlockManager + */ + public BlockManager getBlockManager() + { + return BlockManager.manager; + } + + /** + * BukkitSetBlockManager class contains useful methods relating to bukkit blocks. + * + * @return BukkitSetBlockManager + * + * @see com.plotsquared.bukkit.util.BukkitSetBlockManager + */ + public BukkitSetBlockManager getBukkitBlockManager() + { + return BukkitSetBlockManager.setBlockManager; + } + + /** + * UUIDWrapper class has basic methods for getting UUIDS (it's recommended to use the UUIDHandler class instead) + * + * @return UUIDWrapper + * + * @see com.intellectualcrafters.plot.uuid.UUIDWrapper + */ + public UUIDWrapper getUUIDWrapper() + { + return UUIDHandler.getUUIDWrapper(); + } + + /** + * Do not use this. Instead use FlagManager.[method] in your code. + * - Flag related stuff + * + * @return FlagManager + * + * @see com.intellectualcrafters.plot.flag.FlagManager + */ + @Deprecated + public FlagManager getFlagManager() + { + return new FlagManager(); + } + + /** + * Do not use this. Instead use ClusterManager.[method] in your code. + * - Plot cluster related stuff + * + * @return ClusterManager + * + * @see com.intellectualcrafters.plot.util.ClusterManager + */ + @Deprecated + public ClusterManager getClusterManager() + { + return new ClusterManager(); + } + + /** + * Do not use this. Instead use MainUtil.[method] in your code. + * - Basic plot management stuff + * + * @return MainUtil + * + * @see com.intellectualcrafters.plot.util.MainUtil + */ + @Deprecated + public MainUtil getMainUtil() + { + return new MainUtil(); + } + + /** + * Do not use this. Instead use C.PERMISSION_[method] in your code. + * - Basic permission management stuff + * + * @return Array of strings + * + * @see com.intellectualcrafters.plot.util.Permissions + */ + @Deprecated + public String[] getPermissions() + { + final ArrayList perms = new ArrayList<>(); + for (final C c : C.values()) + { + if (c.getCat().equals("static.permissions")) + { + perms.add(c.s()); + } + } + return perms.toArray(new String[0]); + } + + /** + * SchematicHandler class contains methods related to pasting, reading and writing schematics + * + * @return SchematicHandler + * + * @see com.intellectualcrafters.plot.util.SchematicHandler + */ + public SchematicHandler getSchematicHandler() + { + return SchematicHandler.manager; + } + + /** + * Use C.[caption] instead + * + * @return C + * + * @see com.intellectualcrafters.plot.config.C + */ + @Deprecated + public C[] getCaptions() + { + return C.values(); + } + + /** + * Get the plot manager for a world. - Most of these methods can be accessed through the MainUtil + * + * @param world Which manager to get + * + * @return PlotManager + * + * @see com.intellectualcrafters.plot.object.PlotManager + * @see PS#getPlotManager(String) + */ + public PlotManager getPlotManager(final World world) + { + return PS.get().getPlotManager(world.getName()); + } + + /** + * Get the plot manager for a world. - Contains useful low level methods for plot merging, clearing, and + * tessellation + * + * @param world + * + * @return PlotManager + * + * @see PS#getPlotManager(String) + * @see com.intellectualcrafters.plot.object.PlotManager + */ + public PlotManager getPlotManager(final String world) + { + return PS.get().getPlotManager(world); + } + + /** + * Get the settings for a world (settings bundled in PlotWorld class) - You will need to downcast for the specific + * settings a Generator has. e.g. DefaultPlotWorld class implements PlotWorld + * + * @param world (to get settings of) + * + * @return PlotWorld class for that world ! will return null if not a plot world world + * + * @see PS#getPlotWorld(String) + * @see com.intellectualcrafters.plot.object.PlotWorld + */ + public PlotWorld getWorldSettings(final World world) + { + return PS.get().getPlotWorld(world.getName()); + } + + /** + * Get the settings for a world (settings bundled in PlotWorld class) + * + * @param world (to get settings of) + * + * @return PlotWorld class for that world ! will return null if not a plot world world + * + * @see PS#getPlotWorld(String) + * @see com.intellectualcrafters.plot.object.PlotWorld + */ + public PlotWorld getWorldSettings(final String world) + { + return PS.get().getPlotWorld(world); + } + + /** + * Send a message to a player. + * + * @param player Player that will receive the message + * @param c (Caption) + * + * @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, C, String...) + * com.intellectualcrafters.plot.config.C, String...) + */ + public void sendMessage(final Player player, final C c) + { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), c); + } + + /** + * Send a message to a player. - Supports color codes + * + * @param player Player that will receive the message + * @param string The message + * + * @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, String) + */ + public void sendMessage(final Player player, final String string) + { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), string); + } + + /** + * Send a message to the console. - Supports color codes + * + * @param msg Message that should be sent to the console + * + * @see MainUtil#sendConsoleMessage(String) + */ + public void sendConsoleMessage(final String msg) + { + MainUtil.sendConsoleMessage(msg); + } + + /** + * Send a message to the console + * + * @param c (Caption) + * + * @see #sendConsoleMessage(String) + * @see com.intellectualcrafters.plot.config.C + */ + public void sendConsoleMessage(final C c) + { + sendConsoleMessage(c.s()); + } + + /** + * Register a flag for use in plots + * + * @param flag Flag that should be registered + * + * @see com.intellectualcrafters.plot.flag.FlagManager#addFlag(com.intellectualcrafters.plot.flag.AbstractFlag) + * @see com.intellectualcrafters.plot.flag.AbstractFlag + */ + public void addFlag(final AbstractFlag flag) + { + FlagManager.addFlag(flag); + } + + /** + * get all the currently registered flags + * + * @return array of Flag[] + * + * @see com.intellectualcrafters.plot.flag.FlagManager#getFlags() + * @see com.intellectualcrafters.plot.flag.AbstractFlag + */ + public AbstractFlag[] getFlags() + { + return FlagManager.getFlags().toArray(new AbstractFlag[FlagManager.getFlags().size()]); + } + + /** + * Get a plot based on the ID + * + * @param world World in which the plot is located + * @param x Plot Location X Co-ord + * @param z Plot Location Z Co-ord + * + * @return plot, null if ID is wrong + * + * @see MainUtil#getPlot(String, com.intellectualcrafters.plot.object.PlotId) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Plot getPlot(final World world, final int x, final int z) + { + return MainUtil.getPlot(world.getName(), new PlotId(x, z)); + } + + /** + * Get a plot based on the location + * + * @param l The location that you want to to retrieve the plot from + * + * @return plot if found, otherwise it creates a temporary plot- + * + * @see MainUtil#getPlot(com.intellectualcrafters.plot.object.Location) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Plot getPlot(final Location l) + { + return MainUtil.getPlot(BukkitUtil.getLocation(l)); + } + + /** + * Get a plot based on the player location + * + * @param player Get the current plot for the player location + * + * @return plot if found, otherwise it creates a temporary plot + * + * @see #getPlot(org.bukkit.Location) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Plot getPlot(final Player player) + { + return this.getPlot(player.getLocation()); + } + + /** + * Check whether or not a player has a plot + * + * @param player Player that you want to check for + * + * @return true if player has a plot, false if not. + * + * @see #getPlots(World, Player, boolean) + */ + public boolean hasPlot(final World world, final Player player) + { + return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); + } + + /** + * Get all plots for the player + * + * @param plr to search for + * @param just_owner should we just search for owner? Or with rights? + * + * @see com.intellectualcrafters.plot.object.Plot + */ + public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) + { + final ArrayList pPlots = new ArrayList<>(); + for (final Plot plot : PS.get().getPlotsInWorld(world.getName())) + { + if (just_owner) + { + if ((plot.owner != null) && (plot.owner.equals(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr))))) + { + pPlots.add(plot); + } + } + else + { + if (plot.isAdded(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr)))) + { + pPlots.add(plot); + } + } + } + return pPlots.toArray(new Plot[pPlots.size()]); + } + + /** + * Get all plots for the world + * + * @param world to get plots of + * + * @return Plot[] - array of plot objects in world + * + * @see PS#getPlots(String) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Plot[] getPlots(final World world) + { + final Collection plots = PS.get().getPlotsInWorld(world.getName()); + return plots.toArray(new Plot[plots.size()]); + } + + /** + * Get all plot worlds + * + * @return World[] - array of plot worlds + * + * @see com.intellectualcrafters.plot.PS#getPlotWorlds() + */ + public String[] getPlotWorlds() + { + final Set worlds = PS.get().getPlotWorlds(); + return worlds.toArray(new String[worlds.size()]); + } + + /** + * Get if plot world + * + * @param world (to check if plot world) + * + * @return boolean (if plot world or not) + * + * @see com.intellectualcrafters.plot.PS#isPlotWorld(String) + */ + public boolean isPlotWorld(final World world) + { + return PS.get().isPlotWorld(world.getName()); + } + + /** + * Get plot locations + * + * @param p Plot that you want to get the locations for + * + * @return [0] = bottomLc, [1] = topLoc, [2] = home + * + * @see com.intellectualcrafters.plot.util.MainUtil#getPlotBottomLoc(String, + * com.intellectualcrafters.plot.object.PlotId) + * @see com.intellectualcrafters.plot.util.MainUtil#getPlotTopLoc(String, + * com.intellectualcrafters.plot.object.PlotId) + * @see com.intellectualcrafters.plot.util.MainUtil#getPlotHome(String, + * com.intellectualcrafters.plot.object.Plot) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Location[] getLocations(final Plot p) + { + return new Location[] { + BukkitUtil.getLocation(MainUtil.getPlotBottomLoc(p.world, p.id)), + BukkitUtil.getLocation(MainUtil.getPlotTopLoc(p.world, p.id)), + BukkitUtil.getLocation(MainUtil.getPlotHome(p.world, p.id)) }; + } + + /** + * Get home location + * + * @param p Plot that you want to get the location for + * + * @return plot bottom location + * + * @see com.intellectualcrafters.plot.util.MainUtil#getPlotHome(String, + * com.intellectualcrafters.plot.object.Plot) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Location getHomeLocation(final Plot p) + { + return BukkitUtil.getLocation(MainUtil.getPlotHome(p.world, p.id)); + } + + /** + * Get Bottom Location (min, min, min) + * + * @param p Plot that you want to get the location for + * + * @return plot bottom location + * + * @see com.intellectualcrafters.plot.util.MainUtil#getPlotBottomLoc(String, + * com.intellectualcrafters.plot.object.PlotId) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Location getBottomLocation(final Plot p) + { + return BukkitUtil.getLocation(MainUtil.getPlotBottomLoc(p.world, p.id)); + } + + /** + * Get Top Location (max, max, max) + * + * @param p Plot that you want to get the location for + * + * @return plot top location + * + * @see MainUtil#getPlotTopLoc(String, com.intellectualcrafters.plot.object.PlotId) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Location getTopLocation(final Plot p) + { + return BukkitUtil.getLocation(MainUtil.getPlotTopLoc(p.world, p.id)); + } + + /** + * Check whether or not a player is in a plot + * + * @param player who we're checking for + * + * @return true if the player is in a plot, false if not- + * + * @see com.intellectualcrafters.plot.util.MainUtil#getPlot(com.intellectualcrafters.plot.object.Location) + */ + public boolean isInPlot(final Player player) + { + return MainUtil.getPlot(BukkitUtil.getLocation(player)) != null; + } + + /** + * Register a subcommand + * + * @param c SubCommand, that we want to register + * + * @see com.intellectualcrafters.plot.commands.SubCommand + */ + public void registerCommand(final SubCommand c) + { + if (c.getCommand() != null) + { + MainCommand.getInstance().addCommand(c); + } + else + { + MainCommand.getInstance().createCommand(c); + } + } + + /** + * Get the PlotSquared class + * + * @return PlotSquared Class + * + * @see com.intellectualcrafters.plot.PS + */ + public PS getPlotSquared() + { + return PS.get(); + } + + /** + * Get the player plot count + * + * @param world Specify the world we want to select the plots from + * @param player Player, for whom we're getting the plot count + * + * @return the number of plots the player has + * + * @see com.intellectualcrafters.plot.util.MainUtil#getPlayerPlotCount(String, PlotPlayer) + */ + public int getPlayerPlotCount(final World world, final Player player) + { + return MainUtil.getPlayerPlotCount(world.getName(), BukkitUtil.getPlayer(player)); + } + + /** + * Get a collection containing the players plots + * + * @param world Specify the world we want to select the plots from + * @param player Player, for whom we're getting the plots + * + * @return a set containing the players plots + * + * @see com.intellectualcrafters.plot.PS#getPlots(String, PlotPlayer) + * org.bukkit.entity.Player) + * @see com.intellectualcrafters.plot.object.Plot + */ + public Set getPlayerPlots(final World world, final Player player) + { + return PS.get().getPlots(world.getName(), BukkitUtil.getPlayer(player)); + } + + /** + * Get the numbers of plots, which the player is able to build in + * + * @param player Player, for whom we're getting the plots (trusted, member and owner) + * + * @return the number of allowed plots + * + */ + public int getAllowedPlots(final Player player) + { + final PlotPlayer pp = BukkitUtil.getPlayer(player); + return MainUtil.getAllowedPlots(pp); + } + + /** + * Get the PlotPlayer for a player
      + * - The PlotPlayer is usually cached and will provide useful functions relating to players + * + * @see PlotPlayer.wrap(Player|OfflinePlayer|String|UUID) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final Player player) + { + return PlotPlayer.wrap(player); + } + + /** + * Get the PlotPlayer for a UUID (Please note that PlotSquared can be configured to provide different UUIDs than bukkit) + * + * @see PlotPlayer.wrap(UUID uuid) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final UUID uuid) + { + return PlotPlayer.wrap(uuid); + } + + /** + * Get the PlotPlayer for a username + * + * @see PlotPlayer.wrap(String name) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final String player) + { + return PlotPlayer.wrap(player); + } + + /** + * Get the PlotPlayer for an offline player
      + * Note that this will work if the player is offline, however not all functionality will work + * + * @see PlotPlayer.wrap(OfflinePlayer op) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final OfflinePlayer player) + { + return PlotPlayer.wrap(player); + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Add.java b/src/main/java/com/intellectualcrafters/plot/commands/Add.java index e3926e49b..63dabddd5 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Add.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Add.java @@ -32,71 +32,82 @@ import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.bukkit.uuid.SQLUUIDHandler; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "add", - aliases = {"a"}, - description = "Allow a user to build while you are online", - usage = "/plot add ", - category = CommandCategory.ACTIONS, - permission = "plots.add", - requiredType = RequiredType.NONE -) -public class Add extends SubCommand { +command = "add", +aliases = { "a" }, +description = "Allow a user to build while you are online", +usage = "/plot add ", +category = CommandCategory.ACTIONS, +permission = "plots.add", +requiredType = RequiredType.NONE) +public class Add extends SubCommand +{ - public Add() { + public Add() + { requiredArguments = new Argument[] { - Argument.PlayerName + Argument.PlayerName }; } @Override - public boolean onCommand(PlotPlayer plr, String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.add")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.add")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return true; } UUID uuid; - if (args[0].equalsIgnoreCase("*")) { + if (args[0].equalsIgnoreCase("*")) + { uuid = DBFunc.everyone; - } else { + } + else + { // TODO have a runnable for fetch uuid = UUIDHandler.getUUID(args[0], null); } - if (uuid == null) { + if (uuid == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - if (plot.isOwner(uuid)) { + if (plot.isOwner(uuid)) + { MainUtil.sendMessage(plr, C.ALREADY_OWNER); return false; } - - if (plot.getMembers().contains(uuid)) { + + if (plot.getMembers().contains(uuid)) + { MainUtil.sendMessage(plr, C.ALREADY_ADDED); return false; } - if (plot.removeTrusted(uuid)) { + if (plot.removeTrusted(uuid)) + { plot.addMember(uuid); } - else { - if (plot.getMembers().size() + plot.getTrusted().size() >= PS.get().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) { + else + { + if ((plot.getMembers().size() + plot.getTrusted().size()) >= PS.get().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) + { MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS); return false; } - if (plot.getDenied().contains(uuid)) { + if (plot.getDenied().contains(uuid)) + { plot.removeDenied(uuid); } plot.addMember(uuid); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/src/main/java/com/intellectualcrafters/plot/commands/Auto.java index aaa54114b..76d307673 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Auto.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Auto.java @@ -29,84 +29,102 @@ import com.intellectualcrafters.plot.object.PlotCluster; import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotWorld; -import com.intellectualcrafters.plot.util.ClusterManager; import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.MainUtil; 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" -) -public class Auto extends SubCommand { +command = "auto", +permission = "plots.auto", +category = CommandCategory.CLAIMING, +requiredType = RequiredType.NONE, +description = "Claim the nearest plot", +aliases = { "a" }, +usage = "/plot auto") +public class Auto extends SubCommand +{ - public static PlotId getNextPlot(final PlotId id, final int step) { + public static PlotId getNextPlot(final PlotId id, final int step) + { final int absX = Math.abs(id.x); final int absY = Math.abs(id.y); - if (absX > absY) { - if (id.x > 0) { + if (absX > absY) + { + if (id.x > 0) + { return new PlotId(id.x, id.y + 1); - } else { + } + else + { return new PlotId(id.x, id.y - 1); } - } else if (absY > absX) { - if (id.y > 0) { + } + else if (absY > absX) + { + if (id.y > 0) + { return new PlotId(id.x - 1, id.y); - } else { + } + else + { return new PlotId(id.x + 1, id.y); } - } else { - if (id.x.equals(id.y) && (id.x > 0)) { - return new PlotId(id.x, id.y + step); - } - if (id.x == absX) { - return new PlotId(id.x, id.y + 1); - } - if (id.y == absY) { - return new PlotId(id.x, id.y - 1); - } + } + else + { + if (id.x.equals(id.y) && (id.x > 0)) { return new PlotId(id.x, id.y + step); } + if (id.x == absX) { return new PlotId(id.x, id.y + 1); } + if (id.y == absY) { return new PlotId(id.x, id.y - 1); } return new PlotId(id.x + 1, id.y); } } @Override - public boolean onCommand(PlotPlayer plr, String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + String world; int size_x = 1; int size_z = 1; String schematic = ""; - if (PS.get().getPlotWorlds().size() == 1) { + if (PS.get().getPlotWorlds().size() == 1) + { world = PS.get().getPlotWorlds().iterator().next(); - } else { + } + else + { world = plr.getLocation().getWorld(); - if (!PS.get().isPlotWorld(world)) { + if (!PS.get().isPlotWorld(world)) + { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; } } - if (args.length > 0) { - if (Permissions.hasPermission(plr, "plots.auto.mega")) { - try { + if (args.length > 0) + { + if (Permissions.hasPermission(plr, "plots.auto.mega")) + { + try + { final String[] split = args[0].split(","); size_x = Integer.parseInt(split[0]); size_z = Integer.parseInt(split[1]); - if ((size_x < 1) || (size_z < 1)) { + if ((size_x < 1) || (size_z < 1)) + { MainUtil.sendMessage(plr, "&cError: size<=0"); } - if ((size_x > 4) || (size_z > 4)) { + if ((size_x > 4) || (size_z > 4)) + { MainUtil.sendMessage(plr, "&cError: size>4"); } - if (args.length > 1) { + if (args.length > 1) + { schematic = args[1]; } - } catch (final Exception e) { + } + catch (final Exception e) + { size_x = 1; size_z = 1; schematic = args[0]; @@ -114,32 +132,42 @@ public class Auto extends SubCommand { // "&cError: Invalid size (X,Y)"); // return false; } - } else { + } + else + { schematic = args[0]; // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); // return false; } } - if ((size_x * size_z) > Settings.MAX_AUTO_SIZE) { + if ((size_x * size_z) > Settings.MAX_AUTO_SIZE) + { MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, Settings.MAX_AUTO_SIZE + ""); return false; } final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(world, plr); final int diff = currentPlots - MainUtil.getAllowedPlots(plr); - if ((diff + (size_x * size_z)) > 0) { - if (diff < 0) { + if ((diff + (size_x * size_z)) > 0) + { + if (diff < 0) + { MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, (-diff) + ""); - } else { + } + else + { MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); } return false; } final PlotWorld pWorld = PS.get().getPlotWorld(world); - if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) { + if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) + { double cost = pWorld.PLOT_PRICE; cost = (size_x * size_z) * cost; - if (cost > 0d) { - if (EconHandler.manager.getMoney(plr) < cost) { + if (cost > 0d) + { + if (EconHandler.manager.getMoney(plr) < cost) + { sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); return true; } @@ -147,13 +175,16 @@ public class Auto extends SubCommand { sendMessage(plr, C.REMOVED_BALANCE, cost + ""); } } - if (!schematic.equals("")) { + if (!schematic.equals("")) + { // if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { - if (!pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { + if (!pWorld.SCHEMATICS.contains(schematic.toLowerCase())) + { sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); return true; } - if (!Permissions.hasPermission(plr, "plots.claim." + schematic) && !Permissions.hasPermission(plr, "plots.admin.command.schematic")) { + if (!Permissions.hasPermission(plr, "plots.claim." + schematic) && !Permissions.hasPermission(plr, "plots.admin.command.schematic")) + { MainUtil.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); return true; } @@ -161,15 +192,15 @@ public class Auto extends SubCommand { } final String worldname = world; final PlotWorld plotworld = PS.get().getPlotWorld(worldname); - if (plotworld.TYPE == 2) { + if (plotworld.TYPE == 2) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(new Location(worldname, loc.getX(), loc.getY(), loc.getZ())); - if (plot == null) { - return sendMessage(plr, C.NOT_IN_PLOT); - } + if (plot == null) { return sendMessage(plr, C.NOT_IN_PLOT); } final PlotCluster cluster = plot.getCluster(); // Must be standing in a cluster - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } @@ -180,10 +211,12 @@ public class Auto extends SubCommand { final int width = Math.max((top.x - bot.x) + 1, (top.y - bot.y) + 1); final int max = width * width; // - for (int i = 0; i <= max; i++) { + for (int i = 0; i <= max; i++) + { final PlotId currentId = new PlotId(origin.x + id.x, origin.y + id.y); final Plot current = MainUtil.getPlot(worldname, currentId); - if (MainUtil.canClaim(plr, current) && (current.getSettings().isMerged() == false) && cluster.equals(current.getCluster())) { + if (MainUtil.canClaim(plr, current) && (current.getSettings().isMerged() == false) && cluster.equals(current.getCluster())) + { Claim.claimPlot(plr, current, true, true); return true; } @@ -194,40 +227,50 @@ public class Auto extends SubCommand { return false; } boolean br = false; - if ((size_x == 1) && (size_z == 1)) { - while (!br) { + if ((size_x == 1) && (size_z == 1)) + { + while (!br) + { final Plot plot = MainUtil.getPlot(worldname, getLastPlot(worldname)); - if (MainUtil.canClaim(plr, plot)) { + if (MainUtil.canClaim(plr, plot)) + { Claim.claimPlot(plr, plot, true, true); br = true; } MainUtil.lastPlot.put(worldname, getNextPlot(getLastPlot(worldname), 1)); } - } else { + } + else + { boolean lastPlot = true; - while (!br) { + while (!br) + { final PlotId start = getNextPlot(getLastPlot(worldname), 1); // Checking if the current set of plots is a viable option. MainUtil.lastPlot.put(worldname, start); - if (lastPlot) { - } - if ((PS.get().getPlot(worldname, start) != null) && (PS.get().getPlot(worldname, start).owner != null)) { + if (lastPlot) + {} + if ((PS.get().getPlot(worldname, start) != null) && (PS.get().getPlot(worldname, start).owner != null)) + { continue; - } else { + } + else + { lastPlot = false; } final PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1); - if (MainUtil.canClaim(plr, worldname, start, end)) { - for (int i = start.x; i <= end.x; i++) { - for (int j = start.y; j <= end.y; j++) { + if (MainUtil.canClaim(plr, worldname, start, end)) + { + for (int i = start.x; i <= end.x; i++) + { + for (int j = start.y; j <= end.y; j++) + { final Plot plot = MainUtil.getPlot(worldname, new PlotId(i, j)); final boolean teleport = ((i == end.x) && (j == end.y)); Claim.claimPlot(plr, plot, teleport, true); } } - if (!MainUtil.mergePlots(worldname, MainUtil.getPlotSelectionIds(start, end), true, true)) { - return false; - } + if (!MainUtil.mergePlots(worldname, MainUtil.getPlotSelectionIds(start, end), true, true)) { return false; } br = true; } } @@ -236,8 +279,10 @@ public class Auto extends SubCommand { return true; } - public PlotId getLastPlot(final String world) { - if ((MainUtil.lastPlot == null) || !MainUtil.lastPlot.containsKey(world)) { + public PlotId getLastPlot(final String world) + { + if ((MainUtil.lastPlot == null) || !MainUtil.lastPlot.containsKey(world)) + { MainUtil.lastPlot.put(world, new PlotId(0, 0)); } return MainUtil.lastPlot.get(world); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/BO3.java b/src/main/java/com/intellectualcrafters/plot/commands/BO3.java index a6524def7..a3710e056 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/BO3.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/BO3.java @@ -21,67 +21,65 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.BO3Handler; -import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "bo3", - aliases = {"bo2"}, - description = "Mark a plot as done", - permission = "plots.bo3", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class BO3 extends SubCommand { +command = "bo3", +aliases = { "bo2" }, +description = "Mark a plot as done", +permission = "plots.bo3", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class BO3 extends SubCommand +{ - public void noArgs(PlotPlayer plr) { + public void noArgs(final 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) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - 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 == null) || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.bo3")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (args.length == 0) { + if (args.length == 0) + { noArgs(plr); return false; } - switch (args[0].toLowerCase()) { + switch (args[0].toLowerCase()) + { case "output": case "save": - case "export": { + case "export": + { return BO3Handler.saveBO3(plr, plot); } case "paste": case "load": case "import": - case "input": { + case "input": + { // TODO NOT IMPLEMENTED YET MainUtil.sendMessage(plr, "NOT IMPLEMENTED YET!!!"); return false; } - default: { + default: + { noArgs(plr); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Buy.java b/src/main/java/com/intellectualcrafters/plot/commands/Buy.java index db6ef3fa9..fd23dda1a 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Buy.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Buy.java @@ -38,83 +38,78 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @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 -) -public class Buy extends SubCommand { +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) { - - if (EconHandler.manager == null) { - return sendMessage(plr, C.ECON_DISABLED); - } + public boolean onCommand(final PlotPlayer plr, final String... args) + { + + if (EconHandler.manager == null) { return sendMessage(plr, C.ECON_DISABLED); } final Location loc = plr.getLocation(); final String world = loc.getWorld(); - if (!PS.get().isPlotWorld(world)) { - return sendMessage(plr, C.NOT_IN_PLOT_WORLD); - } + if (!PS.get().isPlotWorld(world)) { return sendMessage(plr, C.NOT_IN_PLOT_WORLD); } Plot plot; - if (args.length > 0) { - try { + if (args.length > 0) + { + try + { final String[] split = args[0].split(";"); final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); plot = MainUtil.getPlot(world, id); - } catch (final Exception e) { + } + catch (final Exception e) + { return sendMessage(plr, C.NOT_VALID_PLOT_ID); } - } else { + } + else + { plot = MainUtil.getPlot(loc); } - if (plot == null) { - return sendMessage(plr, C.NOT_IN_PLOT); - } + if (plot == null) { return sendMessage(plr, C.NOT_IN_PLOT); } final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(world, plr); - if (currentPlots >= MainUtil.getAllowedPlots(plr)) { - return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); - } - if (!plot.hasOwner()) { - return sendMessage(plr, C.PLOT_UNOWNED); - } - if (PlotHandler.isOwner(plot, plr.getUUID())) { - return sendMessage(plr, C.CANNOT_BUY_OWN); - } + if (currentPlots >= MainUtil.getAllowedPlots(plr)) { return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); } + if (!plot.hasOwner()) { return sendMessage(plr, C.PLOT_UNOWNED); } + if (PlotHandler.isOwner(plot, plr.getUUID())) { return sendMessage(plr, C.CANNOT_BUY_OWN); } final Flag flag = FlagManager.getPlotFlag(plot, "price"); - if (flag == null) { - return sendMessage(plr, C.NOT_FOR_SALE); - } + if (flag == null) { return sendMessage(plr, C.NOT_FOR_SALE); } double initPrice = (double) flag.getValue(); double price = initPrice; final PlotId id = plot.id; final PlotId id2 = MainUtil.getTopPlot(plot).id; final int size = MainUtil.getPlotSelectionIds(id, id2).size(); final PlotWorld plotworld = PS.get().getPlotWorld(world); - if (plotworld.USE_ECONOMY) { + if (plotworld.USE_ECONOMY) + { price += plotworld.PLOT_PRICE * size; initPrice += plotworld.SELL_PRICE * size; } - if ((EconHandler.manager != null) && (price > 0d)) { - if (EconHandler.manager.getMoney(plr) < price) { - return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + price); - } + if ((EconHandler.manager != null) && (price > 0d)) + { + if (EconHandler.manager.getMoney(plr) < price) { return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + price); } EconHandler.manager.withdrawMoney(plr, price); sendMessage(plr, C.REMOVED_BALANCE, price + ""); EconHandler.manager.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), initPrice); final PlotPlayer owner = UUIDHandler.getPlayer(plot.owner); - if (owner != null) { + if (owner != null) + { sendMessage(plr, C.PLOT_SOLD, plot.id + "", plr.getName(), initPrice + ""); } FlagManager.removePlotFlag(plot, "price"); } - Plot top = MainUtil.getTopPlot(plot); - - for (PlotId myId : MainUtil.getPlotSelectionIds(plot.id, top.id)) { - Plot myPlot = MainUtil.getPlot(plot.world, myId); + final Plot top = MainUtil.getTopPlot(plot); + + for (final PlotId myId : MainUtil.getPlotSelectionIds(plot.id, top.id)) + { + final Plot myPlot = MainUtil.getPlot(plot.world, myId); myPlot.owner = plr.getUUID(); DBFunc.setOwner(plot, myPlot.owner); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Chat.java b/src/main/java/com/intellectualcrafters/plot/commands/Chat.java index 8b1a54d8f..e34ab505f 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Chat.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Chat.java @@ -1,23 +1,21 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.PlotWorld; 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.ACTIONS, - requiredType = RequiredType.NONE -) -public class Chat extends SubCommand { +command = "chat", +description = "Toggle plot chat on or off", +usage = "/plot chat [on|off]", +permission = "plots.chat", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Chat extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer player, final String ... args) { - return MainCommand.onCommand(player, "plot", new String[] {"toggle", "chat"}); + public boolean onCommand(final PlotPlayer player, final String... args) + { + return MainCommand.onCommand(player, "plot", new String[] { "toggle", "chat" }); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/src/main/java/com/intellectualcrafters/plot/commands/Claim.java index 2aaddd8d7..e7e963cca 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Claim.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Claim.java @@ -37,53 +37,64 @@ import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; 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.NONE, - permission = "plots.claim", - usage = "/plot claim" -) -public class Claim extends SubCommand { +command = "claim", +aliases = { "c" }, +description = "Claim the current plot you're standing on", +category = CommandCategory.CLAIMING, +requiredType = RequiredType.NONE, +permission = "plots.claim", +usage = "/plot claim") +public class Claim extends SubCommand +{ - public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final boolean auto) { + public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final boolean auto) + { return claimPlot(player, plot, teleport, "", auto); } - public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic, final boolean auto) { - if (plot.hasOwner() || plot.getSettings().isMerged()) { - return false; - } + public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic, final boolean auto) + { + if (plot.hasOwner() || plot.getSettings().isMerged()) { return false; } final boolean result = EventUtil.manager.callClaim(player, plot, false); - if (result) { + if (result) + { MainUtil.createPlot(player.getUUID(), plot); MainUtil.setSign(player.getName(), plot); MainUtil.sendMessage(player, C.CLAIMED); final Location loc = player.getLocation(); - if (teleport) { + if (teleport) + { MainUtil.teleportPlayer(player, loc, plot); } final String world = plot.world; final PlotWorld plotworld = PS.get().getPlotWorld(world); final Plot plot2 = PS.get().getPlot(world, plot.id); - if (plotworld.SCHEMATIC_ON_CLAIM) { + if (plotworld.SCHEMATIC_ON_CLAIM) + { Schematic sch; - if (schematic.equals("")) { + if (schematic.equals("")) + { sch = SchematicHandler.manager.getSchematic(plotworld.SCHEMATIC_FILE); - } else { + } + else + { sch = SchematicHandler.manager.getSchematic(schematic); - if (sch == null) { + if (sch == null) + { sch = SchematicHandler.manager.getSchematic(plotworld.SCHEMATIC_FILE); } } - SchematicHandler.manager.paste(sch, plot2, 0, 0, new RunnableVal() { + SchematicHandler.manager.paste(sch, plot2, 0, 0, new RunnableVal() + { @Override - public void run() { - if (value) { + public void run() + { + if (value) + { MainUtil.sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); } - else { + else + { MainUtil.sendMessage(player, C.SCHEMATIC_PASTE_FAILED); } } @@ -95,43 +106,38 @@ public class Claim extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer plr, final String ... args) { - + public boolean onCommand(final PlotPlayer plr, final String... args) + { + String schematic = ""; - if (args.length >= 1) { + if (args.length >= 1) + { schematic = args[0]; } final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return sendMessage(plr, C.NOT_IN_PLOT); - } + if (plot == null) { return sendMessage(plr, C.NOT_IN_PLOT); } final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(loc.getWorld(), plr); - if (currentPlots >= MainUtil.getAllowedPlots(plr)) { - return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); - } - if (!MainUtil.canClaim(plr, plot)) { - return sendMessage(plr, C.PLOT_IS_CLAIMED); - } + if (currentPlots >= MainUtil.getAllowedPlots(plr)) { return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); } + if (!MainUtil.canClaim(plr, plot)) { return sendMessage(plr, C.PLOT_IS_CLAIMED); } final PlotWorld world = PS.get().getPlotWorld(plot.world); - if ((EconHandler.manager != null) && world.USE_ECONOMY) { + if ((EconHandler.manager != null) && world.USE_ECONOMY) + { final double cost = world.PLOT_PRICE; - if (cost > 0d) { - if (EconHandler.manager.getMoney(plr) < cost) { - return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); - } + if (cost > 0d) + { + if (EconHandler.manager.getMoney(plr) < cost) { return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); } EconHandler.manager.withdrawMoney(plr, cost); sendMessage(plr, C.REMOVED_BALANCE, cost + ""); } } - if (!schematic.equals("")) { - if (world.SCHEMATIC_CLAIM_SPECIFY) { - if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { - return sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); - } - if (!Permissions.hasPermission(plr, "plots.claim." + schematic) && !Permissions.hasPermission(plr, "plots.admin.command.schematic")) { - return sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); - } + if (!schematic.equals("")) + { + if (world.SCHEMATIC_CLAIM_SPECIFY) + { + if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { return sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); } + if (!Permissions.hasPermission(plr, "plots.claim." + schematic) && !Permissions.hasPermission(plr, "plots.admin.command.schematic")) { return sendMessage(plr, + C.NO_SCHEMATIC_PERMISSION, schematic); } } } return claimPlot(plr, plot, false, schematic, false) || sendMessage(plr, C.PLOT_NOT_CLAIMED); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/src/main/java/com/intellectualcrafters/plot/commands/Clear.java index c6466995b..561e5a7bd 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Clear.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Clear.java @@ -38,86 +38,105 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "clear", - description = "Clear a plot", - permission = "plots.clear", - category = CommandCategory.ACTIONS, - usage = "/plot clear [id]" -) -public class Clear extends SubCommand { +command = "clear", +description = "Clear a plot", +permission = "plots.clear", +category = CommandCategory.ACTIONS, +usage = "/plot clear [id]") +public class Clear extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String ... args) { + public boolean onCommand(final PlotPlayer plr, final String... args) + { final Location loc = plr.getLocation(); final Plot plot; - if (args.length == 2) { - PlotId id = PlotId.fromString(args[0]); - if (id == null) { - if (args[1].equalsIgnoreCase("mine")) { - Set plots = PS.get().getPlots(plr); - if (plots.size() == 0) { + if (args.length == 2) + { + final PlotId id = PlotId.fromString(args[0]); + if (id == null) + { + if (args[1].equalsIgnoreCase("mine")) + { + final Set plots = PS.get().getPlots(plr); + if (plots.size() == 0) + { MainUtil.sendMessage(plr, C.NO_PLOTS); return false; } plot = plots.iterator().next(); } - else { + else + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]"); return false; } } - else { + else + { plot = MainUtil.getPlot(loc.getWorld(), id); } } - else { + else + { plot = MainUtil.getPlot(loc); } - if (plot == null) { + if (plot == null) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]"); return sendMessage(plr, C.NOT_IN_PLOT); } -// if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { -// return sendMessage(plr, C.UNLINK_REQUIRED); -// } - if (((plot == null) || !plot.hasOwner() || !plot.isOwner(UUIDHandler.getUUID(plr))) && !Permissions.hasPermission(plr, "plots.admin.command.clear")) { - return sendMessage(plr, C.NO_PLOT_PERMS); - } + // if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { + // return sendMessage(plr, C.UNLINK_REQUIRED); + // } + if (((plot == null) || !plot.hasOwner() || !plot.isOwner(UUIDHandler.getUUID(plr))) && !Permissions.hasPermission(plr, "plots.admin.command.clear")) { return sendMessage(plr, C.NO_PLOT_PERMS); } assert plot != null; - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } - if (FlagManager.getPlotFlag(plot, "done") != null && (!Permissions.hasPermission(plr, "plots.continue") || (Settings.DONE_COUNTS_TOWARDS_LIMIT && MainUtil.getAllowedPlots(plr) >= MainUtil.getPlayerPlotCount(plr)))) { + if ((FlagManager.getPlotFlag(plot, "done") != null) + && (!Permissions.hasPermission(plr, "plots.continue") || (Settings.DONE_COUNTS_TOWARDS_LIMIT && (MainUtil.getAllowedPlots(plr) >= MainUtil.getPlayerPlotCount(plr))))) + { MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE); return false; } - Runnable runnable = new Runnable() { + final Runnable runnable = new Runnable() + { @Override - public void run() { + public void run() + { final long start = System.currentTimeMillis(); - final boolean result = MainUtil.clearAsPlayer(plot, plot.owner == null, new Runnable() { + final boolean result = MainUtil.clearAsPlayer(plot, plot.owner == null, new Runnable() + { @Override - public void run() { + public void run() + { // If the state changes, then mark it as no longer done - if (FlagManager.getPlotFlag(plot, "done" ) != null) { + if (FlagManager.getPlotFlag(plot, "done") != null) + { FlagManager.removePlotFlag(plot, "done"); } - if (FlagManager.getPlotFlag(plot, "analysis") != null) { + if (FlagManager.getPlotFlag(plot, "analysis") != null) + { FlagManager.removePlotFlag(plot, "analysis"); } MainUtil.sendMessage(plr, C.CLEARING_DONE, "" + (System.currentTimeMillis() - start)); } }); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); } } }; - 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.id, runnable); } - else { + else + { TaskManager.runTask(runnable); } return true; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java index 06f1010ec..111689323 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java @@ -53,60 +53,77 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "cluster", - aliases = {"clusters"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - permission = "plots.cluster", - description = "Manage a plot cluster" -) -public class Cluster extends SubCommand { +command = "cluster", +aliases = { "clusters" }, +category = CommandCategory.ACTIONS, +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(final PlotPlayer plr, final String... args) + { + // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome - if (args.length == 0) { + if (args.length == 0) + { // return arguments MainUtil.sendMessage(plr, C.CLUSTER_AVAILABLE_ARGS); return false; } final String sub = args[0].toLowerCase(); - switch (sub) { + switch (sub) + { case "l": - case "list": { - if (!Permissions.hasPermission(plr, "plots.cluster.list")) { + case "list": + { + if (!Permissions.hasPermission(plr, "plots.cluster.list")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.list"); return false; } - if (args.length != 1) { + if (args.length != 1) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster list"); return false; } final HashSet clusters = ClusterManager.getClusters(plr.getLocation().getWorld()); MainUtil.sendMessage(plr, C.CLUSTER_LIST_HEADING, clusters.size() + ""); - for (final PlotCluster cluster : clusters) { + for (final PlotCluster cluster : clusters) + { // Ignore unmanaged clusters final String name = "'" + cluster.getName() + "' : " + cluster.toString(); - if (UUIDHandler.getUUID(plr).equals(cluster.owner)) { + if (UUIDHandler.getUUID(plr).equals(cluster.owner)) + { MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&a" + name); - } else if (cluster.helpers.contains(UUIDHandler.getUUID(plr))) { + } + else if (cluster.helpers.contains(UUIDHandler.getUUID(plr))) + { MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&3" + name); - } else if (cluster.invited.contains(UUIDHandler.getUUID(plr))) { + } + else if (cluster.invited.contains(UUIDHandler.getUUID(plr))) + { MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&9" + name); - } else { + } + else + { MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, cluster.toString()); } } return true; } case "c": - case "create": { - if (!Permissions.hasPermission(plr, "plots.cluster.create")) { + case "create": + { + if (!Permissions.hasPermission(plr, "plots.cluster.create")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create"); return false; } - if (args.length != 4) { + if (args.length != 4) + { final PlotId id = ClusterManager.estimatePlotId(plr.getLocation()); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster create "); MainUtil.sendMessage(plr, C.CLUSTER_CURRENT_PLOTID, "" + id); @@ -115,37 +132,46 @@ public class Cluster extends SubCommand { // check pos1 / pos2 PlotId pos1 = MainUtil.parseId(args[2]); PlotId pos2 = MainUtil.parseId(args[3]); - if ((pos1 == null) || (pos2 == null)) { + if ((pos1 == null) || (pos2 == null)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); return false; } // check if name is taken final String name = args[1]; - for (final PlotCluster cluster : ClusterManager.getClusters(plr.getLocation().getWorld())) { - if (name.equals(cluster.getName())) { + for (final PlotCluster cluster : ClusterManager.getClusters(plr.getLocation().getWorld())) + { + if (name.equals(cluster.getName())) + { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); return false; } } - if ((pos2.x < pos1.x) || (pos2.y < pos1.y) ) { + if ((pos2.x < pos1.x) || (pos2.y < pos1.y)) + { pos1 = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y)); pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y)); } //check if overlap - String world = plr.getLocation().getWorld(); + final String world = plr.getLocation().getWorld(); final PlotClusterId id = new PlotClusterId(pos1, pos2); final HashSet intersects = ClusterManager.getIntersects(world, id); - if ((intersects.size() > 0)) { + if ((intersects.size() > 0)) + { MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, intersects.size() + ""); return false; } // Check if it occupies existing plots - Set plots = MainUtil.getPlotSelectionOwned(world, pos1, pos2); - if (plots.size() > 0) { - if (!Permissions.hasPermission(plr, "plots.cluster.create.other")) { - UUID uuid = plr.getUUID(); - for (Plot plot : plots) { - if (!plot.isOwner(uuid)) { + final Set plots = MainUtil.getPlotSelectionOwned(world, pos1, pos2); + if (plots.size() > 0) + { + if (!Permissions.hasPermission(plr, "plots.cluster.create.other")) + { + final UUID uuid = plr.getUUID(); + for (final Plot plot : plots) + { + if (!plot.isOwner(uuid)) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create.other"); return false; } @@ -155,64 +181,76 @@ public class Cluster extends SubCommand { // Check allowed cluster size final PlotCluster cluster = new PlotCluster(world, pos1, pos2, UUIDHandler.getUUID(plr)); int current; - if (Settings.GLOBAL_LIMIT) { + if (Settings.GLOBAL_LIMIT) + { current = ClusterManager.getPlayerClusterCount(plr); } - else { + else + { current = ClusterManager.getPlayerClusterCount(world, plr); } - int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS); - if (current + cluster.getArea() > allowed) { + final 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; } // Set the generator (if applicable) - PlotWorld plotworld = PS.get().getPlotWorld(world); - if (plotworld == null) { + final PlotWorld plotworld = PS.get().getPlotWorld(world); + if (plotworld == null) + { PS.get().config.createSection("worlds." + world); PS.get().loadWorld(world, PS.get().IMP.getGenerator(world, null)); } - else { + else + { String gen_string = PS.get().config.getString("worlds." + world + "." + "generator.plugin"); - if (gen_string == null) { + if (gen_string == null) + { gen_string = "PlotSquared"; } - PlotGenerator wrapper = PS.get().IMP.getGenerator(world, gen_string); - if (wrapper.isFull()) { + final PlotGenerator wrapper = PS.get().IMP.getGenerator(world, gen_string); + if (wrapper.isFull()) + { wrapper.augment(cluster, plotworld); } - else { + else + { MainUtil.sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringMan.join(SetupUtils.generators.keySet(), ",")); return false; } -// BukkitPlotGenerator generator; -// if (gen_string == null) { -// generator = new HybridGen(world); -// } else { -// ChunkGenerator chunkgen = (ChunkGenerator) PS.get().IMP.getGenerator(world, gen_string).generator; -// if (chunkgen instanceof BukkitPlotGenerator) { -// generator = (BukkitPlotGenerator) chunkgen; -// } -// else { -// MainUtil.sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringMan.join(SetupUtils.generators.keySet(), ",")); -// return false; -// } -// } -// new AugmentedPopulator(world, generator, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2); + // BukkitPlotGenerator generator; + // if (gen_string == null) { + // generator = new HybridGen(world); + // } else { + // ChunkGenerator chunkgen = (ChunkGenerator) PS.get().IMP.getGenerator(world, gen_string).generator; + // if (chunkgen instanceof BukkitPlotGenerator) { + // generator = (BukkitPlotGenerator) chunkgen; + // } + // else { + // MainUtil.sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringMan.join(SetupUtils.generators.keySet(), ",")); + // return false; + // } + // } + // new AugmentedPopulator(world, generator, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2); } // create cluster cluster.settings.setAlias(name); DBFunc.createCluster(world, cluster); - if (!ClusterManager.clusters.containsKey(world)) { + if (!ClusterManager.clusters.containsKey(world)) + { ClusterManager.clusters.put(world, new HashSet()); } ClusterManager.clusters.get(world).add(cluster); // Add any existing plots to the current cluster - for (Plot plot : plots) { - if (plot.hasOwner()) { - Flag flag = new Flag(FlagManager.getFlag("cluster"), cluster); + for (final Plot plot : plots) + { + if (plot.hasOwner()) + { + final Flag flag = new Flag(FlagManager.getFlag("cluster"), cluster); FlagManager.addPlotFlag(plot, flag); - if (!cluster.isAdded(plot.owner)) { + if (!cluster.isAdded(plot.owner)) + { cluster.invited.add(plot.owner); DBFunc.setInvited(world, cluster, plot.owner); } @@ -223,50 +261,65 @@ public class Cluster extends SubCommand { } case "disband": case "del": - case "delete": { - if (!Permissions.hasPermission(plr, "plots.cluster.delete")) { + case "delete": + { + if (!Permissions.hasPermission(plr, "plots.cluster.delete")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.delete"); return false; } - if ((args.length != 1) && (args.length != 2)) { + if ((args.length != 1) && (args.length != 2)) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster delete [name]"); return false; } PlotCluster cluster; - if (args.length == 2) { + if (args.length == 2) + { cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); return false; } - } else { + } + else + { cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } } - if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) { - if (!Permissions.hasPermission(plr, "plots.cluster.delete.other")) { + if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) + { + if (!Permissions.hasPermission(plr, "plots.cluster.delete.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.delete.other"); return false; } } final PlotWorld plotworld = PS.get().getPlotWorld(plr.getLocation().getWorld()); - if (plotworld.TYPE == 2) { + if (plotworld.TYPE == 2) + { final ArrayList toRemove = new ArrayList<>(); - for (final Plot plot : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) { + for (final Plot plot : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) + { final PlotCluster other = ClusterManager.getCluster(plot); - if (cluster.equals(other)) { + if (cluster.equals(other)) + { toRemove.add(plot); } } - for (final Plot plot : toRemove) { + for (final Plot plot : toRemove) + { plot.unclaim(); } } DBFunc.delete(cluster); - if (plotworld.TYPE == 2) { + if (plotworld.TYPE == 2) + { SetupUtils.manager.removePopulator(plr.getLocation().getWorld(), cluster); } ClusterManager.last = null; @@ -276,36 +329,44 @@ public class Cluster extends SubCommand { return true; } case "res": - case "resize": { - if (!Permissions.hasPermission(plr, "plots.cluster.resize")) { + case "resize": + { + if (!Permissions.hasPermission(plr, "plots.cluster.resize")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize"); return false; } - if (args.length != 3) { + if (args.length != 3) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster resize "); return false; } // check pos1 / pos2 PlotId pos1 = MainUtil.parseId(args[1]); PlotId pos2 = MainUtil.parseId(args[2]); - if ((pos1 == null) || (pos2 == null)) { + if ((pos1 == null) || (pos2 == null)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); return false; } - if ((pos2.x < pos1.x) || (pos2.y < pos1.y) ) { + if ((pos2.x < pos1.x) || (pos2.y < pos1.y)) + { pos1 = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y)); pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y)); } // check if in cluster - Location loc = plr.getLocation(); - String world = loc.getWorld(); + final Location loc = plr.getLocation(); + final String world = loc.getWorld(); final PlotCluster cluster = ClusterManager.getCluster(loc); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } - if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { - if (!Permissions.hasPermission(plr, "plots.cluster.resize.other")) { + if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) + { + if (!Permissions.hasPermission(plr, "plots.cluster.resize.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.other"); return false; } @@ -313,46 +374,56 @@ public class Cluster extends SubCommand { //check if overlap final PlotClusterId id = new PlotClusterId(pos1, pos2); final HashSet intersects = ClusterManager.getIntersects(world, id); - if (intersects.size() > 1) { + if (intersects.size() > 1) + { MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, (intersects.size() - 1) + ""); return false; } - HashSet existing = MainUtil.getPlotSelectionOwned(world, cluster.getP1(), cluster.getP2()); - HashSet newplots = MainUtil.getPlotSelectionOwned(world, pos1, pos2); - HashSet removed = ((HashSet) existing.clone()); + final HashSet existing = MainUtil.getPlotSelectionOwned(world, cluster.getP1(), cluster.getP2()); + final HashSet newplots = MainUtil.getPlotSelectionOwned(world, pos1, pos2); + final HashSet removed = ((HashSet) existing.clone()); removed.removeAll(newplots); // Check expand / shrink - if (removed.size() > 0) { - if (!Permissions.hasPermission(plr, "plots.cluster.resize.shrink")) { + if (removed.size() > 0) + { + if (!Permissions.hasPermission(plr, "plots.cluster.resize.shrink")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.shrink"); return false; } } newplots.removeAll(existing); - if (newplots.size() > 0) { - if (!Permissions.hasPermission(plr, "plots.cluster.resize.expand")) { + if (newplots.size() > 0) + { + if (!Permissions.hasPermission(plr, "plots.cluster.resize.expand")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.expand"); return false; } } // Check allowed cluster size int current; - if (Settings.GLOBAL_LIMIT) { + if (Settings.GLOBAL_LIMIT) + { current = ClusterManager.getPlayerClusterCount(plr); } - else { + else + { current = ClusterManager.getPlayerClusterCount(world, plr); } - current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); - int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS); - if (current + cluster.getArea() > allowed) { + current -= cluster.getArea() + (((1 + pos2.x) - pos1.x) * ((1 + pos2.y) - pos1.y)); + final 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; } - for (Plot plot : removed) { + for (final Plot plot : removed) + { FlagManager.removePlotFlag(plot, "cluster"); } - for (Plot plot : newplots) { + for (final Plot plot : newplots) + { FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("cluster"), cluster)); } // resize cluster @@ -362,76 +433,95 @@ public class Cluster extends SubCommand { } case "reg": case "regenerate": - case "regen": { - if (!Permissions.hasPermission(plr, "plots.cluster.delete")) { + case "regen": + { + if (!Permissions.hasPermission(plr, "plots.cluster.delete")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.regen"); return false; } - if ((args.length != 1) && (args.length != 2)) { + if ((args.length != 1) && (args.length != 2)) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster regen [name]"); return false; } PlotCluster cluster; - if (args.length == 2) { + if (args.length == 2) + { cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); return false; } - } else { + } + else + { cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } } - if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) { - if (!Permissions.hasPermission(plr, "plots.cluster.regen.other")) { + if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) + { + if (!Permissions.hasPermission(plr, "plots.cluster.regen.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.regen.other"); return false; } } - long start = System.currentTimeMillis(); + final long start = System.currentTimeMillis(); ClusterManager.regenCluster(cluster); MainUtil.sendMessage(plr, C.CLUSTER_REGENERATED, (System.currentTimeMillis() - start) + ""); return true; } case "add": case "inv": - case "invite": { - if (!Permissions.hasPermission(plr, "plots.cluster.invite")) { + case "invite": + { + if (!Permissions.hasPermission(plr, "plots.cluster.invite")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.invite"); return false; } - if (args.length != 2) { + if (args.length != 2) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster invite "); return false; } // check if in cluster final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } - if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { - if (!Permissions.hasPermission(plr, "plots.cluster.invite.other")) { + if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) + { + if (!Permissions.hasPermission(plr, "plots.cluster.invite.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.invite.other"); return false; } } // check uuid final UUID uuid = UUIDHandler.getUUID(args[1], null); - if (uuid == null) { + if (uuid == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[2]); return false; } - if (!cluster.isAdded(uuid)) { + if (!cluster.isAdded(uuid)) + { // add the user if not added cluster.invited.add(uuid); final String world = plr.getLocation().getWorld(); DBFunc.setInvited(world, cluster, uuid); final PlotPlayer player = UUIDHandler.getPlayer(uuid); - if (player != null) { + if (player != null) + { MainUtil.sendMessage(player, C.CLUSTER_INVITED, cluster.getName()); } } @@ -440,51 +530,63 @@ public class Cluster extends SubCommand { } case "k": case "remove": - case "kick": { - if (!Permissions.hasPermission(plr, "plots.cluster.kick")) { + case "kick": + { + if (!Permissions.hasPermission(plr, "plots.cluster.kick")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.kick"); return false; } - if (args.length != 2) { + if (args.length != 2) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster kick "); return false; } final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } - if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { - if (!Permissions.hasPermission(plr, "plots.cluster.kick.other")) { + if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) + { + if (!Permissions.hasPermission(plr, "plots.cluster.kick.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.kick.other"); return false; } } // check uuid final UUID uuid = UUIDHandler.getUUID(args[1], null); - if (uuid == null) { + if (uuid == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[1]); return false; } // Can't kick if the player is yourself, the owner, or not added to the cluster - if (uuid.equals(UUIDHandler.getUUID(plr)) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) { + if (uuid.equals(UUIDHandler.getUUID(plr)) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) + { MainUtil.sendMessage(plr, C.CANNOT_KICK_PLAYER, cluster.getName()); return false; } - if (cluster.helpers.contains(uuid)) { + if (cluster.helpers.contains(uuid)) + { cluster.helpers.remove(uuid); DBFunc.removeHelper(cluster, uuid); } cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); final PlotPlayer player = UUIDHandler.getPlayer(uuid); - if (player != null) { + if (player != null) + { MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); } - for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { + for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) + { final PlotCluster current = ClusterManager.getCluster(plot); - if ((current != null) && current.equals(cluster)) { - final String world = plr.getLocation().getWorld(); + if ((current != null) && current.equals(cluster)) + { + plr.getLocation().getWorld(); plot.unclaim(); } } @@ -492,49 +594,62 @@ public class Cluster extends SubCommand { return true; } case "quit": - case "leave": { - if (!Permissions.hasPermission(plr, "plots.cluster.leave")) { + case "leave": + { + if (!Permissions.hasPermission(plr, "plots.cluster.leave")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.leave"); return false; } - if ((args.length != 1) && (args.length != 2)) { + if ((args.length != 1) && (args.length != 2)) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster leave [name]"); return false; } PlotCluster cluster; - if (args.length == 2) { + if (args.length == 2) + { cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); return false; } - } else { + } + else + { cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } } final UUID uuid = UUIDHandler.getUUID(plr); - if (!cluster.isAdded(uuid)) { + if (!cluster.isAdded(uuid)) + { MainUtil.sendMessage(plr, C.CLUSTER_NOT_ADDED); return false; } - if (uuid.equals(cluster.owner)) { + if (uuid.equals(cluster.owner)) + { MainUtil.sendMessage(plr, C.CLUSTER_CANNOT_LEAVE); return false; } - if (cluster.helpers.contains(uuid)) { + if (cluster.helpers.contains(uuid)) + { cluster.helpers.remove(uuid); DBFunc.removeHelper(cluster, uuid); } 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))) { + for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) + { final PlotCluster current = ClusterManager.getCluster(plot); - if ((current != null) && current.equals(cluster)) { - final String world = plr.getLocation().getWorld(); + if ((current != null) && current.equals(cluster)) + { + plr.getLocation().getWorld(); plot.unclaim(); } } @@ -542,31 +657,38 @@ public class Cluster extends SubCommand { } case "admin": case "helper": - case "helpers": { - if (!Permissions.hasPermission(plr, "plots.cluster.helpers")) { + case "helpers": + { + if (!Permissions.hasPermission(plr, "plots.cluster.helpers")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.helpers"); return false; } - if (args.length != 3) { + if (args.length != 3) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster helpers "); return false; } final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } final UUID uuid = UUIDHandler.getUUID(args[2], null); - if (uuid == null) { + if (uuid == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[2]); return false; } - if (args[1].toLowerCase().equals("add")) { + if (args[1].toLowerCase().equals("add")) + { cluster.helpers.add(uuid); DBFunc.setHelper(cluster, uuid); return MainUtil.sendMessage(plr, C.CLUSTER_ADDED_HELPER); } - if (args[1].toLowerCase().equals("remove")) { + if (args[1].toLowerCase().equals("remove")) + { cluster.helpers.remove(uuid); DBFunc.removeHelper(cluster, uuid); return MainUtil.sendMessage(plr, C.CLUSTER_REMOVED_HELPER); @@ -576,23 +698,29 @@ public class Cluster extends SubCommand { } case "spawn": case "home": - case "tp": { - if (!Permissions.hasPermission(plr, "plots.cluster.tp")) { + case "tp": + { + if (!Permissions.hasPermission(plr, "plots.cluster.tp")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.tp"); return false; } - if (args.length != 2) { + if (args.length != 2) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster tp "); return false; } final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); return false; } final UUID uuid = UUIDHandler.getUUID(plr); - if (!cluster.isAdded(uuid)) { - if (!Permissions.hasPermission(plr, "plots.cluster.tp.other")) { + if (!cluster.isAdded(uuid)) + { + if (!Permissions.hasPermission(plr, "plots.cluster.tp.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.tp.other"); return false; } @@ -603,32 +731,41 @@ public class Cluster extends SubCommand { case "i": case "info": case "show": - case "information": { - if (!Permissions.hasPermission(plr, "plots.cluster.info")) { + case "information": + { + if (!Permissions.hasPermission(plr, "plots.cluster.info")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.info"); return false; } - if ((args.length != 1) && (args.length != 2)) { + if ((args.length != 1) && (args.length != 2)) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster info [name]"); return false; } PlotCluster cluster; - if (args.length == 2) { + if (args.length == 2) + { cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); return false; } - } else { + } + else + { cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } } final String id = cluster.toString(); String owner = UUIDHandler.getName(cluster.owner); - if (owner == null) { + if (owner == null) + { owner = "unknown"; } final String name = cluster.getName(); @@ -645,22 +782,28 @@ public class Cluster extends SubCommand { } case "sh": case "setspawn": - case "sethome": { - if (!Permissions.hasPermission(plr, "plots.cluster.sethome")) { + case "sethome": + { + if (!Permissions.hasPermission(plr, "plots.cluster.sethome")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.sethome"); return false; } - if ((args.length != 1) && (args.length != 2)) { + if ((args.length != 1) && (args.length != 2)) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster sethome"); return false; } final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation()); - if (cluster == null) { + if (cluster == null) + { MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); return false; } - if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { - if (!Permissions.hasPermission(plr, "plots.cluster.sethome.other")) { + if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) + { + if (!Permissions.hasPermission(plr, "plots.cluster.sethome.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.sethome.other"); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java b/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java index b9cc06fd2..2f324404e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java @@ -1,58 +1,59 @@ -package com.intellectualcrafters.plot.commands; - -/** - * CommandCategory - * - * @author Citymonstret - * @author Empire92 - */ -public enum CommandCategory { - /** - * Claiming Commands - * - * Such as: /plot claim - */ - CLAIMING("Claiming"), - /** - * Teleportation Commands - * - * Such as: /plot visit - */ - TELEPORT("Teleportation"), - /** - * Action Commands - * - * Such as: /plot clear - */ - ACTIONS("Actions"), - /** - * Information Commands - * - * Such as: /plot info - */ - INFO("Information"), - /** - * Debug Commands - * - * Such as: /plot debug - */ - DEBUG("Debug"); - /** - * The category name (Readable) - */ - private final String name; - - /** - * Constructor - * - * @param name readable name - */ - CommandCategory(final String name) { - this.name = name; - } - - @Override - public String toString() { - return this.name; - } -} +package com.intellectualcrafters.plot.commands; + +/** + * CommandCategory + * + */ +public enum CommandCategory +{ + /** + * Claiming Commands + * + * Such as: /plot claim + */ + CLAIMING("Claiming"), + /** + * Teleportation Commands + * + * Such as: /plot visit + */ + TELEPORT("Teleportation"), + /** + * Action Commands + * + * Such as: /plot clear + */ + ACTIONS("Actions"), + /** + * Information Commands + * + * Such as: /plot info + */ + INFO("Information"), + /** + * Debug Commands + * + * Such as: /plot debug + */ + DEBUG("Debug"); + /** + * The category name (Readable) + */ + private final String name; + + /** + * Constructor + * + * @param name readable name + */ + CommandCategory(final String name) + { + this.name = name; + } + + @Override + public String toString() + { + return name; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java b/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java index 32f1901cf..ecd451c75 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java @@ -1,52 +1,54 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.commands; - -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.Permissions; - -/** - * Created by Citymonstret on 2014-08-03. - * - * @author Citymonstret - */ -public class CommandPermission { - /** - * Permission Node - */ - public final String permission; - - /** - * @param permission Command Permission - */ - public CommandPermission(final 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, this.permission); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.commands; + +import com.intellectualcrafters.plot.object.PlotPlayer; +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) + { + 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); + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Comment.java b/src/main/java/com/intellectualcrafters/plot/commands/Comment.java index 7876bdeb1..f7b16cf6b 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Comment.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Comment.java @@ -36,56 +36,66 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "comment", - aliases = {"msg"}, - description = "Comment on a plot", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - permission = "plots.comment" -) -public class Comment extends SubCommand { +command = "comment", +aliases = { "msg" }, +description = "Comment on a plot", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE, +permission = "plots.comment") +public class Comment extends SubCommand +{ @Override - public boolean onCommand(PlotPlayer player, String[] args) { - if (args.length < 2) { - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(),"|")); + public boolean onCommand(final PlotPlayer player, final String[] args) + { + if (args.length < 2) + { + sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } - CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); - if (inbox == null) { - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(),"|")); + final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); + if (inbox == null) + { + sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } Plot plot; - Location loc = player.getLocation(); - PlotId id = PlotId.fromString(args[1]); + final Location loc = player.getLocation(); + final PlotId id = PlotId.fromString(args[1]); int index; - if (id != null) { - if (args.length < 4) { - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(),"|")); + if (id != null) + { + if (args.length < 4) + { + sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } index = 2; plot = MainUtil.getPlot(loc.getWorld(), id); } - else { + else + { index = 1; plot = MainUtil.getPlot(loc); } - if (!inbox.canWrite(plot, player)) { + if (!inbox.canWrite(plot, player)) + { sendMessage(player, C.NO_PERM_INBOX, ""); return false; } - 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) { + 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); + if (!result) + { sendMessage(player, C.NO_PLOT_INBOX, ""); - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(),"|")); + sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } - for (PlotPlayer pp : UUIDHandler.getPlayers().values()) { - if (pp.getAttribute("chatspy")) { + for (final PlotPlayer pp : UUIDHandler.getPlayers().values()) + { + if (pp.getAttribute("chatspy")) + { MainUtil.sendMessage(pp, "/plot comment " + StringMan.join(args, " ")); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/src/main/java/com/intellectualcrafters/plot/commands/Condense.java index 4dd63e88d..f57c54c96 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Condense.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Condense.java @@ -36,42 +36,51 @@ import com.intellectualcrafters.plot.util.MathMan; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "condense", - permission = "plots.admin", - description = "Condense a plotworld", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE -) -public class Condense extends SubCommand { +command = "condense", +permission = "plots.admin", +description = "Condense a plotworld", +category = CommandCategory.DEBUG, +requiredType = RequiredType.CONSOLE) +public class Condense extends SubCommand +{ public static boolean TASK = false; @Override - public boolean onCommand(final PlotPlayer plr, String ... args) { - if ((args.length != 2) && (args.length != 3)) { + public boolean onCommand(final PlotPlayer plr, final String... args) + { + if ((args.length != 2) && (args.length != 3)) + { MainUtil.sendMessage(plr, "/plot condense [radius]"); return false; } final String worldname = args[0]; - if (!BlockManager.manager.isWorld(worldname) || !PS.get().isPlotWorld(worldname)) { + if (!BlockManager.manager.isWorld(worldname) || !PS.get().isPlotWorld(worldname)) + { MainUtil.sendMessage(plr, "INVALID WORLD"); return false; } - switch (args[1].toLowerCase()) { - case "start": { - if (args.length == 2) { + switch (args[1].toLowerCase()) + { + case "start": + { + if (args.length == 2) + { MainUtil.sendMessage(plr, "/plot condense " + worldname + " start "); return false; } - if (TASK) { + if (TASK) + { MainUtil.sendMessage(plr, "TASK ALREADY STARTED"); return false; } - if (args.length == 2) { + if (args.length == 2) + { MainUtil.sendMessage(plr, "/plot condense " + worldname + " start "); return false; } - if (!MathMan.isInteger(args[2])) { + if (!MathMan.isInteger(args[2])) + { MainUtil.sendMessage(plr, "INVALID RADIUS"); return false; } @@ -79,61 +88,76 @@ public class Condense extends SubCommand { final Collection plots = PS.get().getPlotsInWorld(worldname); final int size = plots.size(); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); - if (radius < minimum_radius) { + if (radius < minimum_radius) + { MainUtil.sendMessage(plr, "RADIUS TOO SMALL"); return false; } final List to_move = new ArrayList<>(getPlots(plots, radius)); final List free = new ArrayList<>(); PlotId start = new PlotId(0, 0); - while ((start.x <= minimum_radius) && (start.y <= minimum_radius)) { + while ((start.x <= minimum_radius) && (start.y <= minimum_radius)) + { final Plot plot = MainUtil.getPlot(worldname, start); - if (!plot.hasOwner()) { + if (!plot.hasOwner()) + { free.add(plot.id); } start = Auto.getNextPlot(start, 1); } - if (free.size() == 0 || to_move.size() == 0) { + if ((free.size() == 0) || (to_move.size() == 0)) + { MainUtil.sendMessage(plr, "NO FREE PLOTS FOUND"); return false; } - MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), new Runnable() { + MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), new Runnable() + { @Override - public void run() { - if (!TASK) { + public void run() + { + if (!TASK) + { MainUtil.sendMessage(plr, "CONDENSE TASK CANCELLED"); return; } to_move.remove(0); free.remove(0); int index = 0; - for (final PlotId id : to_move) { + for (final PlotId id : to_move) + { final Plot plot = MainUtil.getPlot(worldname, id); - if (plot.hasOwner()) { + if (plot.hasOwner()) + { break; } index++; } - for (int i = 0; i < index; i++) { + for (int i = 0; i < index; i++) + { to_move.remove(0); } index = 0; - for (final PlotId id : free) { + for (final PlotId id : free) + { final Plot plot = MainUtil.getPlot(worldname, id); - if (!plot.hasOwner()) { + if (!plot.hasOwner()) + { break; } index++; } - for (int i = 0; i < index; i++) { + for (int i = 0; i < index; i++) + { free.remove(0); } - if (to_move.size() == 0) { + if (to_move.size() == 0) + { MainUtil.sendMessage(plr, "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); TASK = false; return; } - if (free.size() == 0) { + if (free.size() == 0) + { MainUtil.sendMessage(plr, "TASK FAILED. NO FREE PLOTS FOUND!"); TASK = false; return; @@ -146,8 +170,10 @@ public class Condense extends SubCommand { MainUtil.sendMessage(plr, "TASK STARTED..."); return true; } - case "stop": { - if (!TASK) { + case "stop": + { + if (!TASK) + { MainUtil.sendMessage(plr, "TASK ALREADY STOPPED"); return false; } @@ -155,12 +181,15 @@ public class Condense extends SubCommand { MainUtil.sendMessage(plr, "TASK STOPPED"); return true; } - case "info": { - if (args.length == 2) { + case "info": + { + if (args.length == 2) + { MainUtil.sendMessage(plr, "/plot condense " + worldname + " info "); return false; } - if (!MathMan.isInteger(args[2])) { + if (!MathMan.isInteger(args[2])) + { MainUtil.sendMessage(plr, "INVALID RADIUS"); return false; } @@ -168,7 +197,8 @@ public class Condense extends SubCommand { final Collection plots = PS.get().getPlotsInWorld(worldname); final int size = plots.size(); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); - if (radius < minimum_radius) { + if (radius < minimum_radius) + { MainUtil.sendMessage(plr, "RADIUS TOO SMALL"); return false; } @@ -189,10 +219,13 @@ public class Condense extends SubCommand { return false; } - public Set getPlots(final Collection plots, final int radius) { + public Set getPlots(final Collection plots, final int radius) + { final HashSet outside = new HashSet<>(); - for (final Plot plot : plots) { - if ((plot.id.x > radius) || (plot.id.x < -radius) || (plot.id.y > radius) || (plot.id.y < -radius)) { + for (final Plot plot : plots) + { + if ((plot.id.x > radius) || (plot.id.x < -radius) || (plot.id.y > radius) || (plot.id.y < -radius)) + { outside.add(plot.id); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java b/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java index 46f523ba9..8d409a90e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java @@ -20,7 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.CmdInstance; import com.intellectualcrafters.plot.object.PlotPlayer; @@ -30,26 +29,29 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "confirm", - permission = "plots.use", - description = "Confirm an action", - category = CommandCategory.ACTIONS -) -public class Confirm extends SubCommand { +command = "confirm", +permission = "plots.use", +description = "Confirm an action", +category = CommandCategory.ACTIONS) +public class Confirm extends SubCommand +{ - @Override - public boolean onCommand(final PlotPlayer plr, final String ... args) { - CmdInstance command = CmdConfirm.getPending(plr); - if (command == null) { - MainUtil.sendMessage(plr, C.FAILED_CONFIRM); - return false; - } - CmdConfirm.removePending(plr); - if (System.currentTimeMillis() - command.timestamp > 20000) { - MainUtil.sendMessage(plr, C.FAILED_CONFIRM); - return false; - } - TaskManager.runTask(command.command); - return true; + @Override + public boolean onCommand(final PlotPlayer plr, final String... args) + { + final CmdInstance command = CmdConfirm.getPending(plr); + if (command == null) + { + MainUtil.sendMessage(plr, C.FAILED_CONFIRM); + return false; + } + CmdConfirm.removePending(plr); + if ((System.currentTimeMillis() - command.timestamp) > 20000) + { + MainUtil.sendMessage(plr, C.FAILED_CONFIRM); + return false; + } + TaskManager.runTask(command.command); + return true; } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Continue.java b/src/main/java/com/intellectualcrafters/plot/commands/Continue.java index 51154579a..61fc281ee 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Continue.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Continue.java @@ -22,49 +22,46 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "continue", - description = "Continue a plot that was previously marked as done", - permission = "plots.continue", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Continue extends SubCommand { +command = "continue", +description = "Continue a plot that was previously marked as done", +permission = "plots.continue", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Continue extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null || !plot.hasOwner()) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.continue")) { + if ((plot == null) || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.continue")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (!plot.getSettings().flags.containsKey("done")) { + if (!plot.getSettings().flags.containsKey("done")) + { MainUtil.sendMessage(plr, C.DONE_NOT_DONE); return false; } - if (Settings.DONE_COUNTS_TOWARDS_LIMIT && MainUtil.getAllowedPlots(plr) >= MainUtil.getPlayerPlotCount(plr)) { + if (Settings.DONE_COUNTS_TOWARDS_LIMIT && (MainUtil.getAllowedPlots(plr) >= MainUtil.getPlayerPlotCount(plr))) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.admin.command.continue"); return false; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/src/main/java/com/intellectualcrafters/plot/commands/Copy.java index b9781f14e..76314bf6b 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Copy.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Copy.java @@ -31,53 +31,61 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "copy", - permission = "plots.copy", - aliases = {"copypaste"}, - category = CommandCategory.ACTIONS, - description = "Copy a plot", - usage = "/plot copy ", - requiredType = RequiredType.NONE -) -public class Copy extends SubCommand { +command = "copy", +permission = "plots.copy", +aliases = { "copypaste" }, +category = CommandCategory.ACTIONS, +description = "Copy a plot", +usage = "/plot copy ", +requiredType = RequiredType.NONE) +public class Copy extends SubCommand +{ - public Copy() { + public Copy() + { requiredArguments = new Argument[] { - Argument.PlotID + Argument.PlotID }; } @Override - public boolean onCommand(final PlotPlayer plr, final String ... args) { + public boolean onCommand(final PlotPlayer plr, final String... args) + { final Location loc = plr.getLocation(); final Plot plot1 = MainUtil.getPlot(loc); - if (plot1 == null) { - return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot1.isAdded(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) { + if (plot1 == null) { return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot1.isAdded(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } final String world = loc.getWorld(); final PlotId plot2 = MainUtil.parseId(args[0]); - if ((plot2 == null)) { + if ((plot2 == null)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy "); return false; } - if (plot1.id.equals(plot2)) { + if (plot1.id.equals(plot2)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy "); return false; } - if (MainUtil.copy(world, plot1.id, plot2, new Runnable() { + if (MainUtil.copy(world, plot1.id, plot2, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(plr, C.COPY_SUCCESS); } - })) { + })) + { return true; - } else { + } + else + { MainUtil.sendMessage(plr, C.REQUIRES_UNOWNED); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java b/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java index 1f0937750..a3c5ea544 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java @@ -31,26 +31,23 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "createroadschematic", - aliases = {"crs"}, - category = CommandCategory.DEBUG, - 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 { +command = "createroadschematic", +aliases = { "crs" }, +category = CommandCategory.DEBUG, +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) { + public boolean onCommand(final PlotPlayer player, final String... args) + { final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return sendMessage(player, C.NOT_IN_PLOT); - } - if (!(PS.get().getPlotWorld(loc.getWorld()) instanceof HybridPlotWorld)) { - return sendMessage(player, C.NOT_IN_PLOT_WORLD); - } + if (plot == null) { return sendMessage(player, C.NOT_IN_PLOT); } + if (!(PS.get().getPlotWorld(loc.getWorld()) instanceof HybridPlotWorld)) { return sendMessage(player, C.NOT_IN_PLOT_WORLD); } HybridUtils.manager.setupRoadSchematic(plot); MainUtil.sendMessage(player, "&6Saved new road schematic. To test the road, fly to a few other plots and use /plot debugroadregen"); return true; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/src/main/java/com/intellectualcrafters/plot/commands/Database.java index 0a8109081..b3b669038 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Database.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Database.java @@ -3,12 +3,10 @@ package com.intellectualcrafters.plot.commands; import java.io.File; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.MySQL; import com.intellectualcrafters.plot.database.SQLManager; @@ -21,35 +19,45 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "database", - aliases = {"convert"}, - category = CommandCategory.DEBUG, - permission = "plots.database", - description = "Convert/Backup Storage", - requiredType = RequiredType.CONSOLE, - usage = "/plots database [world] " - -) -public class Database extends SubCommand { +command = "database", +aliases = { "convert" }, +category = CommandCategory.DEBUG, +permission = "plots.database", +description = "Convert/Backup Storage", +requiredType = RequiredType.CONSOLE, +usage = "/plots database [world] " - public static void insertPlots(final SQLManager manager, final ArrayList plots, final PlotPlayer player) { - TaskManager.runTaskAsync(new Runnable() { +) +public class Database extends SubCommand +{ + + public static void insertPlots(final SQLManager manager, final ArrayList plots, final PlotPlayer player) + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - try { + public void run() + { + try + { final ArrayList ps = new ArrayList<>(); - for (final Plot p : plots) { + for (final Plot p : plots) + { ps.add(p); } MainUtil.sendMessage(player, "&6Starting..."); - manager.createPlotsAndData(ps, new Runnable() { + manager.createPlotsAndData(ps, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(player, "&6Database conversion finished!"); manager.close(); } }); - } catch (final Exception e) { + } + catch (final Exception e) + { MainUtil.sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); e.printStackTrace(); } @@ -58,42 +66,54 @@ public class Database extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer player, String[] args) { - if (args.length < 1) { + public boolean onCommand(final PlotPlayer player, String[] args) + { + if (args.length < 1) + { MainUtil.sendMessage(player, "/plot database [world] "); return false; } ArrayList plots; - if (PS.get().isPlotWorld(args[0])) { + if (PS.get().isPlotWorld(args[0])) + { plots = PS.get().sortPlotsByTemp(PS.get().getPlotsInWorld(args[0])); args = Arrays.copyOfRange(args, 1, args.length); } - else { + else + { plots = PS.get().sortPlotsByTemp(PS.get().getPlotsRaw()); } - if (args.length < 1) { + if (args.length < 1) + { MainUtil.sendMessage(player, "/plot database [world] "); MainUtil.sendMessage(player, "[arg] indicates an optional argument"); return false; } - try { + try + { com.intellectualcrafters.plot.database.Database implementation; String prefix = ""; - switch (args[0].toLowerCase()) { - case "import": { - if (args.length < 2) { + switch (args[0].toLowerCase()) + { + case "import": + { + if (args.length < 2) + { MainUtil.sendMessage(player, "/plot database import [sqlite file] [prefix]"); return false; } MainUtil.sendMessage(player, "&6Starting..."); implementation = new SQLite(PS.get().IMP.getDirectory() + File.separator + args[1] + ".db"); - SQLManager manager = new SQLManager(implementation, (args.length == 3) ? args[2] : "", true); - ConcurrentHashMap> map = manager.getPlots(); + final SQLManager manager = new SQLManager(implementation, (args.length == 3) ? args[2] : "", true); + final ConcurrentHashMap> map = manager.getPlots(); plots = new ArrayList(); - for (Entry> entry : map.entrySet()) { - for (Entry entry2 : entry.getValue().entrySet()) { - Plot plot = entry2.getValue(); - if (PS.get().getPlot(plot.world, plot.id) != null) { + for (final Entry> entry : map.entrySet()) + { + for (final Entry entry2 : entry.getValue().entrySet()) + { + final Plot plot = entry2.getValue(); + if (PS.get().getPlot(plot.world, plot.id) != null) + { MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp); continue; } @@ -101,43 +121,44 @@ public class Database extends SubCommand { plots.add(entry2.getValue()); } } - DBFunc.createPlotsAndData(plots, new Runnable() { + DBFunc.createPlotsAndData(plots, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(player, "&6Database conversion finished!"); } }); return true; } case "mysql": - if (args.length < 6) { - return MainUtil.sendMessage(player, "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); - } + 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]; - if (args.length > 6) { + if (args.length > 6) + { prefix = args[6]; } implementation = new MySQL(host, port, database, username, password); break; case "sqlite": - if (args.length < 2) { - return MainUtil.sendMessage(player, "/plot database sqlite [file]"); - } + if (args.length < 2) { return MainUtil.sendMessage(player, "/plot database sqlite [file]"); } implementation = new SQLite(PS.get().IMP.getDirectory() + File.separator + args[1] + ".db"); break; default: return MainUtil.sendMessage(player, "/plot database [sqlite/mysql]"); } - try { + try + { final SQLManager manager = new SQLManager(implementation, prefix, true); insertPlots(manager, plots, player); return true; } - catch (Exception e) { + catch (final Exception e) + { MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info"); MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); @@ -146,7 +167,8 @@ public class Database extends SubCommand { return false; } } - catch (Exception e) { + catch (final Exception e) + { MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info"); MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/src/main/java/com/intellectualcrafters/plot/commands/Debug.java index bb9de7836..7d7b107c9 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Debug.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Debug.java @@ -28,19 +28,22 @@ 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" -) -public class Debug extends SubCommand { +command = "debug", +category = CommandCategory.DEBUG, +description = "Show debug information", +usage = "/plot debug [msg]", +permission = "plots.admin") +public class Debug extends SubCommand +{ @Override - public boolean onCommand(PlotPlayer plr, String[] args) { - if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) + { final StringBuilder msg = new StringBuilder(); - for (final C c : C.values()) { + for (final C c : C.values()) + { msg.append(c.s()).append("\n"); } MainUtil.sendMessage(plr, msg.toString()); @@ -56,7 +59,8 @@ public class Debug extends SubCommand { } { final StringBuilder worlds = new StringBuilder(""); - for (final String world : PS.get().getPlotWorlds()) { + for (final String world : PS.get().getPlotWorlds()) + { worlds.append(world).append(" "); } information.append(header); @@ -77,11 +81,13 @@ public class Debug extends SubCommand { return true; } - private String getSection(final String line, final String val) { + private String getSection(final String line, final String val) + { return line.replaceAll("%val%", val) + "\n"; } - private String getLine(final String line, final String var, final Object val) { + private String getLine(final String line, final String var, final Object val) + { return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java index 07138829d..ce2738892 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java @@ -9,24 +9,28 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - 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 { +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) { - - if (unsafeAllowed.contains(plr.getUUID())) { + public boolean onCommand(final PlotPlayer plr, final String... args) + { + + if (unsafeAllowed.contains(plr.getUUID())) + { unsafeAllowed.remove(plr.getUUID()); sendMessage(plr, C.DEBUGALLOWUNSAFE_OFF); - } else { + } + else + { unsafeAllowed.add(plr.getUUID()); sendMessage(plr, C.DEBUGALLOWUNSAFE_ON); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java index 16b16c34e..3527ef53e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java @@ -43,25 +43,29 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "debugclaimtest", - description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot sighs. Execution time may vary", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE, - permission = "plots.debugclaimtest" -) -public class DebugClaimTest extends SubCommand { +command = "debugclaimtest", +description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot sighs. Execution time may vary", +category = CommandCategory.DEBUG, +requiredType = RequiredType.CONSOLE, +permission = "plots.debugclaimtest") +public class DebugClaimTest extends SubCommand +{ - public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport) { + public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport) + { return claimPlot(player, plot, teleport, ""); } - public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic) { + public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic) + { final boolean result = EventUtil.manager.callClaim(player, plot, false); - if (result) { + if (result) + { MainUtil.createPlot(player.getUUID(), plot); MainUtil.setSign(player.getName(), plot); MainUtil.sendMessage(player, C.CLAIMED); - if (teleport) { + if (teleport) + { MainUtil.teleportPlayer(player, player.getLocation(), plot); } } @@ -69,81 +73,103 @@ public class DebugClaimTest extends SubCommand { } @Override - public boolean onCommand(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}"); - } + public boolean onCommand(final PlotPlayer plr, final 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}"); } final String world = args[0]; - if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) { - return !MainUtil.sendMessage(null, "&cInvalid plot world!"); - } + if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) { return !MainUtil.sendMessage(null, "&cInvalid plot world!"); } PlotId min, max; - try { - final String[] split1 = args[1].split(";"); - final String[] split2 = args[2].split(";"); + try + { + args[1].split(";"); + args[2].split(";"); min = PlotId.fromString(args[1]); max = PlotId.fromString(args[2]); - } catch (final Exception e) { - return !MainUtil.sendMessage(null, "&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."); + } + catch (final Exception e) + { + return !MainUtil.sendMessage(null, + "&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(null, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while..."); MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); final PlotManager manager = PS.get().getPlotManager(world); final PlotWorld plotworld = PS.get().getPlotWorld(world); final ArrayList plots = new ArrayList<>(); - for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) { + for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) + { final Plot plot = MainUtil.getPlot(world, id); - if (PS.get().getPlot(world, plot.id) != null) { + if (PS.get().getPlot(world, plot.id) != null) + { MainUtil.sendMessage(null, " - &cDB Already contains: " + plot.id); continue; } final Location loc = manager.getSignLoc(plotworld, plot); final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); final boolean result = ChunkManager.manager.loadChunk(world, chunk, false); - if (!result) { + if (!result) + { continue; } final String[] lines = BlockManager.manager.getSign(loc); - if (lines != null) { + if (lines != null) + { String line = lines[2]; - if ((line != null) && (line.length() > 2)) { + if ((line != null) && (line.length() > 2)) + { line = line.substring(2); final BiMap map = UUIDHandler.getUuidMap(); UUID uuid = (map.get(new StringWrapper(line))); - if (uuid == null) { - for (final StringWrapper string : map.keySet()) { - if (string.value.toLowerCase().startsWith(line.toLowerCase())) { + if (uuid == null) + { + for (final StringWrapper string : map.keySet()) + { + if (string.value.toLowerCase().startsWith(line.toLowerCase())) + { uuid = map.get(string); break; } } } - if (uuid == null) { + if (uuid == null) + { uuid = UUIDHandler.getUUID(line, null); } - if (uuid != null) { + if (uuid != null) + { MainUtil.sendMessage(null, " - &aFound plot: " + plot.id + " : " + line); plot.owner = uuid; plots.add(plot); - } else { + } + else + { MainUtil.sendMessage(null, " - &cInvalid playername: " + plot.id + " : " + line); } } } } - if (plots.size() > 0) { + if (plots.size() > 0) + { MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!"); - DBFunc.createPlotsAndData(plots, new Runnable() { + DBFunc.createPlotsAndData(plots, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(null, "&6Database update finished!"); } }); - for (final Plot plot : plots) { + for (final Plot plot : plots) + { PS.get().updatePlot(plot); } MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); - } else { + } + else + { MainUtil.sendMessage(null, "No plots were found for the given search."); } return true; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java index 5c1410c8f..f1b4df53d 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java @@ -33,36 +33,34 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "debugclear", - aliases = {"fastclear"}, - description = "Clear a plot using a fast experiment algorithm", - category = CommandCategory.DEBUG -) -public class DebugClear extends SubCommand { +command = "debugclear", +aliases = { "fastclear" }, +description = "Clear a plot using a fast experiment algorithm", +category = CommandCategory.DEBUG) +public class DebugClear extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if ((plot == null) || !(PS.get().getPlotWorld(loc.getWorld()) instanceof SquarePlotWorld)) { - return sendMessage(plr, C.NOT_IN_PLOT); - } - if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { - return sendMessage(plr, C.UNLINK_REQUIRED); - } - if ((!plot.hasOwner() || !plot.isOwner(UUIDHandler.getUUID(plr))) && !Permissions.hasPermission(plr, "plots.admin.command.debugclear")) { - return sendMessage(plr, C.NO_PLOT_PERMS); - } + if ((plot == null) || !(PS.get().getPlotWorld(loc.getWorld()) instanceof SquarePlotWorld)) { return sendMessage(plr, C.NOT_IN_PLOT); } + if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { return sendMessage(plr, C.UNLINK_REQUIRED); } + if ((!plot.hasOwner() || !plot.isOwner(UUIDHandler.getUUID(plr))) && !Permissions.hasPermission(plr, "plots.admin.command.debugclear")) { return sendMessage(plr, C.NO_PLOT_PERMS); } final Location pos1 = MainUtil.getPlotBottomLoc(loc.getWorld(), plot.id).add(1, 0, 1); final Location pos2 = MainUtil.getPlotTopLoc(loc.getWorld(), plot.id); - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); - ChunkManager.manager.regenerateRegion(pos1, pos2, new Runnable() { + ChunkManager.manager.regenerateRegion(pos1, pos2, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); MainUtil.sendMessage(plr, "&aDone!"); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java index ae99b81d2..b2a6af5b1 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java @@ -65,7 +65,6 @@ import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.ExpireManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.StringMan; @@ -73,61 +72,67 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.bukkit.util.BukkitHybridUtils; import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandCaller; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "debugexec", - permission = "plots.admin", - description = "Mutli-purpose debug command", - aliases = {"exec"}, - category = CommandCategory.DEBUG -) -public class DebugExec extends SubCommand { +command = "debugexec", +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 { - File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js"); - if (file.exists()) { + + public DebugExec() + { + try + { + final File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js"); + if (file.exists()) + { init(); - 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); + final 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); } - } catch (Exception e) { } + catch (final Exception e) + {} } - - public ScriptEngine getEngine() { + + public ScriptEngine getEngine() + { return engine; } - - public Bindings getScope() { + + public Bindings getScope() + { return scope; } - - public void init() { - if (engine != null) { - return; - } + + public void init() + { + if (engine != null) { return; } engine = (new ScriptEngineManager(null)).getEngineByName("nashorn"); - if (engine == null) { + if (engine == null) + { engine = (new ScriptEngineManager(null)).getEngineByName("JavaScript"); } - ScriptContext context = new SimpleScriptContext(); + final ScriptContext context = new SimpleScriptContext(); 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()); - + // Classes scope.put("Location", Location.class); scope.put("PlotBlock", PlotBlock.class); @@ -135,7 +140,7 @@ public class DebugExec extends SubCommand { scope.put("PlotId", PlotId.class); scope.put("Runnable", Runnable.class); scope.put("RunnableVal", RunnableVal.class); - + // Instances scope.put("PS", PS.get()); scope.put("TaskManager", PS.get().TASK); @@ -152,112 +157,143 @@ public class DebugExec extends SubCommand { scope.put("HybridUtils", HybridUtils.manager); scope.put("IMP", PS.get().IMP); scope.put("MainCommand", MainCommand.getInstance()); - + // enums - for (Enum value : C.values()) { + for (final Enum value : C.values()) + { scope.put("C_" + value.name(), value); } } - + @Override - public boolean onCommand(final PlotPlayer player, String... args) { + public boolean onCommand(final PlotPlayer player, final String... args) + { final List allowed_params = Arrays.asList("calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "show-expired", "update-expired", "seen", "trim-check"); - if (args.length > 0) { + if (args.length > 0) + { final String arg = args[0].toLowerCase(); String script; boolean async = false; - switch (arg) { - case "analyze": { - Plot plot = MainUtil.getPlot(player.getLocation()); - if (plot == null) { + switch (arg) + { + case "analyze": + { + final Plot plot = MainUtil.getPlot(player.getLocation()); + if (plot == null) + { MainUtil.sendMessage(player, C.NOT_IN_PLOT); return false; } - PlotAnalysis analysis = plot.getComplexity(); - if (analysis != null) { - int complexity = analysis.getComplexity(); + final PlotAnalysis analysis = plot.getComplexity(); + if (analysis != null) + { + final int complexity = analysis.getComplexity(); MainUtil.sendMessage(player, "Changes: " + analysis.changes); MainUtil.sendMessage(player, "Complexity: " + complexity); return true; } MainUtil.sendMessage(player, "$1Starting task..."); - HybridUtils.manager.analyzePlot(plot, new RunnableVal() { + HybridUtils.manager.analyzePlot(plot, new RunnableVal() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(player, "$1Done: $2use $3/plot debugexec analyze$2 for more information"); } }); return true; } - case "calibrate-analysis": { - if (args.length != 2) { + 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)"); return false; } double threshold; - try { + try + { threshold = Integer.parseInt(args[1]) / 100d; } - catch (NumberFormatException e) { + catch (final 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; } - PlotAnalysis.calcOptimalModifiers(new Runnable() { + PlotAnalysis.calcOptimalModifiers(new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(player, "$1Thank you for calibrating PlotSquared plot expiry"); } }, threshold); return true; } - case "stop-expire": { - if (ExpireManager.task != -1) { + case "stop-expire": + { + if (ExpireManager.task != -1) + { PS.get().TASK.cancelTask(ExpireManager.task); - } else { + } + else + { return MainUtil.sendMessage(player, "Task already halted"); } ExpireManager.task = -1; return MainUtil.sendMessage(player, "Cancelled task."); } - case "remove-flag": { - if (args.length != 2) { + case "remove-flag": + { + if (args.length != 2) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag "); return false; } - String flag = args[1]; - for (Plot plot : PS.get().getPlots()) { - if (FlagManager.getPlotFlag(plot, flag) != null) { + final String flag = args[1]; + for (final Plot plot : PS.get().getPlots()) + { + if (FlagManager.getPlotFlag(plot, flag) != null) + { FlagManager.removePlotFlag(plot, flag); } } - return MainUtil.sendMessage(player, "Cleared flag: " + flag); + return MainUtil.sendMessage(player, "Cleared flag: " + flag); } - case "start-rgar": { - if (args.length != 2) { + case "start-rgar": + { + if (args.length != 2) + { MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar "); return false; } boolean result; - if (!PS.get().isPlotWorld(args[1])) { + if (!PS.get().isPlotWorld(args[1])) + { MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); return false; } - if (BukkitHybridUtils.regions != null) { - result = ((BukkitHybridUtils)(HybridUtils.manager)).scheduleRoadUpdate(args[1], BukkitHybridUtils.regions, 0); + if (HybridUtils.regions != null) + { + result = ((BukkitHybridUtils) (HybridUtils.manager)).scheduleRoadUpdate(args[1], HybridUtils.regions, 0); } - else { + else + { result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0); } - if (!result) { + if (!result) + { MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } return true; } - case "stop-rgar": { - if (!HybridUtils.UPDATE) { + case "stop-rgar": + { + if (!HybridUtils.UPDATE) + { MainUtil.sendMessage(player, "&cTASK NOT RUNNING!"); return false; } @@ -265,55 +301,53 @@ public class DebugExec extends SubCommand { MainUtil.sendMessage(player, "&cCancelling task... (please wait)"); return true; } - case "start-expire": { - if (ExpireManager.task == -1) { + case "start-expire": + { + if (ExpireManager.task == -1) + { ExpireManager.runTask(); - } else { + } + else + { return MainUtil.sendMessage(player, "Plot expiry task already started"); } return MainUtil.sendMessage(player, "Started plot expiry task"); } - case "update-expired": { - if (args.length > 1) { + case "update-expired": + { + if (args.length > 1) + { final String world = args[1]; - if (!BlockManager.manager.isWorld(world)) { - return MainUtil.sendMessage(player, "Invalid world: " + args[1]); - } + if (!BlockManager.manager.isWorld(world)) { return MainUtil.sendMessage(player, "Invalid world: " + args[1]); } MainUtil.sendMessage(player, "Updating expired plot list"); ExpireManager.updateExpired(args[1]); return true; } return MainUtil.sendMessage(player, "Use /plot debugexec update-expired "); } - case "show-expired": { - if (args.length > 1) { + case "show-expired": + { + if (args.length > 1) + { final String world = args[1]; - if (!BlockManager.manager.isWorld(world)) { - return MainUtil.sendMessage(player, "Invalid world: " + args[1]); - } - if (!ExpireManager.expiredPlots.containsKey(args[1])) { - return MainUtil.sendMessage(player, "No task for world: " + args[1]); - } + if (!BlockManager.manager.isWorld(world)) { return MainUtil.sendMessage(player, "Invalid world: " + args[1]); } + if (!ExpireManager.expiredPlots.containsKey(args[1])) { return MainUtil.sendMessage(player, "No task for world: " + args[1]); } MainUtil.sendMessage(player, "Expired plots (" + ExpireManager.expiredPlots.get(args[1]).size() + "):"); - for (final Plot plot : ExpireManager.expiredPlots.get(args[1])) { + for (final Plot plot : ExpireManager.expiredPlots.get(args[1])) + { MainUtil.sendMessage(player, " - " + plot.world + ";" + plot.id.x + ";" + plot.id.y + ";" + UUIDHandler.getName(plot.owner) + " : " + ExpireManager.dates.get(plot.owner)); } return true; } return MainUtil.sendMessage(player, "Use /plot debugexec show-expired "); } - case "seen": { - if (args.length != 2) { - return MainUtil.sendMessage(player, "Use /plot debugexec seen "); - } + case "seen": + { + if (args.length != 2) { return MainUtil.sendMessage(player, "Use /plot debugexec seen "); } final UUID uuid = UUIDHandler.getUUID(args[1], null); - if (uuid == null) { - return MainUtil.sendMessage(player, "player not found: " + args[1]); - } + if (uuid == null) { return MainUtil.sendMessage(player, "player not found: " + args[1]); } final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); - if ((op == null) || (op.getLastPlayed() == 0)) { - return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]); - } + 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()); MainUtil.sendMessage(player, "PLAYER: " + args[1]); @@ -323,34 +357,40 @@ public class DebugExec extends SubCommand { MainUtil.sendMessage(player, "Local: " + date.toLocaleString()); return true; } - case "trim-check": { - if (args.length != 2) { + case "trim-check": + { + if (args.length != 2) + { MainUtil.sendMessage(player, "Use /plot debugexec trim-check "); MainUtil.sendMessage(player, "&7 - Generates a list of regions to trim"); return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run"); } final String world = args[1]; - if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(args[1])) { - return MainUtil.sendMessage(player, "Invalid world: " + args[1]); - } + if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(args[1])) { return MainUtil.sendMessage(player, "Invalid world: " + args[1]); } final ArrayList empty = new ArrayList<>(); - final boolean result = Trim.getTrimRegions(empty, world, new Runnable() { + final boolean result = Trim.getTrimRegions(empty, world, new Runnable() + { @Override - public void run() { + public void run() + { Trim.sendMessage("Processing is complete! Here's how many chunks would be deleted:"); Trim.sendMessage(" - MCA #: " + empty.size()); Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)"); Trim.sendMessage("Exporting log for manual approval..."); final File file = new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt"); PrintWriter writer; - try { + try + { writer = new PrintWriter(file); - for (final ChunkLoc loc : empty) { + for (final ChunkLoc loc : empty) + { writer.println(world + "/region/r." + loc.x + "." + loc.z + ".mca"); } writer.close(); Trim.sendMessage("File saved to 'plugins/PlotSquared/trim.txt'"); - } catch (final FileNotFoundException e) { + } + catch (final FileNotFoundException e) + { e.printStackTrace(); Trim.sendMessage("File failed to save! :("); } @@ -360,7 +400,8 @@ public class DebugExec extends SubCommand { Trim.sendMessage(" - Add 31 to each number to get the end position"); } }); - if (!result) { + if (!result) + { MainUtil.sendMessage(player, "Trim task already started!"); } return result; @@ -368,90 +409,120 @@ public class DebugExec extends SubCommand { case "h": case "he": case "?": - case "help": { + case "help": + { MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">"); return false; } - case "addcmd": { - try { - final String cmd = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), System.getProperty("line.separator")); - Command subcommand = new Command(args[1].split("\\.")[0]) { - @Override - public boolean onCommand(PlotPlayer plr, String[] args) { - try { - scope.put("PlotPlayer", plr); - scope.put("args", args); - engine.eval(cmd, scope); - return true; - } catch (ScriptException e) { - e.printStackTrace(); - MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG); - return false; + case "addcmd": + { + try + { + final String cmd = StringMan.join(Files.readLines(new File(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]) + { + @Override + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + try + { + scope.put("PlotPlayer", plr); + scope.put("args", args); + engine.eval(cmd, scope); + return true; + } + catch (final ScriptException e) + { + e.printStackTrace(); + MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG); + return false; + } } - } - }; - MainCommand.getInstance().addCommand(subcommand); - return true; + }; + MainCommand.getInstance().addCommand(subcommand); + return true; } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); return false; } } - case "runasync": { + case "runasync": + { async = true; } - case "run": { - try { - script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), System.getProperty("line.separator")); - if (args.length > 2) { - HashMap replacements = new HashMap<>(); - for (int i = 2; i < args.length; i++) { - replacements.put("%s" + (i-2), args[i]); + case "run": + { + try + { + script = StringMan.join(Files.readLines(new File(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<>(); + for (int i = 2; i < args.length; i++) + { + replacements.put("%s" + (i - 2), args[i]); } script = StringMan.replaceFromMap(script, replacements); } - } catch (IOException e) { + } + catch (final IOException e) + { e.printStackTrace(); return false; } break; } - default: { + default: + { script = StringMan.join(args, " "); } } - if (!ConsolePlayer.isConsole(player)) { + if (!ConsolePlayer.isConsole(player)) + { MainUtil.sendMessage(player, C.NOT_CONSOLE); return false; } init(); scope.put("PlotPlayer", player); PS.debug("> " + script); - try { - if (async) { + try + { + if (async) + { final String toExec = script; - TaskManager.runTaskAsync(new Runnable() { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - long start = System.currentTimeMillis(); - try { + public void run() + { + final long start = System.currentTimeMillis(); + try + { engine.eval(toExec, scope); - } catch (ScriptException e) { + } + catch (final ScriptException e) + { e.printStackTrace(); } PS.log("> " + (System.currentTimeMillis() - start) + "ms"); } }); } - else { - long start = System.currentTimeMillis(); + else + { + final long start = System.currentTimeMillis(); engine.eval(script, scope); PS.log("> " + (System.currentTimeMillis() - start) + "ms"); } return true; - } catch (ScriptException e) { + } + catch (final ScriptException e) + { e.printStackTrace(); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugFill.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugFill.java index f9c052f2f..6bc93fca5 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugFill.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugFill.java @@ -32,36 +32,39 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "fill", - permission = "plots.fill", - description = "Fill or surround a plot in bedrock", - usage = "/plot fill", - aliases = {"debugfill"}, - category = CommandCategory.DEBUG, - requiredType = RequiredType.NONE -) -public class DebugFill extends SubCommand { +command = "fill", +permission = "plots.fill", +description = "Fill or surround a plot in bedrock", +usage = "/plot fill", +aliases = { "debugfill" }, +category = CommandCategory.DEBUG, +requiredType = RequiredType.NONE) +public class DebugFill extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer player, final String ... args) { - if (args.length != 1 || (!args[0].equalsIgnoreCase("outline") && !args[0].equalsIgnoreCase("all"))) { + public boolean onCommand(final PlotPlayer player, final String... args) + { + if ((args.length != 1) || (!args[0].equalsIgnoreCase("outline") && !args[0].equalsIgnoreCase("all"))) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot fill "); return true; } final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.fill")) { + if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.fill")) + { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return true; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); return false; } @@ -69,89 +72,119 @@ public class DebugFill extends SubCommand { final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id); MainUtil.sendMessage(player, "&cPreparing task"); MainUtil.runners.put(plot, 1); - SetBlockQueue.addNotify(new Runnable() { + SetBlockQueue.addNotify(new Runnable() + { @Override - public void run() { - TaskManager.runTaskAsync(new Runnable() { + public void run() + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(player, "&7 - Starting"); - if (args[0].equalsIgnoreCase("all")) { + if (args[0].equalsIgnoreCase("all")) + { int height = 255; PlotBlock block = new PlotBlock((short) 7, (byte) 0); - PlotBlock air = new PlotBlock((short) 0, (byte) 0); - if (args.length > 2) { - try { + final PlotBlock air = new PlotBlock((short) 0, (byte) 0); + if (args.length > 2) + { + try + { block = new PlotBlock(Short.parseShort(args[1]), (byte) 0); - if (args.length == 3) { + if (args.length == 3) + { height = Integer.parseInt(args[2]); } } - catch (Exception e) { + catch (final Exception e) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot fill all "); MainUtil.runners.remove(plot); return; } } - for (int y = 0; y <= height; y++) { - for (int x = bottom.getX(); x <= top.getX(); x++) { - for (int z = bottom.getZ(); z <= top.getZ(); z++) { + for (int y = 0; y <= height; y++) + { + for (int x = bottom.getX(); x <= top.getX(); x++) + { + for (int z = bottom.getZ(); z <= top.getZ(); z++) + { SetBlockQueue.setBlock(plot.world, x, y, z, block); } } } - for (int y = height + 1; y <= 255; y++) { - for (int x = bottom.getX(); x <= top.getX(); x++) { - for (int z = bottom.getZ(); z <= top.getZ(); z++) { + for (int y = height + 1; y <= 255; y++) + { + for (int x = bottom.getX(); x <= top.getX(); x++) + { + for (int z = bottom.getZ(); z <= top.getZ(); z++) + { SetBlockQueue.setBlock(plot.world, x, y, z, air); } } } - SetBlockQueue.addNotify(new Runnable() { + SetBlockQueue.addNotify(new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); MainUtil.sendMessage(player, "&aFill task complete!"); } }); } - else if (args[0].equals("outline")) { + else if (args[0].equals("outline")) + { int x, z; z = bottom.getZ(); - for (x = bottom.getX(); x <= (top.getX() - 1); x++) { - for (int y = 1; y <= 255; y++) { + for (x = bottom.getX(); x <= (top.getX() - 1); x++) + { + for (int y = 1; y <= 255; y++) + { SetBlockQueue.setBlock(plot.world, x, y, z, 7); } } x = top.getX(); - for (z = bottom.getZ(); z <= (top.getZ() - 1); z++) { - for (int y = 1; y <= 255; y++) { + for (z = bottom.getZ(); z <= (top.getZ() - 1); z++) + { + for (int y = 1; y <= 255; y++) + { SetBlockQueue.setBlock(plot.world, x, y, z, 7); } } z = top.getZ(); - for (x = top.getX(); x >= (bottom.getX() + 1); x--) { - for (int y = 1; y <= 255; y++) { + for (x = top.getX(); x >= (bottom.getX() + 1); x--) + { + for (int y = 1; y <= 255; y++) + { SetBlockQueue.setBlock(plot.world, x, y, z, 7); } } x = bottom.getX(); - for (z = top.getZ(); z >= (bottom.getZ() + 1); z--) { - for (int y = 1; y <= 255; y++) { + for (z = top.getZ(); z >= (bottom.getZ() + 1); z--) + { + for (int y = 1; y <= 255; y++) + { SetBlockQueue.setBlock(plot.world, x, y, z, 7); } } - SetBlockQueue.addNotify(new Runnable() { + SetBlockQueue.addNotify(new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(player, "&aWalls complete! The ceiling will take a while :("); bottom.setY(255); - top.add(1,0,1); + top.add(1, 0, 1); SetBlockQueue.setSlow(true); MainUtil.setSimpleCuboidAsync(plot.world, bottom, top, new PlotBlock((short) 7, (byte) 0)); - SetBlockQueue.addNotify(new Runnable() { + SetBlockQueue.addNotify(new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); MainUtil.sendMessage(player, "&aFill task complete!"); SetBlockQueue.setSlow(false); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java index 26daf282d..869d98724 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java @@ -37,40 +37,47 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - 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 { +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() { + public DebugFixFlags() + { requiredArguments = new Argument[] { - Argument.String + Argument.String }; } @Override - public boolean onCommand(PlotPlayer plr, String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final String world = args[0]; - if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) { + if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD, args[0]); return false; } MainUtil.sendMessage(plr, "&8--- &6Starting task &8 ---"); - for (final Plot plot : PS.get().getPlotsInWorld(world)) { + for (final Plot plot : PS.get().getPlotsInWorld(world)) + { final HashMap flags = plot.getSettings().flags; - Iterator> i = flags.entrySet().iterator(); + final Iterator> i = flags.entrySet().iterator(); boolean changed = false; - while (i.hasNext()) { - if (FlagManager.getFlag(i.next().getKey()) == null) { + while (i.hasNext()) + { + if (FlagManager.getFlag(i.next().getKey()) == null) + { changed = true; i.remove(); } } - if (changed) { + if (changed) + { DBFunc.setFlags(plot, plot.getSettings().flags.values()); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java index 6a7f22ad4..f87573a7d 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java @@ -28,22 +28,26 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; @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 -) -public class DebugLoadTest extends SubCommand { +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(PlotPlayer plr, String[] args) { - try { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + try + { final Field fPlots = PS.class.getDeclaredField("plots"); fPlots.setAccessible(true); fPlots.set(null, DBFunc.getPlots()); - } catch (final Exception e) { + } + catch (final Exception e) + { PS.debug("&3===FAILED&3==="); e.printStackTrace(); PS.debug("&3===END OF STACKTRACE==="); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java index 32593bcc5..cffb514dd 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java @@ -15,30 +15,37 @@ import com.plotsquared.bukkit.BukkitMain; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "debugpaste", - aliases = {"dp"}, - usage = "/plot debugpaste", - description = "Upload settings.yml & latest.log to hastebin", - permission = "plots.debugpaste", - category = CommandCategory.DEBUG -) -public class DebugPaste extends SubCommand { +command = "debugpaste", +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, String[] args) { - TaskManager.runTaskAsync(new Runnable() { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - try { - String settingsYML = HastebinUtility.upload(PS.get().configFile); + public void run() + { + try + { + final String settingsYML = HastebinUtility.upload(PS.get().configFile); String latestLOG; - try { + try + { latestLOG = HastebinUtility.upload(new File(BukkitMain.THIS.getDirectory(), "../../logs/latest.log")); - } catch(final Exception e) { + } + catch (final Exception e) + { plr.sendMessage("&clatest.log is too big to be pasted, will ignore"); latestLOG = "too big :("; } - StringBuilder b = new StringBuilder(); + 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"); b.append("links.settings_yml: '").append(settingsYML).append("'\n"); b.append("links.latest_log: '").append(latestLOG).append("'\n"); @@ -47,11 +54,12 @@ public class DebugPaste extends SubCommand { b.append("version.bukkit: '").append(Bukkit.getBukkitVersion()).append("'\n"); b.append("online_mode: ").append(Bukkit.getServer().getOnlineMode()).append("\n"); b.append("plugins:"); - for (final Plugin p : Bukkit.getPluginManager().getPlugins()) { + for (final Plugin p : Bukkit.getPluginManager().getPlugins()) + { b.append("\n ").append(p.getName()).append(":\n ").append("version: '").append(p.getDescription().getVersion()).append("'").append("\n enabled: ").append(p.isEnabled()); } b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); - Runtime runtime = Runtime.getRuntime(); + final 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 +71,11 @@ 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"); - String link = HastebinUtility.upload(b.toString()); + final String link = HastebinUtility.upload(b.toString()); plr.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); - } catch (IOException e) { + } + catch (final IOException e) + { e.printStackTrace(); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java index bd919fc78..ff789ba9c 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java @@ -35,44 +35,49 @@ 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" -) -public class DebugRoadRegen extends SubCommand { +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) { + public boolean onCommand(final PlotPlayer player, final String... args) + { final Location loc = player.getLocation(); final String world = loc.getWorld(); - PlotWorld plotworld = PS.get().getPlotWorld(world); - if (!(plotworld instanceof HybridPlotWorld)) { - return sendMessage(player, C.NOT_IN_PLOT_WORLD); - } - Plot plot = player.getCurrentPlot(); - if (plot == null) { + final PlotWorld plotworld = PS.get().getPlotWorld(world); + if (!(plotworld instanceof HybridPlotWorld)) { return sendMessage(player, C.NOT_IN_PLOT_WORLD); } + final Plot plot = player.getCurrentPlot(); + if (plot == null) + { final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); int extend = 0; - if (args.length == 1) { - if (MathMan.isInteger(args[0])) { - try { + if (args.length == 1) + { + if (MathMan.isInteger(args[0])) + { + try + { extend = Integer.parseInt(args[0]); } - catch (Exception e) { + catch (final Exception e) + { C.NOT_VALID_NUMBER.send(player, "(0, )"); return false; } } } - boolean result = HybridUtils.manager.regenerateRoad(world, chunk, extend); + final boolean result = HybridUtils.manager.regenerateRoad(world, chunk, extend); MainUtil.sendMessage(player, "&6Regenerating chunk: " + chunk.x + "," + chunk.z + "\n&6 - Result: " + (result == true ? "&aSuccess" : "&cFailed")); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } - else { - HybridPlotManager manager = (HybridPlotManager) PS.get().getPlotManager(world); + else + { + final HybridPlotManager manager = (HybridPlotManager) PS.get().getPlotManager(world); manager.createRoadEast(plotworld, plot); manager.createRoadSouth(plotworld, plot); manager.createRoadSouthEast(plotworld, plot); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java index a645a6900..81cd03e2f 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java @@ -30,23 +30,26 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @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" -) -public class DebugSaveTest extends SubCommand { +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(PlotPlayer plr, String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final ArrayList plots = new ArrayList(); plots.addAll(PS.get().getPlots()); MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`"); - DBFunc.createPlotsAndData(plots, new Runnable() { + DBFunc.createPlotsAndData(plots, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(null, "&6Database sync finished!"); } }); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java index bcff67c15..7ced00979 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java @@ -36,7 +36,6 @@ import org.bukkit.Bukkit; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.AbstractDB; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.OfflinePlotPlayer; @@ -55,54 +54,64 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "uuidconvert", - permission = "plots.admin", - description = "Debug UUID conversion", - usage = "/plot uuidconvert ", - requiredType = RequiredType.CONSOLE, - category = CommandCategory.DEBUG -) -public class DebugUUID extends SubCommand { +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() { + public DebugUUID() + { requiredArguments = new Argument[] { - Argument.String + Argument.String }; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - PlotPlayer player = null; + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final PlotPlayer player = null; final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper(); final UUIDWrapper newWrapper; - - switch (args[0].toLowerCase()) { - case "lower": { + + switch (args[0].toLowerCase()) + { + case "lower": + { newWrapper = new LowerOfflineUUIDWrapper(); break; } - case "offline": { + case "offline": + { newWrapper = new OfflineUUIDWrapper(); break; } - case "online": { + case "online": + { newWrapper = new DefaultUUIDWrapper(); break; } - default: { - try { - Class clazz = Class.forName(args[0]); + default: + { + try + { + final Class clazz = Class.forName(args[0]); newWrapper = (UUIDWrapper) clazz.newInstance(); } - catch (Exception e) { + catch (final Exception e) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert "); return false; } } } - - if (args.length != 2 || !args[1].equals("-o")) { + + if ((args.length != 2) || !args[1].equals("-o")) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o"); MainUtil.sendMessage(player, "&cBe aware of the following!"); MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand"); @@ -113,22 +122,24 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)"); return false; } - - if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) { + + if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) + { MainUtil.sendMessage(player, "&cUUID mode already in use!"); return false; } MainUtil.sendConsoleMessage("&6Beginning UUID mode conversion"); MainUtil.sendConsoleMessage("&7 - Disconnecting players"); - for (PlotPlayer pp : UUIDHandler.getPlayers().values()) { + for (final PlotPlayer pp : UUIDHandler.getPlayers().values()) + { pp.kick("PlotSquared UUID conversion has been initiated. You may reconnect when finished."); } - + MainUtil.sendConsoleMessage("&7 - Initializing map"); - + final HashMap uCMap = new HashMap(); final HashMap uCReverse = new HashMap(); - + MainUtil.sendConsoleMessage("&7 - Collecting playerdata"); final HashSet worlds = new HashSet<>(); @@ -136,212 +147,269 @@ public class DebugUUID extends SubCommand { worlds.add("world"); final HashSet uuids = new HashSet<>(); final HashSet names = new HashSet<>(); - for (final String worldname : worlds) { + for (final String worldname : worlds) + { final File playerdataFolder = new File(worldname + File.separator + "playerdata"); - String[] dat = playerdataFolder.list(new FilenameFilter() { + String[] dat = playerdataFolder.list(new FilenameFilter() + { @Override - public boolean accept(final File f, final String s) { + public boolean accept(final File f, final String s) + { return s.endsWith(".dat"); } }); - if (dat != null) { - for (final String current : dat) { + if (dat != null) + { + for (final String current : dat) + { final String s = current.replaceAll(".dat$", ""); - try { + try + { final UUID uuid = UUID.fromString(s); uuids.add(uuid); - } catch (final Exception e) { + } + catch (final Exception e) + { MainUtil.sendMessage(plr, C.PREFIX.s() + "Invalid playerdata: " + current); } } } final File playersFolder = new File(worldname + File.separator + "players"); - dat = playersFolder.list(new FilenameFilter() { + dat = playersFolder.list(new FilenameFilter() + { @Override - public boolean accept(final File f, final String s) { + public boolean accept(final File f, final String s) + { return s.endsWith(".dat"); } }); - if (dat != null) { - for (final String current : dat) { + if (dat != null) + { + for (final String current : dat) + { names.add(current.replaceAll(".dat$", "")); } } } - + MainUtil.sendConsoleMessage("&7 - Populating map"); UUID uuid2; final UUIDWrapper wrapper = new DefaultUUIDWrapper(); - for (UUID uuid : uuids) { - try { + for (UUID uuid : uuids) + { + try + { final OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid); uuid = currentUUIDWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op); - if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) { + if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) + { uCMap.put(uuid, uuid2); uCReverse.put(uuid2, uuid); } - } catch (final Throwable e) { + } + catch (final Throwable e) + { MainUtil.sendMessage(plr, C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } - for (final String name : names) { + for (final String name : names) + { final UUID uuid = currentUUIDWrapper.getUUID(name); uuid2 = newWrapper.getUUID(name); - if (!uuid.equals(uuid2)) { + if (!uuid.equals(uuid2)) + { uCMap.put(uuid, uuid2); uCReverse.put(uuid2, uuid); } } - if (uCMap.size() == 0) { + if (uCMap.size() == 0) + { MainUtil.sendConsoleMessage("&c - Error! Attempting to repopulate"); - for (OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) { - if (op.getLastPlayed() != 0) { -// String name = op.getName(); -// StringWrapper wrap = new StringWrapper(name); - UUID uuid = currentUUIDWrapper.getUUID(op); + for (final OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) + { + if (op.getLastPlayed() != 0) + { + // String name = op.getName(); + // StringWrapper wrap = new StringWrapper(name); + final UUID uuid = currentUUIDWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op); - if (!uuid.equals(uuid2)) { + if (!uuid.equals(uuid2)) + { uCMap.put(uuid, uuid2); uCReverse.put(uuid2, uuid); } } } - if (uCMap.size() == 0) { + if (uCMap.size() == 0) + { MainUtil.sendConsoleMessage("&cError. Failed to collect UUIDs!"); return false; } - else { + else + { MainUtil.sendConsoleMessage("&a - Successfully repopulated"); } } - + MainUtil.sendConsoleMessage("&7 - Replacing cache"); - TaskManager.runTaskAsync(new Runnable() { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - for (Entry entry : uCMap.entrySet()) { - String name = UUIDHandler.getName(entry.getKey()); - if (name != null) { + public void run() + { + for (final Entry entry : uCMap.entrySet()) + { + final String name = UUIDHandler.getName(entry.getKey()); + if (name != null) + { UUIDHandler.add(new StringWrapper(name), entry.getValue()); } } - + MainUtil.sendConsoleMessage("&7 - Scanning for applicable files (uuids.txt)"); - - File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); - if (file.exists()) { - try { - List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - for (String line : lines) { - try { + + final File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); + if (file.exists()) + { + try + { + final List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + for (String line : lines) + { + try + { line = line.trim(); - if (line.length() == 0) { + if (line.length() == 0) + { continue; } line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - String[] split = line.split("\\|"); - String name = split[0]; - if (name.length() == 0 || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) { + final String[] split = line.split("\\|"); + final String name = split[0]; + if ((name.length() == 0) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) + { continue; } - UUID old = currentUUIDWrapper.getUUID(name); - if (old == null) { + final UUID old = currentUUIDWrapper.getUUID(name); + if (old == null) + { continue; } - UUID now = newWrapper.getUUID(name); + final UUID now = newWrapper.getUUID(name); UUIDHandler.add(new StringWrapper(name), now); uCMap.put(old, now); uCReverse.put(now, old); } - catch (Exception e2) { + catch (final Exception e2) + { e2.printStackTrace(); } } - } catch (IOException e) { + } + catch (final IOException e) + { e.printStackTrace(); } } - + MainUtil.sendConsoleMessage("&7 - Replacing wrapper"); UUIDHandler.setUUIDWrapper(newWrapper); - + MainUtil.sendConsoleMessage("&7 - Updating plot objects"); - for (Plot plot : PS.get().getPlotsRaw()) { - UUID value = uCMap.get(plot.owner); - if (value != null) { + for (final Plot plot : PS.get().getPlotsRaw()) + { + final UUID value = uCMap.get(plot.owner); + if (value != null) + { plot.owner = value; } plot.getTrusted().clear(); plot.getMembers().clear(); plot.getDenied().clear(); } - + MainUtil.sendConsoleMessage("&7 - Deleting database"); final AbstractDB database = DBFunc.dbManager; - boolean result = database.deleteTables(); + final boolean result = database.deleteTables(); MainUtil.sendConsoleMessage("&7 - Creating tables"); - - try { + + try + { database.createTables(); - if (!result) { + if (!result) + { MainUtil.sendConsoleMessage("&cConversion failed! Attempting recovery"); - for (Plot plot : PS.get().getPlots()) { - UUID value = uCReverse.get(plot.owner); - if (value != null) { + for (final Plot plot : PS.get().getPlots()) + { + final UUID value = uCReverse.get(plot.owner); + if (value != null) + { plot.owner = value; } } - database.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() { + database.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(null, "&6Recovery was successful!"); } }); return; } } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); return; } - - if (newWrapper instanceof OfflineUUIDWrapper) { + + if (newWrapper instanceof OfflineUUIDWrapper) + { PS.get().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.offline", true); } - else if (newWrapper instanceof LowerOfflineUUIDWrapper) { + else if (newWrapper instanceof LowerOfflineUUIDWrapper) + { PS.get().config.set("UUID.force-lowercase", true); PS.get().config.set("UUID.offline", true); } - else if (newWrapper instanceof DefaultUUIDWrapper) { + else if (newWrapper instanceof DefaultUUIDWrapper) + { PS.get().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.offline", false); } - try { + try + { PS.get().config.save(PS.get().configFile); } - catch (Exception e) { + catch (final Exception e) + { MainUtil.sendConsoleMessage("Could not save configuration. It will need to be manuall set!"); } - + MainUtil.sendConsoleMessage("&7 - Populating tables"); - - TaskManager.runTaskAsync(new Runnable() { + + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - ArrayList plots = new ArrayList<>(PS.get().getPlots()); - database.createPlotsAndData(plots, new Runnable() { + public void run() + { + final ArrayList plots = new ArrayList<>(PS.get().getPlots()); + database.createPlotsAndData(plots, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendConsoleMessage("&aConversion complete!"); } }); } }); - + MainUtil.sendConsoleMessage("&aIt is now safe for players to join"); MainUtil.sendConsoleMessage("&cConversion is still in progress, you will be notified when it is complete"); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/src/main/java/com/intellectualcrafters/plot/commands/Delete.java index 0498af26c..a2fc99a94 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Delete.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Delete.java @@ -36,66 +36,73 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "delete", - permission = "plots.delete", - description = "Delete a plot", - usage = "/plot delete", - aliases = {"dispose", "del"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Delete extends SubCommand { +command = "delete", +permission = "plots.delete", +description = "Delete a plot", +usage = "/plot delete", +aliases = { "dispose", "del" }, +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Delete extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { - return !sendMessage(plr, C.UNLINK_REQUIRED); - } - if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID()))) && !Permissions.hasPermission(plr, "plots.admin.command.delete")) { - return !sendMessage(plr, C.NO_PLOT_PERMS); - } + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { return !sendMessage(plr, C.UNLINK_REQUIRED); } + if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID()))) && !Permissions.hasPermission(plr, "plots.admin.command.delete")) { return !sendMessage(plr, C.NO_PLOT_PERMS); } final PlotWorld pWorld = PS.get().getPlotWorld(plot.world); - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } - Runnable runnable = new Runnable() { + final Runnable runnable = new Runnable() + { @Override - public void run() { - if ((EconHandler.manager != null) && pWorld.USE_ECONOMY && plot.hasOwner() && plot.isOwner(UUIDHandler.getUUID(plr))) { + public void run() + { + if ((EconHandler.manager != null) && pWorld.USE_ECONOMY && plot.hasOwner() && plot.isOwner(UUIDHandler.getUUID(plr))) + { final double c = pWorld.SELL_PRICE; - if (c > 0d) { + if (c > 0d) + { EconHandler.manager.depositMoney(plr, c); sendMessage(plr, C.ADDED_BALANCE, c + ""); } } - if (plot.unclaim()) { + if (plot.unclaim()) + { final long start = System.currentTimeMillis(); - final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() { + final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(plr, C.CLEARING_DONE, "" + (System.currentTimeMillis() - start)); } }); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); } } - else { + else + { MainUtil.sendMessage(plr, C.UNCLAIM_FAILED); } } }; - if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { + if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) + { CmdConfirm.addPending(plr, "/plot delete " + plot.id, runnable); } - else { + else + { TaskManager.runTask(runnable); } return true; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Deny.java b/src/main/java/com/intellectualcrafters/plot/commands/Deny.java index 4d84b6649..5f033a543 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Deny.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Deny.java @@ -37,57 +37,68 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "deny", - aliases = {"d"}, - description = "Deny a user from a plot", - usage = "/plot deny ", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Deny extends SubCommand { +command = "deny", +aliases = { "d" }, +description = "Deny a user from a plot", +usage = "/plot deny ", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Deny extends SubCommand +{ - public Deny() { + public Deny() + { requiredArguments = new Argument[] { - Argument.PlayerName + Argument.PlayerName }; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if ((plot == null) || !plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((plot == null) || !plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.deny")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.deny")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return true; } UUID uuid; - if (args[0].equalsIgnoreCase("*")) { + if (args[0].equalsIgnoreCase("*")) + { uuid = DBFunc.everyone; - } else { + } + else + { uuid = UUIDHandler.getUUID(args[0], null); } - if (uuid == null) { - if (UUIDHandler.implementation instanceof SQLUUIDHandler) { + if (uuid == null) + { + if (UUIDHandler.implementation instanceof SQLUUIDHandler) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER_WAIT, args[0]); - } else { + } + else + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); } return false; } - if (plot.isOwner(uuid)) { + if (plot.isOwner(uuid)) + { MainUtil.sendMessage(plr, C.ALREADY_OWNER); return false; } - - if (plot.getDenied().contains(uuid)) { + + if (plot.getDenied().contains(uuid)) + { MainUtil.sendMessage(plr, C.ALREADY_ADDED); return false; } @@ -96,15 +107,18 @@ public class Deny extends SubCommand { plot.addDenied(uuid); EventUtil.manager.callDenied(plr, plot, uuid, true); MainUtil.sendMessage(plr, C.DENIED_ADDED); - if (!uuid.equals(DBFunc.everyone)) { + if (!uuid.equals(DBFunc.everyone)) + { handleKick(uuid, plot); } return true; } - private void handleKick(final UUID uuid, final Plot plot) { - PlotPlayer pp = UUIDHandler.getPlayer(uuid); - if (pp != null && plot.equals(MainUtil.getPlot(pp.getLocation()))) { + private void handleKick(final UUID uuid, final Plot plot) + { + final PlotPlayer pp = UUIDHandler.getPlayer(uuid); + if ((pp != null) && plot.equals(MainUtil.getPlot(pp.getLocation()))) + { pp.teleport(BlockManager.manager.getSpawn(pp.getLocation().getWorld())); MainUtil.sendMessage(pp, C.YOU_GOT_DENIED); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Done.java b/src/main/java/com/intellectualcrafters/plot/commands/Done.java index 42ea960bd..6cdf7ae22 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Done.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Done.java @@ -30,53 +30,57 @@ import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "done", - aliases = {"submit"}, - description = "Mark a plot as done", - permission = "plots.done", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Done extends SubCommand { +command = "done", +aliases = { "submit" }, +description = "Mark a plot as done", +permission = "plots.done", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Done extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - 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 == null) || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.done")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (plot.getSettings().flags.containsKey("done")) { + if (plot.getSettings().flags.containsKey("done")) + { MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE); return false; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); MainUtil.sendMessage(plr, C.GENERATING_LINK); - HybridUtils.manager.analyzePlot(plot, new RunnableVal() { + HybridUtils.manager.analyzePlot(plot, new RunnableVal() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); - if (value == null || value.getComplexity() >= Settings.CLEAR_THRESHOLD) { - Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000)); + if ((value == null) || (value.getComplexity() >= Settings.CLEAR_THRESHOLD)) + { + final Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000)); FlagManager.addPlotFlag(plot, flag); MainUtil.sendMessage(plr, C.DONE_SUCCESS); } - else { + else + { MainUtil.sendMessage(plr, C.DONE_INSUFFICIENT_COMPLEXITY); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Download.java b/src/main/java/com/intellectualcrafters/plot/commands/Download.java index fcd16bdbe..c9f0f8db3 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Download.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Download.java @@ -17,52 +17,58 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "download", - aliases = {"dl"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - description = "Download your plot", - permission = "plots.download" -) -public class Download extends SubCommand { +command = "download", +aliases = { "dl" }, +category = CommandCategory.ACTIONS, +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) { - - if (!Settings.METRICS) { + public boolean onCommand(final PlotPlayer plr, final 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"); return false; } final String world = plr.getLocation().getWorld(); - if (!PS.get().isPlotWorld(world)) { - return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); - } + if (!PS.get().isPlotWorld(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } final Plot plot = MainUtil.getPlot(plr.getLocation()); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if ((!plot.isOwner(plr.getUUID()) || (Settings.DOWNLOAD_REQUIRES_DONE && FlagManager.getPlotFlag(plot, "done") != null)) && !Permissions.hasPermission(plr, "plots.admin.command.download")) { + if ((!plot.isOwner(plr.getUUID()) || (Settings.DOWNLOAD_REQUIRES_DONE && (FlagManager.getPlotFlag(plot, "done") != null))) && !Permissions.hasPermission(plr, "plots.admin.command.download")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); MainUtil.sendMessage(plr, C.GENERATING_LINK); - SchematicHandler.manager.getCompoundTag(plot.world, plot.id, new RunnableVal() { + SchematicHandler.manager.getCompoundTag(plot.world, plot.id, new RunnableVal() + { @Override - public void run() { - TaskManager.runTaskAsync(new Runnable() { + public void run() + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - URL url = SchematicHandler.manager.upload(value, null, null); - if (url == null) { + public void run() + { + final URL url = SchematicHandler.manager.upload(value, null, null); + if (url == null) + { MainUtil.sendMessage(plr, C.GENERATING_LINK_FAILED); MainUtil.runners.remove(plot); return; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java index 58520793a..70d1df41a 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java @@ -39,24 +39,26 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "flag", - aliases = {"f"}, - usage = "/plot flag ", - description = "Manage plot flags", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - permission = "plots.flag" -) -public class FlagCmd extends SubCommand { +command = "flag", +aliases = { "f" }, +usage = "/plot flag ", +description = "Manage plot flags", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE, +permission = "plots.flag") +public class FlagCmd extends SubCommand +{ @Override - public String getUsage() { + public String getUsage() + { return super.getUsage().replaceAll("", StringMan.join(FlagManager.getFlags(), "|")); } - + @Override - public boolean onCommand(final PlotPlayer player, final String ... args) { - + public boolean onCommand(final PlotPlayer player, final String... args) + { + /* * plot flag set fly true * plot flag remove fly @@ -64,40 +66,50 @@ public class FlagCmd extends SubCommand { * plot flag add use 2,4 * plot flag list */ - if (args.length == 0) { + if (args.length == 0) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag "); return false; } final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { + if (plot == null) + { MainUtil.sendMessage(player, C.NOT_IN_PLOT); return false; } - if (!plot.hasOwner()) { + if (!plot.hasOwner()) + { sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, "plots.set.flag.other")) { + if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, "plots.set.flag.other")) + { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag.other"); return false; } - if (args.length > 1 && FlagManager.isReserved(args[1])) { + if ((args.length > 1) && FlagManager.isReserved(args[1])) + { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } - switch (args[0].toLowerCase()) { - case "info": { - if (!Permissions.hasPermission(player, "plots.set.flag")) { + switch (args[0].toLowerCase()) + { + case "info": + { + if (!Permissions.hasPermission(player, "plots.set.flag")) + { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.info"); return false; } - if (args.length != 2) { + if (args.length != 2) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info "); return false; } final AbstractFlag af = FlagManager.getFlag(args[1]); - if (af == null) { + if (af == null) + { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info "); return false; @@ -110,73 +122,92 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.FLAG_DESC, af.getValueDesc()); return true; } - case "set": { - if (!Permissions.hasPermission(player, "plots.set.flag")) { + case "set": + { + if (!Permissions.hasPermission(player, "plots.set.flag")) + { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag"); return false; } - if (args.length < 3) { + if (args.length < 3) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag set "); return false; } final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); - if (af == null) { + if (af == null) + { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); - if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + value.toLowerCase())) { + 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); - if (parsed == null) { + 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); - if (!result) { + if (!result) + { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; } MainUtil.sendMessage(player, C.FLAG_ADDED); return true; } - case "remove": { - if (!Permissions.hasPermission(player, "plots.flag.remove")) { + case "remove": + { + if (!Permissions.hasPermission(player, "plots.flag.remove")) + { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.remove"); return false; } - if ((args.length != 2) && (args.length != 3)) { + if ((args.length != 2) && (args.length != 3)) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); return false; } final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); - if (af == null) { + if (af == null) + { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()); - if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { - for (String entry : args[2].split(",")) { - if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) { + if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) + { + for (final 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; } } } - if (flag == null) { + if (flag == null) + { MainUtil.sendMessage(player, C.FLAG_NOT_IN_PLOT); return false; } - if ((args.length == 3) && flag.getAbstractFlag().isList()) { + if ((args.length == 3) && flag.getAbstractFlag().isList()) + { final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); ((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value); DBFunc.setFlags(plot, plot.getSettings().flags.values()); - } else { + } + else + { final boolean result = FlagManager.removePlotFlag(plot, flag.getKey()); - if (!result) { + if (!result) + { MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED); return false; } @@ -184,23 +215,30 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.FLAG_REMOVED); return true; } - case "add": { - if (!Permissions.hasPermission(player, "plots.flag.add")) { + case "add": + { + if (!Permissions.hasPermission(player, "plots.flag.add")) + { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.add"); return false; } - if (args.length < 3) { + if (args.length < 3) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); return false; } final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); - if (af == null) { + if (af == null) + { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } - if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { - for (String entry : args[2].split(",")) { - if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) { + if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) + { + for (final 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; } @@ -208,18 +246,23 @@ public class FlagCmd extends SubCommand { } final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); final Object parsed = af.parseValueRaw(value); - if (parsed == null) { + if (parsed == null) + { MainUtil.sendMessage(player, "&c" + af.getValueDesc()); return false; } Flag flag = FlagManager.getPlotFlag(plot, args[1].toLowerCase()); - if ((flag == null) || !flag.getAbstractFlag().isList()) { + if ((flag == null) || !flag.getAbstractFlag().isList()) + { flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed); - } else { + } + else + { ((FlagValue.ListValue) flag.getAbstractFlag().value).add(flag.getValue(), value); } final boolean result = FlagManager.addPlotFlag(plot, flag); - if (!result) { + if (!result) + { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; } @@ -227,26 +270,32 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.FLAG_ADDED); return true; } - case "list": { - if (!Permissions.hasPermission(player, "plots.flag.list")) { + case "list": + { + if (!Permissions.hasPermission(player, "plots.flag.list")) + { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.list"); return false; } - if (args.length != 1) { + if (args.length != 1) + { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag list"); return false; } final HashMap> flags = new HashMap<>(); - for (final AbstractFlag af : FlagManager.getFlags()) { + for (final AbstractFlag af : FlagManager.getFlags()) + { final String type = af.value.getClass().getSimpleName().replaceAll("Value", ""); - if (!flags.containsKey(type)) { + if (!flags.containsKey(type)) + { flags.put(type, new ArrayList()); } flags.get(type).add(af.getKey()); } String message = ""; String prefix = ""; - for (final String flag : flags.keySet()) { + for (final String flag : flags.keySet()) + { message += prefix + "&6" + flag + ": &7" + StringMan.join(flags.get(flag), ", "); prefix = "\n"; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java b/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java index 04e6c0860..a4cc8b2d6 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java @@ -9,79 +9,86 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.ConsolePlayer; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.Command; -public class GenerateDocs { - public static void main(String[] args) { +public class GenerateDocs +{ + public static void main(final String[] args) + { MainCommand.getInstance().addCommand(new WE_Anywhere()); MainCommand.getInstance().addCommand(new Cluster()); - ArrayList> commands = MainCommand.getInstance().getCommands(); + final 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 (CommandCategory category : CommandCategory.values()) { + for (final CommandCategory category : CommandCategory.values()) + { log("###### " + category.name()); - for (Command command : MainCommand.getCommands(category, null)) { - log(" - [/plot " + command.getCommand() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getCommand() +") "); + for (final Command command : MainCommand.getCommands(category, null)) + { + log(" - [/plot " + command.getCommand() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getCommand() + ") "); } log(""); } log("# Commands"); - for (Command command : commands) { + for (final Command command : commands) + { printCommand(command); } } - - public static void printCommand(Command command) { - try { - String clazz = command.getClass().getSimpleName(); - String name = command.getCommand(); - + + public static void printCommand(final Command command) + { + try + { + final String clazz = command.getClass().getSimpleName(); + final String name = command.getCommand(); + // Header - String source = "https://github.com/IntellectualSites/PlotSquared/tree/master/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"; + final String source = "https://github.com/IntellectualSites/PlotSquared/tree/master/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"; log("## [" + name.toUpperCase() + "](" + source + ") "); - - File file = new File("src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); - List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - List perms = getPerms(name, lines); - String comment = getComments(lines); - + + final File file = new File("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 String comment = getComments(lines); + log("#### Description"); log("`" + command.getDescription() + "`"); - if (comment.length() > 0) { + if (comment.length() > 0) + { log("##### Comments"); log("``` java"); log(comment); log("```"); } - + log("#### Usage"); log("`" + command.getUsage().replaceAll("\\{label\\}", "plot") + "`"); - - - if (command.getRequiredType() != RequiredType.NONE) { + + if (command.getRequiredType() != RequiredType.NONE) + { log("#### Required callers"); log("`" + command.getRequiredType().name() + "`"); } - - Set aliases = command.getAliases(); - if (aliases.size() > 0) { + + final Set aliases = command.getAliases(); + if (aliases.size() > 0) + { log("#### Aliases"); log("`" + StringMan.getString(command.getAliases()) + "`"); } - + log("#### Permissions"); log("##### Primary"); log(" - `" + command.getPermission() + "` "); - if (perms.size() > 0) { + if (perms.size() > 0) + { log(""); log("##### Other"); log(" - `" + StringMan.join(perms, "`\n - `") + "`"); @@ -90,54 +97,68 @@ public class GenerateDocs { log("***"); log(""); } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); } } - - public static List getPerms(String cmd, List lines) { - ArrayList perms = new ArrayList(); - Pattern p = Pattern.compile("\"([^\"]*)\""); - for (String line : lines) { - if (line.contains("Permissions.hasPermission(")) { - Matcher m = p.matcher(line); - while (m.find()) { + + public static List getPerms(final String cmd, final List lines) + { + final ArrayList perms = new ArrayList(); + final Pattern p = Pattern.compile("\"([^\"]*)\""); + for (final String line : lines) + { + if (line.contains("Permissions.hasPermission(")) + { + final Matcher m = p.matcher(line); + while (m.find()) + { String perm = m.group(1); - if (perm.endsWith(".")) { + if (perm.endsWith(".")) + { perm += ""; } - if (perm.startsWith(".")) { + if (perm.startsWith(".")) + { perms.set(perms.size() - 1, perms.get(perms.size() - 1) + perm); } - else if (perm.contains(".")) { + else if (perm.contains(".")) + { perms.add(perm); } } } } - switch (cmd.toLowerCase()) { + switch (cmd.toLowerCase()) + { case "auto": - case "claim": { + case "claim": + { perms.add("plots.plot.#"); break; } } return perms; } - - public static String getComments(List lines) { - StringBuilder result = new StringBuilder(); - for (String line : lines) { + + public static String getComments(final List lines) + { + final StringBuilder result = new StringBuilder(); + for (String line : lines) + { line = line.trim(); - if (line.startsWith("/** ") || line.startsWith("*/ ") || line.startsWith("* ")) { + if (line.startsWith("/** ") || line.startsWith("*/ ") || line.startsWith("* ")) + { line = (line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "")).trim(); result.append(line + "\n"); } } return result.toString().trim(); } - - public static void log(String s) { + + public static void log(final String s) + { System.out.println(s); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Help.java b/src/main/java/com/intellectualcrafters/plot/commands/Help.java index 4ce7611b7..5cac2dcb8 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Help.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Help.java @@ -4,15 +4,16 @@ 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 -) -public class Help extends SubCommand { +command = "help", +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(final PlotPlayer plr, final String[] args) + { return true; } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Home.java b/src/main/java/com/intellectualcrafters/plot/commands/Home.java index 99013162b..a2e509fe0 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Home.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Home.java @@ -23,7 +23,6 @@ package com.intellectualcrafters.plot.commands; import java.util.ArrayList; import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.PS.SortType; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; @@ -31,42 +30,53 @@ import com.intellectualcrafters.plot.util.MainUtil; 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 -) -public class Home extends SubCommand { +command = "home", +aliases = { "h" }, +description = "Go to your plot", +usage = "/plot home [id|alias]", +category = CommandCategory.TELEPORT, +requiredType = RequiredType.NONE) +public class Home extends SubCommand +{ - private Plot isAlias(final String a) { - for (final Plot p : PS.get().getPlots()) { - if ((p.getSettings().getAlias().length() > 0) && p.getSettings().getAlias().equalsIgnoreCase(a)) { - return p; - } + private Plot isAlias(final String a) + { + for (final Plot p : PS.get().getPlots()) + { + if ((p.getSettings().getAlias().length() > 0) && p.getSettings().getAlias().equalsIgnoreCase(a)) { return p; } } return null; } @Override - public boolean onCommand(final PlotPlayer plr, String[] args) { + public boolean onCommand(final PlotPlayer plr, String[] args) + { final ArrayList plots = PS.get().sortPlotsByTemp(PS.get().getPlots(plr));//PS.get().sortPlots(PS.get().getPlots(plr), SortType.CREATION_DATE, null); - if (plots.size() == 1) { + if (plots.size() == 1) + { MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(0)); return true; - } else if (plots.size() > 1) { - if (args.length < 1) { + } + else if (plots.size() > 1) + { + if (args.length < 1) + { args = new String[] { "1" }; } int id = 0; - try { + try + { id = Integer.parseInt(args[0]); - } catch (final Exception e) { + } + catch (final Exception e) + { Plot temp; - if ((temp = isAlias(args[0])) != null) { - if (temp.hasOwner()) { - if (temp.isOwner(plr.getUUID())) { + if ((temp = isAlias(args[0])) != null) + { + if (temp.hasOwner()) + { + if (temp.isOwner(plr.getUUID())) + { MainUtil.teleportPlayer(plr, plr.getLocation(), temp); return true; } @@ -77,19 +87,23 @@ public class Home extends SubCommand { MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + plots.size() + ")"); return true; } - if ((id > (plots.size())) || (id < 1)) { + if ((id > (plots.size())) || (id < 1)) + { MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + plots.size() + ")"); return false; } MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(id - 1)); return true; - } else { + } + else + { MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS); return true; } } - public void teleportPlayer(final PlotPlayer player, final Plot plot) { + public void teleportPlayer(final PlotPlayer player, final Plot plot) + { MainUtil.teleportPlayer(player, player.getLocation(), plot); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java index 6017b43d7..560fa5414 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java @@ -35,46 +35,54 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "inbox", - description = "Review the comments for a plot", - usage = "/plot inbox [inbox] [delete |clear|page]", - permission = "plots.inbox", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Inbox extends SubCommand { - - public void displayComments(PlotPlayer player, List oldComments, int page) { - if (oldComments == null || oldComments.size() == 0) { +command = "inbox", +description = "Review the comments for a plot", +usage = "/plot inbox [inbox] [delete |clear|page]", +permission = "plots.inbox", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Inbox extends SubCommand +{ + + public void displayComments(final PlotPlayer player, final List oldComments, int page) + { + if ((oldComments == null) || (oldComments.size() == 0)) + { MainUtil.sendMessage(player, C.INBOX_EMPTY); return; } - PlotComment[] comments = oldComments.toArray(new PlotComment[oldComments.size()]); - if (page < 0) { + final 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); - if (page > totalPages) { + if (page > totalPages) + { page = totalPages; } // Only display 12 per page int max = (page * 12) + 12; - if (max > comments.length) { + 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"); PlotComment c; // This might work xD - for (int x = (page * 12); x < max; x++) { + for (int x = (page * 12); x < max; x++) + { c = comments[x]; String color; - if (player.getName().equals(c.senderName)) { + if (player.getName().equals(c.senderName)) + { color = "&a"; } - else { + else + { color = "&7"; } string.append("&8[&7#" + x + "&8][&7" + c.world + ";" + c.id + "&8][&6" + c.senderName + "&8]" + color + c.comment + "\n"); @@ -83,32 +91,43 @@ public class Inbox extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { - + public boolean onCommand(final PlotPlayer player, final String[] args) + { final Plot plot = MainUtil.getPlot(player.getLocation()); - if (args.length == 0) { + if (args.length == 0) + { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); - for (final CommentInbox inbox : CommentManager.inboxes.values()) { - if (inbox.canRead(plot, player)) { - if (!inbox.getComments(plot, new RunnableVal() { + for (final CommentInbox inbox : CommentManager.inboxes.values()) + { + if (inbox.canRead(plot, player)) + { + if (!inbox.getComments(plot, new RunnableVal() + { @Override - public void run() { - if (value != null) { + public void run() + { + if (value != null) + { int total = 0; int unread = 0; - for (PlotComment comment : (ArrayList) value) { + for (final PlotComment comment : (ArrayList) value) + { total++; - if (comment.timestamp > CommentManager.getTimestamp(player, inbox.toString())) { + if (comment.timestamp > CommentManager.getTimestamp(player, inbox.toString())) + { unread++; } } - if (total != 0) { + if (total != 0) + { String color; - if (unread > 0) { + if (unread > 0) + { color = "&c"; } - else { + else + { color = ""; } sendMessage(player, C.INBOX_ITEM, color + inbox.toString() + " (" + total + "/" + unread + ")"); @@ -117,7 +136,8 @@ public class Inbox extends SubCommand { } sendMessage(player, C.INBOX_ITEM, inbox.toString()); } - })) { + })) + { sendMessage(player, C.INBOX_ITEM, inbox.toString()); } } @@ -125,94 +145,120 @@ public class Inbox extends SubCommand { return false; } final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); - if (inbox == null) { - sendMessage(player, C.INVALID_INBOX, StringMan.join(CommentManager.inboxes.keySet(),", ")); + if (inbox == null) + { + sendMessage(player, C.INVALID_INBOX, StringMan.join(CommentManager.inboxes.keySet(), ", ")); return false; } player.setMeta("inbox:" + inbox.toString(), System.currentTimeMillis()); final int page; - if (args.length > 1) { - switch (args[1].toLowerCase()) { - case "delete": { - if (!inbox.canModify(plot, player)) { + if (args.length > 1) + { + switch (args[1].toLowerCase()) + { + case "delete": + { + if (!inbox.canModify(plot, player)) + { sendMessage(player, C.NO_PERM_INBOX_MODIFY); return false; } - if (args.length != 3) { + if (args.length != 3) + { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); } final int index; - try { + try + { index = Integer.parseInt(args[2]); - if (index < 1) { + if (index < 1) + { sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); return false; } } - catch (NumberFormatException e) { + catch (final NumberFormatException e) + { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); return false; } - - if (!inbox.getComments(plot, new RunnableVal() { + + if (!inbox.getComments(plot, new RunnableVal() + { @Override - public void run() { - List comments = (List) value; - if (index > comments.size()) { + public void run() + { + final List comments = (List) value; + if (index > comments.size()) + { sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); } - PlotComment comment = comments.get(index - 1); + final PlotComment comment = comments.get(index - 1); inbox.removeComment(plot, comment); plot.getSettings().removeComment(comment); MainUtil.sendMessage(player, C.COMMENT_REMOVED, comment.comment); } - })) { + })) + { sendMessage(player, C.NOT_IN_PLOT); return false; } return true; } - case "clear": { - if (!inbox.canModify(plot, player)) { + case "clear": + { + if (!inbox.canModify(plot, player)) + { sendMessage(player, C.NO_PERM_INBOX_MODIFY); } inbox.clearInbox(plot); - ArrayList comments = plot.getSettings().getComments(inbox.toString()); - if (comments != null) { + final ArrayList comments = plot.getSettings().getComments(inbox.toString()); + if (comments != null) + { plot.getSettings().removeComments(comments); } MainUtil.sendMessage(player, C.COMMENT_REMOVED, "*"); return true; } - default: { - try { - page = Integer.parseInt(args[1]) ; + default: + { + try + { + page = Integer.parseInt(args[1]); } - catch (NumberFormatException e) { + catch (final NumberFormatException e) + { sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); return false; } } } } - else { + else + { page = 1; } - if (!inbox.canRead(plot, player)) { + if (!inbox.canRead(plot, player)) + { sendMessage(player, C.NO_PERM_INBOX); return false; } - if (!inbox.getComments(plot, new RunnableVal() { + if (!inbox.getComments(plot, new RunnableVal() + { @Override - public void run() { - List comments = (List) value; + public void run() + { + final List comments = (List) value; displayComments(player, comments, page); } - })) { - if (plot == null) { + })) + { + if (plot == null) + { sendMessage(player, C.NOT_IN_PLOT); } - else { + else + { sendMessage(player, C.PLOT_UNOWNED); } return false; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/src/main/java/com/intellectualcrafters/plot/commands/Info.java index 7665a3e52..516b8de2f 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Info.java @@ -25,7 +25,6 @@ import java.util.Collection; import java.util.UUID; import java.util.regex.Matcher; -import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; @@ -37,7 +36,6 @@ import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotInventory; import com.intellectualcrafters.plot.object.PlotItemStack; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.PlotWorld; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.StringMan; @@ -46,52 +44,56 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "info", - aliases = {"i"}, - description = "Display plot info", - usage = "/plot info ", - category = CommandCategory.INFO -) -public class Info extends SubCommand { +command = "info", +aliases = { "i" }, +description = "Display plot info", +usage = "/plot info ", +category = CommandCategory.INFO) +public class Info extends SubCommand +{ - public static String getPlayerList(final Collection uuids) { - ArrayList l = new ArrayList<>(uuids); - if ((l == null) || (l.size() < 1)) { - return C.NONE.s(); - } + public static String getPlayerList(final Collection uuids) + { + final ArrayList l = new ArrayList<>(uuids); + if ((l == null) || (l.size() < 1)) { return C.NONE.s(); } final String c = C.PLOT_USER_LIST.s(); final StringBuilder list = new StringBuilder(); - for (int x = 0; x < l.size(); x++) { - if ((x + 1) == l.size()) { + for (int x = 0; x < l.size(); x++) + { + if ((x + 1) == l.size()) + { list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); - } else { + } + else + { list.append(c.replace("%user%", getPlayerName(l.get(x)))); } } return list.toString(); } - public static String getPlayerName(final UUID uuid) { - if (uuid == null) { - return C.UNKNOWN.s(); - } - if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { - return "everyone"; - } + public static String getPlayerName(final UUID uuid) + { + if (uuid == null) { return C.UNKNOWN.s(); } + if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { return "everyone"; } final String name = UUIDHandler.getName(uuid); - if (name == null) { - return "unknown"; - } + if (name == null) { return "unknown"; } return name; } @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + public boolean onCommand(final PlotPlayer player, String[] args) + { String arg = null; Plot plot; - if (args.length > 0) arg = args[0] + ""; - if (arg != null) { - switch (arg) { + if (args.length > 0) + { + arg = args[0] + ""; + } + if (arg != null) + { + switch (arg) + { case "trusted": case "alias": case "inv": @@ -107,49 +109,66 @@ public class Info extends SubCommand { break; default: plot = MainUtil.getPlotFromString(player, arg, false); - if (args.length == 2) { + if (args.length == 2) + { arg = args[1]; } - else { + else + { arg = null; } break; } } - else { + else + { plot = MainUtil.getPlotFromString(player, null, false); } - if (plot == null && arg != null) { + if ((plot == null) && (arg != null)) + { plot = MainUtil.getPlotFromString(player, null, false); } - if (plot == null) { + if (plot == null) + { MainUtil.sendMessage(player, C.NOT_IN_PLOT); return false; } - if (arg != null) { - if (args.length == 1) { + if (arg != null) + { + if (args.length == 1) + { args = new String[0]; } - else { + else + { args = new String[] { args[1] }; } } - if ((args.length == 1) && args[0].equalsIgnoreCase("inv")) { - PlotInventory inv = new PlotInventory(player) { + if ((args.length == 1) && args[0].equalsIgnoreCase("inv")) + { + final PlotInventory inv = new PlotInventory(player) + { @Override - public boolean onClick(int index) { + public boolean onClick(final int index) + { // TODO InfoInventory not implemented yet!!!!!!!! // See plot rating or musicsubcommand on examples return false; } }; - UUID uuid = player.getUUID(); - String name = MainUtil.getName(plot.owner); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", new String[] { "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, "&cAlias: &6" + plot.getSettings().getAlias(), "&cBiome: &6" + plot.getBiome().toString().replaceAll("_", "").toLowerCase(), "&cCan Build: &6" + plot.isAdded(uuid), "&cIs Denied: &6" + plot.isDenied(uuid)})); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", new String[] {"&cAmount: &6" + plot.getTrusted().size(), "&8Click to view a list of the trusted users"})); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", new String[] {"&cAmount: &6" + plot.getMembers().size(), "&8Click to view a list of plot members"})); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", new String[] {"&cDenied", "&cAmount: &6" + plot.getDenied().size(), "&8Click to view a list of denied players"})); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", new String[] {"&cFlags", "&cAmount: &6" + plot.getSettings().flags.size(), "&8Click to view a list of plot flags"})); + final UUID uuid = player.getUUID(); + final String name = MainUtil.getName(plot.owner); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", new String[] { + "&cID: &6" + plot.getId().toString(), + "&cOwner: &6" + name, + "&cAlias: &6" + plot.getSettings().getAlias(), + "&cBiome: &6" + plot.getBiome().toString().replaceAll("_", "").toLowerCase(), + "&cCan Build: &6" + plot.isAdded(uuid), + "&cIs Denied: &6" + plot.isDenied(uuid) })); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", new String[] { "&cAmount: &6" + plot.getTrusted().size(), "&8Click to view a list of the trusted users" })); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", new String[] { "&cAmount: &6" + plot.getMembers().size(), "&8Click to view a list of plot members" })); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", new String[] { "&cDenied", "&cAmount: &6" + plot.getDenied().size(), "&8Click to view a list of denied players" })); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", new String[] { "&cFlags", "&cAmount: &6" + plot.getSettings().flags.size(), "&8Click to view a list of plot flags" })); inv.openInventory(); return true; } @@ -162,27 +181,33 @@ public class Info extends SubCommand { trustedEveryone = (plot.getMembers() != null) && plot.getMembers().contains(DBFunc.everyone); } // Unclaimed? - if (!hasOwner && !containsEveryone && !trustedEveryone) { + if (!hasOwner && !containsEveryone && !trustedEveryone) + { MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y)); return true; } String info = C.PLOT_INFO.s(); - if (arg != null) { + if (arg != null) + { info = getCaption(arg); - if (info == null) { + 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"); return false; } formatAndSend(info, plot.world, plot, player, true); } - else { + else + { formatAndSend(info, plot.world, plot, player, false); } return true; } - private String getCaption(final String string) { - switch (string) { + private String getCaption(final String string) + { + switch (string) + { case "trusted": return C.PLOT_INFO_TRUSTED.s(); case "alias": @@ -208,25 +233,29 @@ public class Info extends SubCommand { } } - private void formatAndSend(String info, final String world, final Plot plot, final PlotPlayer player, final boolean full) { + private void formatAndSend(String info, final String world, final Plot plot, final PlotPlayer player, final boolean full) + { final PlotId id = plot.id; final PlotId id2 = MainUtil.getTopPlot(plot).id; final int num = MainUtil.getPlotSelectionIds(id, id2).size(); final String alias = plot.getSettings().getAlias().length() > 0 ? plot.getSettings().getAlias() : C.NONE.s(); - Location top = MainUtil.getPlotTopLoc(world, plot.id); - Location bot = MainUtil.getPlotBottomLoc(world, plot.id).add(1, 0, 1); + final Location top = MainUtil.getPlotTopLoc(world, plot.id); + final Location bot = MainUtil.getPlotBottomLoc(world, plot.id).add(1, 0, 1); final String biome = BlockManager.manager.getBiome(plot.world, bot.getX() + ((top.getX() - bot.getX()) / 2), bot.getZ() + ((top.getZ() - bot.getZ()) / 2)); final String trusted = getPlayerList(plot.getTrusted()); final String members = getPlayerList(plot.getMembers()); final String denied = getPlayerList(plot.getDenied()); - Flag descriptionFlag = FlagManager.getPlotFlag(plot, "description"); + final Flag descriptionFlag = FlagManager.getPlotFlag(plot, "description"); final String description = descriptionFlag == null ? C.NONE.s() : descriptionFlag.getValueString(); - final String flags = StringMan.replaceFromMap("$2" + (StringMan.join(FlagManager.getPlotFlags(plot.world, plot.getSettings(), true).values(), "").length() > 0 ? StringMan.join(FlagManager.getPlotFlags(plot.world, plot.getSettings(), true).values(), "$1, $2") : C.NONE.s()), C.replacements); + final String flags = StringMan.replaceFromMap( + "$2" + + (StringMan.join(FlagManager.getPlotFlags(plot.world, plot.getSettings(), true).values(), "").length() > 0 ? StringMan.join(FlagManager.getPlotFlags(plot.world, plot.getSettings(), true) + .values(), "$1, $2") : C.NONE.s()), C.replacements); final boolean build = plot.isAdded(player.getUUID()); - String owner = plot.owner == null ? "unowned" : getPlayerList(plot.getOwners()); + final String owner = plot.owner == null ? "unowned" : getPlayerList(plot.getOwners()); info = info.replaceAll("%alias%", alias); info = info.replaceAll("%id%", id.toString()); @@ -242,27 +271,34 @@ public class Info extends SubCommand { info = info.replaceAll("%flags%", Matcher.quoteReplacement(flags)); info = info.replaceAll("%build%", build + ""); info = info.replaceAll("%desc%", "No description set."); - if (info.contains("%rating%")) { + if (info.contains("%rating%")) + { final String newInfo = info; - TaskManager.runTaskAsync(new Runnable() { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { + public void run() + { int max = 10; - if (Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 0) { + if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() > 0)) + { max = 8; } String info; - if (full && Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 1) { + if (full && (Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() > 1)) + { String rating = ""; String prefix = ""; - double[] ratings = MainUtil.getAverageRatings(plot); - for (int i = 0; i < ratings.length; i++) { + final double[] ratings = MainUtil.getAverageRatings(plot); + for (int i = 0; i < ratings.length; i++) + { rating += prefix + Settings.RATING_CATEGORIES.get(i) + "=" + String.format("%.1f", ratings[i]); prefix = ","; } info = newInfo.replaceAll("%rating%", rating); } - else { + else + { info = newInfo.replaceAll("%rating%", String.format("%.1f", MainUtil.getAverageRating(plot)) + "/" + max); } MainUtil.sendMessage(player, C.PLOT_INFO_HEADER); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Kick.java b/src/main/java/com/intellectualcrafters/plot/commands/Kick.java index 4157384c2..661598522 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Kick.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Kick.java @@ -31,38 +31,41 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "kick", - aliases = {"k"}, - description = "Kick a player from your plot", - permission = "plots.kick", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Kick extends SubCommand { +command = "kick", +aliases = { "k" }, +description = "Kick a player from your plot", +permission = "plots.kick", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Kick extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (plot == null || ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.kick"))) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((plot == null) || ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.kick"))) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (args.length != 1) { + if (args.length != 1) + { MainUtil.sendMessage(plr, "&c/plot kick "); return false; } final PlotPlayer player = UUIDHandler.getPlayer(args[0]); - if (player == null) { + if (player == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - Location otherLoc = player.getLocation(); - if (!plr.getLocation().getWorld().equals(otherLoc.getWorld()) || !plot.equals(MainUtil.getPlot(otherLoc))) { + final Location otherLoc = player.getLocation(); + if (!plr.getLocation().getWorld().equals(otherLoc.getWorld()) || !plot.equals(MainUtil.getPlot(otherLoc))) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Limit.java b/src/main/java/com/intellectualcrafters/plot/commands/Limit.java index 583844575..47c949c97 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Limit.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Limit.java @@ -23,7 +23,6 @@ package com.intellectualcrafters.plot.commands; import java.util.UUID; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.UUIDHandler; @@ -31,38 +30,40 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "limit", - permission = "plots.limit", - description = "Set or increment player plot claim limits", - aliases = {"setlimit"}, - usage = "/plot limit ", - category = CommandCategory.DEBUG -) -public class Limit extends SubCommand { +command = "limit", +permission = "plots.limit", +description = "Set or increment player plot claim limits", +aliases = { "setlimit" }, +usage = "/plot limit ", +category = CommandCategory.DEBUG) +public class Limit extends SubCommand +{ - public Limit() { + public Limit() + { requiredArguments = new Argument[] { - Argument.String, - Argument.String + Argument.String, + Argument.String }; } - + @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - UUID uuid = UUIDHandler.getUUID(args[0], null); - if (uuid == null) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final UUID uuid = UUIDHandler.getUUID(args[0], null); + if (uuid == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); - + UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); + // get current plot limit // increase - -// EconHandler.manager.setPermission(op, perm, value); + + // EconHandler.manager.setPermission(op, perm, value); plr.sendMessage("TODO"); - - + return true; } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Load.java b/src/main/java/com/intellectualcrafters/plot/commands/Load.java index d2bb74401..73c066e6e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Load.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Load.java @@ -19,90 +19,106 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "load", - aliases = {"restore"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - description = "Load your plot", - permission = "plots.load", - usage = "/plot restore" -) -public class Load extends SubCommand { +command = "load", +aliases = { "restore" }, +category = CommandCategory.ACTIONS, +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) { - - if (!Settings.METRICS) { + public boolean onCommand(final PlotPlayer plr, final 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"); return false; } final String world = plr.getLocation().getWorld(); - if (!PS.get().isPlotWorld(world)) { - return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); - } + if (!PS.get().isPlotWorld(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } final Plot plot = MainUtil.getPlot(plr.getLocation()); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.load")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.load")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } - - if (args.length != 0) { - if (args.length == 1) { + + if (args.length != 0) + { + if (args.length == 1) + { // TODO load save here - List schematics = (List) plr.getMeta("plot_schematics"); - if (schematics == null) { + final List schematics = (List) plr.getMeta("plot_schematics"); + if (schematics == null) + { // No schematics found: MainUtil.sendMessage(plr, C.LOAD_NULL); return false; } String schem; - try { + try + { schem = schematics.get(Integer.parseInt(args[0]) - 1); } - catch (Exception e) { + catch (final Exception e) + { // use /plot load MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ")"); return false; } final URL url; - try { + try + { url = new URL(Settings.WEB_URL + "saves/" + plr.getUUID() + "/" + schem + ".schematic"); - } catch (MalformedURLException e) { + } + catch (final MalformedURLException e) + { e.printStackTrace(); MainUtil.sendMessage(plr, C.LOAD_FAILED); return false; } - + MainUtil.runners.put(plot, 1); MainUtil.sendMessage(plr, C.GENERATING_COMPONENT); - TaskManager.runTaskAsync(new Runnable() { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - Schematic schematic = SchematicHandler.manager.getSchematic(url); - if (schematic == null) { + public void run() + { + final Schematic schematic = SchematicHandler.manager.getSchematic(url); + if (schematic == null) + { MainUtil.runners.remove(plot); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); return; } - SchematicHandler.manager.paste(schematic, plot, 0, 0, new RunnableVal() { + SchematicHandler.manager.paste(schematic, plot, 0, 0, new RunnableVal() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); - if (this.value) { + if (value) + { sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); } - else { + else + { sendMessage(plr, C.SCHEMATIC_PASTE_FAILED); } } @@ -115,18 +131,22 @@ public class Load extends SubCommand { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot load "); return false; } - + // list schematics - - List schematics = (List) plr.getMeta("plot_schematics"); - if (schematics == null) { + + final List schematics = (List) plr.getMeta("plot_schematics"); + if (schematics == null) + { MainUtil.runners.put(plot, 1); - TaskManager.runTaskAsync(new Runnable() { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - List schematics = SchematicHandler.manager.getSaves(plr.getUUID()); + public void run() + { + final List schematics = SchematicHandler.manager.getSaves(plr.getUUID()); MainUtil.runners.remove(plot); - if (schematics == null || schematics.size() == 0) { + if ((schematics == null) || (schematics.size() == 0)) + { MainUtil.sendMessage(plr, C.LOAD_FAILED); return; } @@ -135,76 +155,91 @@ public class Load extends SubCommand { } }); } - else { + else + { displaySaves(plr, 0); } return true; } - - public void displaySaves(PlotPlayer player, int page) { - List schematics = (List) player.getMeta("plot_schematics"); - for (int i = 0; i < Math.min(schematics.size(), 32); i++) { - try { - String schem = schematics.get(i); - String[] split = schem.split("_"); - if (split.length != 6) { + + public void displaySaves(final PlotPlayer player, final int page) + { + final List schematics = (List) 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("_"); + if (split.length != 6) + { continue; } - 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", ""); + 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 color; - if (PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "").equals(server)) { + if (PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "").equals(server)) + { color = "$4"; } - else { + else + { color = "$1"; } MainUtil.sendMessage(player, "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ";" + id + "$3 | " + color + size + "x" + size); } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); } } MainUtil.sendMessage(player, C.LOAD_LIST); } - - public String secToTime(long time) { - StringBuilder toreturn = new StringBuilder(); + + public String secToTime(long time) + { + final StringBuilder toreturn = new StringBuilder(); int years = 0; int weeks = 0; int days = 0; int hours = 0; int minutes = 0; - if (time>=33868800) { - years = (int) (time/33868800); - time-=years*33868800; - toreturn.append(years+"y "); + if (time >= 33868800) + { + years = (int) (time / 33868800); + time -= years * 33868800; + toreturn.append(years + "y "); } - if (time>=604800) { - weeks = (int) (time/604800); - time-=weeks*604800; - toreturn.append(weeks+"w "); + if (time >= 604800) + { + weeks = (int) (time / 604800); + time -= weeks * 604800; + toreturn.append(weeks + "w "); } - if (time>=86400) { - days = (int) (time/86400); - time-=days*86400; - toreturn.append(days+"d "); + if (time >= 86400) + { + days = (int) (time / 86400); + time -= days * 86400; + toreturn.append(days + "d "); } - if (time>=3600) { - hours = (int) (time/3600); - time-=hours*3600; - toreturn.append(hours+"h "); + if (time >= 3600) + { + hours = (int) (time / 3600); + time -= hours * 3600; + toreturn.append(hours + "h "); } - if (time>=60) { - minutes = (int) (time/60); - time-=minutes*60; - toreturn.append(minutes+"m "); + if (time >= 60) + { + minutes = (int) (time / 60); + time -= minutes * 60; + toreturn.append(minutes + "m "); } - if (toreturn.equals("")||time>0){ - toreturn.append((time)+"s "); + if (toreturn.equals("") || (time > 0)) + { + toreturn.append((time) + "s "); } return toreturn.toString().trim(); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index 69940baac..52b664fca 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -1,462 +1,552 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.commands; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.helpmenu.HelpMenu; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandHandlingOutput; -import com.plotsquared.general.commands.CommandManager; - -/** - * PlotSquared command class - * - * @author Citymonstret - */ -public class MainCommand extends CommandManager { - - private static MainCommand instance; - - public static MainCommand getInstance() { - if (instance == null) { - instance = new MainCommand(); - } - return instance; - } - - private MainCommand() { - super(null, new ArrayList>()); - instance = this; - createCommand(new Buy()); - createCommand(new Save()); - createCommand(new Load()); - createCommand(new Unclaim()); - createCommand(new Confirm()); - createCommand(new Template()); - createCommand(new Download()); - createCommand(new Update()); - createCommand(new Template()); - createCommand(new Setup()); - createCommand(new DebugFill()); - createCommand(new DebugSaveTest()); - createCommand(new DebugLoadTest()); - createCommand(new CreateRoadSchematic()); - createCommand(new DebugAllowUnsafe()); - createCommand(new RegenAllRoads()); - createCommand(new DebugClear()); - createCommand(new Claim()); - createCommand(new Auto()); - createCommand(new Home()); - createCommand(new Visit()); - createCommand(new TP()); - createCommand(new Set()); - createCommand(new Toggle()); - createCommand(new Clear()); - createCommand(new Delete()); - createCommand(new SetOwner()); - createCommand(new Trust()); - createCommand(new Add()); - createCommand(new Deny()); - createCommand(new Untrust()); - createCommand(new Remove()); - createCommand(new Undeny()); - createCommand(new Info()); - createCommand(new list()); - createCommand(new Help()); - createCommand(new Debug()); - createCommand(new SchematicCmd()); - createCommand(new plugin()); - createCommand(new Purge()); - createCommand(new Reload()); - createCommand(new Merge()); - createCommand(new DebugPaste()); - createCommand(new Unlink()); - createCommand(new Kick()); - createCommand(new Rate()); - createCommand(new DebugClaimTest()); - createCommand(new Inbox()); - createCommand(new Comment()); - createCommand(new Database()); - createCommand(new Swap()); - createCommand(new MusicSubcommand()); - createCommand(new DebugRoadRegen()); - createCommand(new Trust()); - createCommand(new DebugExec()); - createCommand(new FlagCmd()); - createCommand(new Target()); - createCommand(new DebugFixFlags()); - createCommand(new Move()); - createCommand(new Condense()); - createCommand(new Condense()); - createCommand(new Copy()); - createCommand(new Chat()); - createCommand(new Trim()); - createCommand(new Done()); - createCommand(new Continue()); - createCommand(new BO3()); - if (Settings.ENABLE_CLUSTERS) { - MainCommand.getInstance().addCommand(new Cluster()); - } - } - - public static boolean no_permission(final PlotPlayer player, final String permission) { - MainUtil.sendMessage(player, C.NO_PERMISSION, permission); - return false; - } - - public static List> getCommandAndAliases(final CommandCategory category, final PlotPlayer player) { - List> commands = new ArrayList<>(); - for (Command command : getInstance().getCommands()) { - if (category != null && !command.getCategory().equals(category)) { - continue; - } - if (player != null && !Permissions.hasPermission(player, command.getPermission())) { - continue; - } - commands.add(command); - } - return commands; - } - - public static List> getCommands(final CommandCategory category, final PlotPlayer player) { - List> commands = new ArrayList<>(); - for (Command command : new HashSet<>(getInstance().getCommands())) { - if (category != null && !command.getCategory().equals(category)) { - continue; - } - if (player != null && !Permissions.hasPermission(player, command.getPermission())) { - continue; - } - commands.add(command); - } - return commands; - } - -//// public static List helpMenu(final PlotPlayer player, final CommandCategory category, int page) { -// List> commands; -// // commands = getCommands(category, player); -// // final int totalPages = ((int) Math.ceil(12 * (commands.size()) / -// // 100)); -// final int perPage = 5; -// // final int totalPages = (commands.size() / perPage) + (commands.size() % perPage == 0 ? 0 : 1); -// // if (page > totalPages) { -// // page = totalPages; -// // } -// int max = (page * perPage) + perPage; -// // if (max > commands.size()) { -// // max = commands.size(); -// // } -// final List help = new ArrayList<>(); -// help.add(C.HELP_HEADER.s()); -// // HELP_PAGE_HEADER("&cCategory: &6%category%&c, Page: %current%&c/&6%max%&c, Displaying: &6%dis%&c/&6%total%"), -// // help.add(C.HELP_PAGE_HEADER.s().replace("%category%", category == null ? "All" : category.toString()).replace("%current%", "" + (page + 1)).replace("%max%", "" + (totalPages)).replace("%dis%", "" + perPage).replace("%total%", "" + commands.size())); -// Command cmd; -// // HELP_CATEGORY("&cCategory: &6%category%&c, Page: %current%&c/&6%max%&c, Displaying: &6%dis%&c/&6%total%"), -// // help.add(C.HELP_CATEGORY.s().replace("%category%", category == null ? "All" : category.toString()).replace("%current%", "" + (page + 1)).replace("%max%", "" + (totalPages)).replace("%dis%", "" + perPage).replace("%total%", "" + commands.size())); -// // Command cmd; -// final int start = page * perPage; -// for (int x = start; x < max; x++) { -// // cmd = commands.get(x); -// String s = C.HELP_ITEM.s(); -// if (cmd.getAliases().size() > 0) { -// s = s.replace("%alias%", StringMan.join(cmd.getAliases(), "|")); -// } -// else { -// s = s.replace("%alias%", ""); -// } -// s = s.replace("%usage%", cmd.getUsage().contains("plot") ? cmd.getUsage() : "/plot " + cmd.getUsage()).replace("%cmd%", cmd.getCommand()).replace("%desc%", cmd.getDescription()).replace("[]", ""); -// help.add(s); -// } -// if (help.size() < 2) { -// help.add(C.NO_COMMANDS.s()); -// } -// return help; -// } -// - 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 (CommandCategory c : CommandCategory.values()) { - if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { - catEnum = c; - cat = c.name(); - break; - } - } - if (catEnum == null) { - cat = null; - } - } - } - if (cat == null && page == 0) { - final 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())); - } - 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()); - MainUtil.sendMessage(player, builder.toString(), false); - return; - } - page--; - new HelpMenu(player) - .setCategory(catEnum) - .getCommands() - .generateMaxPages() - .generatePage(page, label) - .render(); - } - - public static boolean onCommand(final PlotPlayer player, final String cmd, String... args) { - int help_index = -1; - String category = null; - if (args.length == 0) { - help_index = 0; - } - else if (StringMan.isEqualIgnoreCaseToAny(args[0], "he", "help", "?")) { - help_index = 0; - switch (args.length) { - case 3: { - category = args[1]; - if (MathMan.isInteger(args[2])) { - try { - help_index = Integer.parseInt(args[2]); - } - catch (NumberFormatException e) { - help_index = 1; - } - } - break; - } - case 2: { - if (MathMan.isInteger(args[1])) { - category = null; - try { - help_index = Integer.parseInt(args[1]); - } catch(NumberFormatException e) { - help_index = 1; - } - } else { - help_index = 1; - category = args[1]; - } - break; - } - } - } - else if (args.length == 1 && MathMan.isInteger(args[args.length - 1])) { - try { - help_index = Integer.parseInt(args[args.length - 1]); - } - catch (NumberFormatException e) {} - } - else if (ConsolePlayer.isConsole(player) && args.length >= 2) { - String[] split = args[0].split(";"); - String world; - PlotId id; - if (split.length == 2) { - world = player.getLocation().getWorld(); - id = PlotId.fromString(split[0] + ";" + split[1]); - } - else if (split.length == 3) { - world = split[0]; - id = PlotId.fromString(split[1] + ";" + split[2]); - } - else { - id = null; - world = null; - } - if (id != null && PS.get().isPlotWorld(world)) { - Plot plot = MainUtil.getPlot(world, id); - if (plot != null) { - player.teleport(MainUtil.getPlotCenter(plot)); - args = Arrays.copyOfRange(args, 1, args.length); - } - } - - } - if (help_index != -1) { - displayHelp(player, category, help_index, cmd); - return true; - } - StringBuilder builder = new StringBuilder(cmd).append(" "); - Iterator iterator = Arrays.asList(args).iterator(); - while (iterator.hasNext()) { - builder.append(iterator.next()); - if (iterator.hasNext()) { - builder.append(" "); - } - } - getInstance().handle(player, builder.toString()); - return true; - } - - @Override - public int handle(PlotPlayer plr, String input) { - String[] parts = input.split(" "); - String[] args; - String label; - if (parts.length == 1) { - label = null; - args = new String[0]; - } else { - label = parts[1]; - args = new String[parts.length - 2]; - System.arraycopy(parts, 2, args, 0, args.length); - } - Command cmd; - if (label != null) { - cmd = getInstance().commands.get(label); - } - else { - cmd = null; - } - if (cmd == null) { - MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); - { - List> cmds = getCommands(null, plr); - if (label == null || cmds.size() == 0) { - MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); - } - else { - HashSet setargs = new HashSet<>(args.length + 1); - for (String arg : args) { - setargs.add(arg.toLowerCase()); - } - setargs.add(label.toLowerCase()); - String[] allargs = setargs.toArray(new String[setargs.size()]); - int best = 0; - for (Command current : cmds) { - if (current.getUsage() != null) { - int count = 0; - for (String word : new HashSet(Arrays.asList((current.getUsage() + " " + current.getPermission() + " " + current.getCategory().name()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) { - for (int i = 0; i < allargs.length; i++) { - String arg = allargs[i]; - if (best - count - (allargs.length - i) * 3 >= 0) { - continue; - } - if (StringMan.isEqual(arg, word)) { - count+=3; - } - else if (word.length() > arg.length() && word.contains(arg)) { - count+=2; - } - } - } - for (String word : new HashSet(Arrays.asList((current.getDescription()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) { - for (int i = 0; i < allargs.length; i++) { - String arg = allargs[i]; - if (best - count - (allargs.length - i) * 2 >= 0) { - continue; - } - if (StringMan.isEqual(arg, word)) { - count+=2; - } - else if (word.length() > arg.length() && word.contains(arg)) { - count++; - } - } - } - if (count > best) { - best = count; - cmd = current; - } - } - } - if (cmd == null) { - cmd = new StringComparison<>(label, getCommandAndAliases(null, plr)).getMatchObject(); - } - MainUtil.sendMessage(plr, C.DID_YOU_MEAN, cmd.getUsage().replaceAll("\\{label\\}", parts[0])); - } - } - return CommandHandlingOutput.NOT_FOUND; - } - if (!cmd.getRequiredType().allows(plr)) { - if (ConsolePlayer.isConsole(plr)) { - MainUtil.sendMessage(plr, C.IS_CONSOLE); - } else { - MainUtil.sendMessage(plr, C.NOT_CONSOLE); - } - return CommandHandlingOutput.CALLER_OF_WRONG_TYPE; - } - if (!Permissions.hasPermission(plr, cmd.getPermission())) { - MainUtil.sendMessage(plr, C.NO_PERMISSION, cmd.getPermission()); - return CommandHandlingOutput.NOT_PERMITTED; - } - Argument[] requiredArguments = cmd.getRequiredArguments(); - if (requiredArguments != null && requiredArguments.length > 0) { - boolean success = true; - if (args.length < requiredArguments.length) { - success = false; - } else { - for (int i = 0; i < requiredArguments.length; i++) { - if (requiredArguments[i].parse(args[i]) == null) { - success = false; - break; - } - } - } - if (!success) { - C.COMMAND_SYNTAX.send(plr, cmd.getUsage()); - return CommandHandlingOutput.WRONG_USAGE; - } - } - try { - boolean result = cmd.onCommand(plr, args); - if (!result) { - String usage = cmd.getUsage(); - // Unecessary! -// if (usage != null && !usage.isEmpty()) { -// MainUtil.sendMessage(plr, usage); -// } - return CommandHandlingOutput.WRONG_USAGE; - } - } catch (final Throwable t) { - t.printStackTrace(); - return CommandHandlingOutput.ERROR; - } - return CommandHandlingOutput.SUCCESS; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.commands; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.object.ConsolePlayer; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.MathMan; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.StringComparison; +import com.intellectualcrafters.plot.util.StringMan; +import com.intellectualcrafters.plot.util.helpmenu.HelpMenu; +import com.plotsquared.general.commands.Argument; +import com.plotsquared.general.commands.Command; +import com.plotsquared.general.commands.CommandHandlingOutput; +import com.plotsquared.general.commands.CommandManager; + +/** + * PlotSquared command class + * + */ +public class MainCommand extends CommandManager +{ + + private static MainCommand instance; + + public static MainCommand getInstance() + { + if (instance == null) + { + instance = new MainCommand(); + } + return instance; + } + + private MainCommand() + { + super(null, new ArrayList>()); + instance = this; + createCommand(new Buy()); + createCommand(new Save()); + createCommand(new Load()); + createCommand(new Unclaim()); + createCommand(new Confirm()); + createCommand(new Template()); + createCommand(new Download()); + createCommand(new Update()); + createCommand(new Template()); + createCommand(new Setup()); + createCommand(new DebugFill()); + createCommand(new DebugSaveTest()); + createCommand(new DebugLoadTest()); + createCommand(new CreateRoadSchematic()); + createCommand(new DebugAllowUnsafe()); + createCommand(new RegenAllRoads()); + createCommand(new DebugClear()); + createCommand(new Claim()); + createCommand(new Auto()); + createCommand(new Home()); + createCommand(new Visit()); + createCommand(new TP()); + createCommand(new Set()); + createCommand(new Toggle()); + createCommand(new Clear()); + createCommand(new Delete()); + createCommand(new SetOwner()); + createCommand(new Trust()); + createCommand(new Add()); + createCommand(new Deny()); + createCommand(new Untrust()); + createCommand(new Remove()); + createCommand(new Undeny()); + createCommand(new Info()); + createCommand(new list()); + createCommand(new Help()); + createCommand(new Debug()); + createCommand(new SchematicCmd()); + createCommand(new plugin()); + createCommand(new Purge()); + createCommand(new Reload()); + createCommand(new Merge()); + createCommand(new DebugPaste()); + createCommand(new Unlink()); + createCommand(new Kick()); + createCommand(new Rate()); + createCommand(new DebugClaimTest()); + createCommand(new Inbox()); + createCommand(new Comment()); + createCommand(new Database()); + createCommand(new Swap()); + createCommand(new MusicSubcommand()); + createCommand(new DebugRoadRegen()); + createCommand(new Trust()); + createCommand(new DebugExec()); + createCommand(new FlagCmd()); + createCommand(new Target()); + createCommand(new DebugFixFlags()); + createCommand(new Move()); + createCommand(new Condense()); + createCommand(new Condense()); + createCommand(new Copy()); + createCommand(new Chat()); + createCommand(new Trim()); + createCommand(new Done()); + createCommand(new Continue()); + createCommand(new BO3()); + if (Settings.ENABLE_CLUSTERS) + { + MainCommand.getInstance().addCommand(new Cluster()); + } + } + + public static boolean no_permission(final PlotPlayer player, final 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()) + { + if ((category != null) && !command.getCategory().equals(category)) + { + continue; + } + if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) + { + continue; + } + commands.add(command); + } + 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())) + { + if ((category != null) && !command.getCategory().equals(category)) + { + continue; + } + if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) + { + continue; + } + commands.add(command); + } + return commands; + } + + //// public static List helpMenu(final PlotPlayer player, final CommandCategory category, int page) { + // List> commands; + // // commands = getCommands(category, player); + // // final int totalPages = ((int) Math.ceil(12 * (commands.size()) / + // // 100)); + // final int perPage = 5; + // // final int totalPages = (commands.size() / perPage) + (commands.size() % perPage == 0 ? 0 : 1); + // // if (page > totalPages) { + // // page = totalPages; + // // } + // int max = (page * perPage) + perPage; + // // if (max > commands.size()) { + // // max = commands.size(); + // // } + // final List help = new ArrayList<>(); + // help.add(C.HELP_HEADER.s()); + // // HELP_PAGE_HEADER("&cCategory: &6%category%&c, Page: %current%&c/&6%max%&c, Displaying: &6%dis%&c/&6%total%"), + // // help.add(C.HELP_PAGE_HEADER.s().replace("%category%", category == null ? "All" : category.toString()).replace("%current%", "" + (page + 1)).replace("%max%", "" + (totalPages)).replace("%dis%", "" + perPage).replace("%total%", "" + commands.size())); + // Command cmd; + // // HELP_CATEGORY("&cCategory: &6%category%&c, Page: %current%&c/&6%max%&c, Displaying: &6%dis%&c/&6%total%"), + // // help.add(C.HELP_CATEGORY.s().replace("%category%", category == null ? "All" : category.toString()).replace("%current%", "" + (page + 1)).replace("%max%", "" + (totalPages)).replace("%dis%", "" + perPage).replace("%total%", "" + commands.size())); + // // Command cmd; + // final int start = page * perPage; + // for (int x = start; x < max; x++) { + // // cmd = commands.get(x); + // String s = C.HELP_ITEM.s(); + // if (cmd.getAliases().size() > 0) { + // s = s.replace("%alias%", StringMan.join(cmd.getAliases(), "|")); + // } + // else { + // s = s.replace("%alias%", ""); + // } + // s = s.replace("%usage%", cmd.getUsage().contains("plot") ? cmd.getUsage() : "/plot " + cmd.getUsage()).replace("%cmd%", cmd.getCommand()).replace("%desc%", cmd.getDescription()).replace("[]", ""); + // help.add(s); + // } + // if (help.size() < 2) { + // help.add(C.NO_COMMANDS.s()); + // } + // return help; + // } + // + public static void displayHelp(final PlotPlayer player, String cat, int page, final String label) + { + CommandCategory catEnum = null; + if (cat != null) + { + if (StringMan.isEqualIgnoreCase(cat, "all")) + { + catEnum = null; + } + else + { + for (final CommandCategory c : CommandCategory.values()) + { + if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) + { + catEnum = c; + cat = c.name(); + break; + } + } + if (catEnum == null) + { + cat = null; + } + } + } + if ((cat == null) && (page == 0)) + { + final 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())); + } + 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()); + MainUtil.sendMessage(player, builder.toString(), false); + return; + } + page--; + new HelpMenu(player) + .setCategory(catEnum) + .getCommands() + .generateMaxPages() + .generatePage(page, label) + .render(); + } + + public static boolean onCommand(final PlotPlayer player, final String cmd, String... args) + { + int help_index = -1; + String category = null; + if (args.length == 0) + { + help_index = 0; + } + else if (StringMan.isEqualIgnoreCaseToAny(args[0], "he", "help", "?")) + { + help_index = 0; + switch (args.length) + { + case 3: + { + category = args[1]; + if (MathMan.isInteger(args[2])) + { + try + { + help_index = Integer.parseInt(args[2]); + } + catch (final NumberFormatException e) + { + help_index = 1; + } + } + break; + } + case 2: + { + if (MathMan.isInteger(args[1])) + { + category = null; + try + { + help_index = Integer.parseInt(args[1]); + } + catch (final NumberFormatException e) + { + help_index = 1; + } + } + else + { + help_index = 1; + category = args[1]; + } + break; + } + } + } + else if ((args.length == 1) && MathMan.isInteger(args[args.length - 1])) + { + try + { + help_index = Integer.parseInt(args[args.length - 1]); + } + catch (final NumberFormatException e) + {} + } + else if (ConsolePlayer.isConsole(player) && (args.length >= 2)) + { + final String[] split = args[0].split(";"); + String world; + PlotId id; + if (split.length == 2) + { + world = player.getLocation().getWorld(); + id = PlotId.fromString(split[0] + ";" + split[1]); + } + else if (split.length == 3) + { + world = split[0]; + id = PlotId.fromString(split[1] + ";" + split[2]); + } + else + { + id = null; + world = null; + } + if ((id != null) && PS.get().isPlotWorld(world)) + { + final Plot plot = MainUtil.getPlot(world, id); + if (plot != null) + { + player.teleport(MainUtil.getPlotCenter(plot)); + args = Arrays.copyOfRange(args, 1, args.length); + } + } + + } + if (help_index != -1) + { + displayHelp(player, category, help_index, cmd); + return true; + } + final StringBuilder builder = new StringBuilder(cmd).append(" "); + final Iterator iterator = Arrays.asList(args).iterator(); + while (iterator.hasNext()) + { + builder.append(iterator.next()); + if (iterator.hasNext()) + { + builder.append(" "); + } + } + getInstance().handle(player, builder.toString()); + return true; + } + + @Override + public int handle(final PlotPlayer plr, final String input) + { + final String[] parts = input.split(" "); + String[] args; + String label; + if (parts.length == 1) + { + label = null; + args = new String[0]; + } + else + { + label = parts[1]; + args = new String[parts.length - 2]; + System.arraycopy(parts, 2, args, 0, args.length); + } + Command cmd; + if (label != null) + { + cmd = getInstance().commands.get(label); + } + else + { + cmd = null; + } + if (cmd == null) + { + MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); + { + final List> cmds = getCommands(null, plr); + if ((label == null) || (cmds.size() == 0)) + { + MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); + } + else + { + final HashSet setargs = new HashSet<>(args.length + 1); + for (final String arg : args) + { + setargs.add(arg.toLowerCase()); + } + setargs.add(label.toLowerCase()); + final String[] allargs = setargs.toArray(new String[setargs.size()]); + int best = 0; + for (final Command current : cmds) + { + if (current.getUsage() != null) + { + int count = 0; + for (final String word : new HashSet(Arrays.asList((current.getUsage() + " " + current.getPermission() + " " + current.getCategory().name()).toLowerCase() + .replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) + { + for (int i = 0; i < allargs.length; i++) + { + final String arg = allargs[i]; + if ((best - count - ((allargs.length - i) * 3)) >= 0) + { + continue; + } + if (StringMan.isEqual(arg, word)) + { + count += 3; + } + else if ((word.length() > arg.length()) && word.contains(arg)) + { + count += 2; + } + } + } + for (final String word : new HashSet(Arrays.asList((current.getDescription()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim() + .replaceAll("\\s+", " ").split(" ")))) + { + for (int i = 0; i < allargs.length; i++) + { + final String arg = allargs[i]; + if ((best - count - ((allargs.length - i) * 2)) >= 0) + { + continue; + } + if (StringMan.isEqual(arg, word)) + { + count += 2; + } + else if ((word.length() > arg.length()) && word.contains(arg)) + { + count++; + } + } + } + if (count > best) + { + best = count; + cmd = current; + } + } + } + if (cmd == null) + { + cmd = new StringComparison<>(label, getCommandAndAliases(null, plr)).getMatchObject(); + } + MainUtil.sendMessage(plr, C.DID_YOU_MEAN, cmd.getUsage().replaceAll("\\{label\\}", parts[0])); + } + } + return CommandHandlingOutput.NOT_FOUND; + } + if (!cmd.getRequiredType().allows(plr)) + { + if (ConsolePlayer.isConsole(plr)) + { + MainUtil.sendMessage(plr, C.IS_CONSOLE); + } + else + { + MainUtil.sendMessage(plr, C.NOT_CONSOLE); + } + return CommandHandlingOutput.CALLER_OF_WRONG_TYPE; + } + if (!Permissions.hasPermission(plr, cmd.getPermission())) + { + MainUtil.sendMessage(plr, C.NO_PERMISSION, cmd.getPermission()); + return CommandHandlingOutput.NOT_PERMITTED; + } + final Argument[] requiredArguments = cmd.getRequiredArguments(); + if ((requiredArguments != null) && (requiredArguments.length > 0)) + { + boolean success = true; + if (args.length < requiredArguments.length) + { + success = false; + } + else + { + for (int i = 0; i < requiredArguments.length; i++) + { + if (requiredArguments[i].parse(args[i]) == null) + { + success = false; + break; + } + } + } + if (!success) + { + C.COMMAND_SYNTAX.send(plr, cmd.getUsage()); + return CommandHandlingOutput.WRONG_USAGE; + } + } + try + { + final boolean result = cmd.onCommand(plr, args); + if (!result) + { + cmd.getUsage(); + // Unecessary! + // if (usage != null && !usage.isEmpty()) { + // MainUtil.sendMessage(plr, usage); + // } + return CommandHandlingOutput.WRONG_USAGE; + } + } + catch (final Throwable t) + { + t.printStackTrace(); + return CommandHandlingOutput.ERROR; + } + return CommandHandlingOutput.SUCCESS; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/src/main/java/com/intellectualcrafters/plot/commands/Merge.java index 64c8b655c..839f2b4fb 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Merge.java @@ -42,22 +42,24 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "merge", - aliases = {"m"}, - description = "Merge the plot you are standing on, with another plot", - permission = "plots.merge", - usage = "/plot merge [direction]", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Merge extends SubCommand { +command = "merge", +aliases = { "m" }, +description = "Merge the plot you are standing on, with another plot", +permission = "plots.merge", +usage = "/plot merge [direction]", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Merge extends SubCommand +{ public final static String[] values = new String[] { "north", "east", "south", "west" }; public final static String[] aliases = new String[] { "n", "e", "s", "w" }; - public static String direction(float yaw) { + public static String direction(float yaw) + { yaw = yaw / 90; final int i = Math.round(yaw); - switch (i) { + switch (i) + { case -4: case 0: case 4: @@ -77,25 +79,28 @@ public class Merge extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final Location loc = plr.getLocationFull(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if ((plot == null) || !plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((plot == null) || !plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } final boolean admin = Permissions.hasPermission(plr, "plots.admin.command.merge"); - if (!plot.isOwner(plr.getUUID()) && !admin) { + if (!plot.isOwner(plr.getUUID()) && !admin) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } int direction = -1; - if (args.length == 0) { - switch (direction(plr.getLocationFull().getYaw())) { + if (args.length == 0) + { + switch (direction(plr.getLocationFull().getYaw())) + { case "NORTH": direction = 0; break; @@ -110,20 +115,25 @@ public class Merge extends SubCommand { break; } } - else { - if (args[0].equalsIgnoreCase("all")) { - plot.autoMerge(args.length != 2 || !args[1].equalsIgnoreCase("false")); + else + { + if (args[0].equalsIgnoreCase("all")) + { + plot.autoMerge((args.length != 2) || !args[1].equalsIgnoreCase("false")); MainUtil.sendMessage(plr, C.SUCCESS_MERGE); return true; } - for (int i = 0; i < values.length; i++) { - if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { + for (int i = 0; i < values.length; i++) + { + if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) + { direction = i; break; } } } - if (direction == -1) { + if (direction == -1) + { MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan.join(values, C.BLOCK_LIST_SEPARATER.s())); MainUtil.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); return false; @@ -132,7 +142,8 @@ public class Merge extends SubCommand { PlotId top = MainUtil.getTopPlot(plot).id; ArrayList selPlots; final String world = loc.getWorld(); - switch (direction) { + switch (direction) + { case 0: // north = -y selPlots = MainUtil.getMaxPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); break; @@ -148,8 +159,9 @@ public class Merge extends SubCommand { default: return false; } - int size = selPlots.size(); - if (Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS) < size) { + final int size = selPlots.size(); + if (Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS) < size) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.merge." + size); return false; } @@ -164,20 +176,24 @@ public class Merge extends SubCommand { final ArrayList plots = MainUtil.getMaxPlotSelectionIds(world, bot, top); boolean multiMerge = false; final HashSet multiUUID = new HashSet(); - HashSet multiPlots = new HashSet<>(); + final HashSet multiPlots = new HashSet<>(); final UUID u1 = plot.owner; - for (final PlotId myid : plots) { + for (final PlotId myid : plots) + { final Plot myplot = PS.get().getPlot(world, myid); - if (myplot == null || myplot.owner == null) { + if ((myplot == null) || (myplot.owner == null)) + { MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); return false; } - UUID u2 = myplot.owner; - if (u2.equals(u1)) { + final UUID u2 = myplot.owner; + if (u2.equals(u1)) + { continue; } - PlotPlayer p2 = UUIDHandler.getPlayer(u2); - if (p2 == null) { + final PlotPlayer p2 = UUIDHandler.getPlayer(u2); + if (p2 == null) + { MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); return false; } @@ -185,30 +201,40 @@ public class Merge extends SubCommand { multiPlots.add(myid); multiUUID.add(u2); } - if (multiMerge) { - if (!Permissions.hasPermission(plr, C.PERMISSION_MERGE_OTHER)) { + if (multiMerge) + { + if (!Permissions.hasPermission(plr, C.PERMISSION_MERGE_OTHER)) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, C.PERMISSION_MERGE_OTHER.s()); return false; } - for (final UUID uuid : multiUUID) { - PlotPlayer accepter = UUIDHandler.getPlayer(uuid); - CmdConfirm.addPending(accepter, C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", plr.getName()), new Runnable() { + for (final UUID uuid : multiUUID) + { + final PlotPlayer accepter = UUIDHandler.getPlayer(uuid); + CmdConfirm.addPending(accepter, C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", plr.getName()), new Runnable() + { @Override - public void run() { - PlotPlayer accepter = UUIDHandler.getPlayer(uuid); + public void run() + { + final PlotPlayer accepter = UUIDHandler.getPlayer(uuid); multiUUID.remove(uuid); - if (multiUUID.size() == 0) { - PlotPlayer pp = UUIDHandler.getPlayer(u1); - if (pp == null) { + if (multiUUID.size() == 0) + { + final PlotPlayer pp = UUIDHandler.getPlayer(u1); + if (pp == null) + { sendMessage(accepter, C.MERGE_NOT_VALID); return; } final PlotWorld plotWorld = PS.get().getPlotWorld(world); - if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) { + if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) + { double cost = plotWorld.MERGE_PRICE; cost = plots.size() * cost; - if (cost > 0d) { - if (EconHandler.manager.getMoney(plr) < cost) { + if (cost > 0d) + { + if (EconHandler.manager.getMoney(plr) < cost) + { sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); return; } @@ -217,7 +243,8 @@ public class Merge extends SubCommand { } } final boolean result = EventUtil.manager.callMerge(world, plot, plots); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, "&cMerge has been cancelled"); return; } @@ -233,11 +260,14 @@ public class Merge extends SubCommand { return true; } final PlotWorld plotWorld = PS.get().getPlotWorld(world); - if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) { + if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) + { double cost = plotWorld.MERGE_PRICE; cost = plots.size() * cost; - if (cost > 0d) { - if (EconHandler.manager.getMoney(plr) < cost) { + if (cost > 0d) + { + if (EconHandler.manager.getMoney(plr) < cost) + { sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); return false; } @@ -246,7 +276,8 @@ public class Merge extends SubCommand { } } final boolean result = EventUtil.manager.callMerge(world, plot, plots); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, "&cMerge has been cancelled"); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Move.java b/src/main/java/com/intellectualcrafters/plot/commands/Move.java index e735472a0..db03a384e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Move.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Move.java @@ -33,68 +33,79 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "move", - description = "Move a plot", - aliases = {"debugmove"}, - permission = "plots.move", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Move extends SubCommand { +command = "move", +description = "Move a plot", +aliases = { "debugmove" }, +permission = "plots.move", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Move extends SubCommand +{ - public Move() { + public Move() + { requiredArguments = new Argument[] { - Argument.PlotID + Argument.PlotID }; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + final Location loc = plr.getLocation(); final Plot plot1 = MainUtil.getPlot(loc); - if (plot1 == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot1.isAdded(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) { + if (plot1 == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot1.isAdded(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } final String world = loc.getWorld(); final PlotId plot2id = MainUtil.parseId(args[0]); - if ((plot2id == null)) { + if ((plot2id == null)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot move "); return false; } String world2; - if (args.length == 2) { - PlotWorld other = PS.get().getPlotWorld(args[1]); - PlotWorld current = PS.get().getPlotWorld(loc.getWorld()); - if (other == null || current == null || !other.equals(current)) { + if (args.length == 2) + { + final PlotWorld other = PS.get().getPlotWorld(args[1]); + final PlotWorld current = PS.get().getPlotWorld(loc.getWorld()); + if ((other == null) || (current == null) || !other.equals(current)) + { MainUtil.sendMessage(plr, C.PLOTWORLD_INCOMPATIBLE); return false; } - world2 = other.worldname; + world2 = other.worldname; } - else { - world2 = world; + else + { + world2 = world; } - Plot plot2 = MainUtil.getPlot(world2, plot2id); - - if (plot1.equals(plot2)) { + final Plot plot2 = MainUtil.getPlot(world2, plot2id); + + if (plot1.equals(plot2)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot move "); return false; } - if (MainUtil.move(plot1, plot2, new Runnable() { + if (MainUtil.move(plot1, plot2, new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.sendMessage(plr, C.MOVE_SUCCESS); } - })) { + })) + { return true; - } else { + } + else + { MainUtil.sendMessage(plr, C.REQUIRES_UNOWNED); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java b/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java index 5a03c8f6d..574e3c282 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java @@ -34,53 +34,60 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "music", - permission = "plots.music", - description = "Player music in a plot", - usage = "/plot music", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class MusicSubcommand extends SubCommand { +command = "music", +permission = "plots.music", +description = "Player music in a plot", +usage = "/plot music", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class MusicSubcommand extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { + public boolean onCommand(final PlotPlayer player, final String[] args) + { final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); - } - if (!plot.isAdded(player.getUUID())) { + if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } + if (!plot.isAdded(player.getUUID())) + { sendMessage(player, C.NO_PLOT_PERMS); return true; } - PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { - public boolean onClick(int index) { - PlotItemStack item = getItem(index); + final PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") + { + @Override + public boolean onClick(final int index) + { + final PlotItemStack item = getItem(index); if (item == null) { - return true; + return true; } - int id = item.id == 7 ? 0 : item.id; - if (id == 0) { + final int id = item.id == 7 ? 0 : item.id; + if (id == 0) + { FlagManager.removePlotFlag(plot, "music"); } - else { + else + { FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("music"), id)); } return false; } }; int index = 0; - for (int i = 2256; i < 2268; i++) { - String name = "&r&6" + BlockManager.manager.getClosestMatchingName(new PlotBlock((short) i, (byte) 0)); - String[] lore = {"&r&aClick to play!"}; - PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore); + for (int i = 2256; i < 2268; i++) + { + final String name = "&r&6" + BlockManager.manager.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); inv.setItem(index, item); index++; } - if (player.getMeta("music") != null) { - String name = "&r&6Cancel music"; - String[] lore = {"&r&cClick to cancel!"}; + if (player.getMeta("music") != null) + { + final String name = "&r&6Cancel music"; + final String[] lore = { "&r&cClick to cancel!" }; inv.setItem(index, new PlotItemStack(7, (short) 0, 1, name, lore)); } inv.openInventory(); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/src/main/java/com/intellectualcrafters/plot/commands/Purge.java index 0ec980357..5343af9f6 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Purge.java @@ -35,128 +35,147 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; - @CommandDeclaration( - command = "purge", - permission = "plots.admin", - description = "Purge all plots for a world", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.CONSOLE -) -public class Purge extends SubCommand { - - public PlotId getId(final String id) { - try { +command = "purge", +permission = "plots.admin", +description = "Purge all plots for a world", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.CONSOLE) +public class Purge extends SubCommand +{ + + public PlotId getId(final String id) + { + try + { final String[] split = id.split(";"); return new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); - } catch (final Exception e) { + } + catch (final Exception e) + { return null; } } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - if (args.length == 1) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + if (args.length == 1) + { final String arg = args[0].toLowerCase(); final PlotId id = getId(arg); - if (id != null) { + if (id != null) + { MainUtil.sendMessage(plr, "/plot purxe x;z &l"); return false; } final UUID uuid = UUIDHandler.getUUID(args[0], null); - if (uuid != null) { + if (uuid != null) + { MainUtil.sendMessage(plr, "/plot purge " + args[0] + " &l"); return false; } - if (arg.equals("player")) { + if (arg.equals("player")) + { MainUtil.sendMessage(plr, "/plot purge &l "); return false; } - if (arg.equals("unowned")) { + if (arg.equals("unowned")) + { MainUtil.sendMessage(plr, "/plot purge unowned &l"); return false; } - if (arg.equals("unknown")) { + if (arg.equals("unknown")) + { MainUtil.sendMessage(plr, "/plot purge unknown &l"); return false; } - if (arg.equals("all")) { + if (arg.equals("all")) + { MainUtil.sendMessage(plr, "/plot purge all &l"); return false; } MainUtil.sendMessage(plr, C.PURGE_SYNTAX); return false; } - if (args.length != 2) { + if (args.length != 2) + { MainUtil.sendMessage(plr, C.PURGE_SYNTAX); return false; } final String worldname = args[1]; - if (!PS.get().getAllPlotsRaw().containsKey(worldname)) { + if (!PS.get().getAllPlotsRaw().containsKey(worldname)) + { MainUtil.sendMessage(plr, "INVALID WORLD"); return false; } final String arg = args[0].toLowerCase(); final PlotId id = getId(arg); - if (id != null) { + if (id != null) + { final HashSet ids = new HashSet(); final int DBid = DBFunc.getId(MainUtil.getPlot(worldname, id)); - if (DBid != Integer.MAX_VALUE) { + if (DBid != Integer.MAX_VALUE) + { ids.add(DBid); } DBFunc.purgeIds(worldname, ids); return finishPurge(DBid == Integer.MAX_VALUE ? 1 : 0); } - if (arg.equals("all")) { + if (arg.equals("all")) + { final Set ids = PS.get().getPlots(worldname).keySet(); - int length = ids.size(); - if (length == 0) { - return MainUtil.sendMessage(null, "&cNo plots found"); - } + final int length = ids.size(); + if (length == 0) { return MainUtil.sendMessage(null, "&cNo plots found"); } DBFunc.purge(worldname, ids); return finishPurge(length); } - if (arg.equals("unknown")) { + if (arg.equals("unknown")) + { final Collection plots = PS.get().getPlotsInWorld(worldname); final Set ids = new HashSet<>(); - for (final Plot plot : plots) { - if (plot.owner != null) { + for (final Plot plot : plots) + { + if (plot.owner != null) + { final String name = UUIDHandler.getName(plot.owner); - if (name == null) { + if (name == null) + { ids.add(plot.id); } } } - int length = ids.size(); - if (length == 0) { - return MainUtil.sendMessage(null, "&cNo plots found"); - } + final int length = ids.size(); + if (length == 0) { return MainUtil.sendMessage(null, "&cNo plots found"); } DBFunc.purge(worldname, ids); return finishPurge(length); } - if (arg.equals("unowned")) { + if (arg.equals("unowned")) + { final Collection plots = PS.get().getPlotsInWorld(worldname); final Set ids = new HashSet<>(); - for (final Plot plot : plots) { - if (plot.owner == null) { + for (final Plot plot : plots) + { + if (plot.owner == null) + { ids.add(plot.id); } } - int length = ids.size(); - if (length == 0) { - return MainUtil.sendMessage(null, "&cNo plots found"); - } + final int length = ids.size(); + if (length == 0) { return MainUtil.sendMessage(null, "&cNo plots found"); } DBFunc.purge(worldname, ids); return finishPurge(length); } final UUID uuid = UUIDHandler.getUUID(args[0], null); - if (uuid != null) { + if (uuid != null) + { final Set plots = PS.get().getPlots(worldname, uuid); final Set ids = new HashSet<>(); - for (final Plot plot : plots) { + for (final Plot plot : plots) + { ids.add(plot.id); } - int length = ids.size(); + final int length = ids.size(); DBFunc.purge(worldname, ids); return finishPurge(length); } @@ -164,7 +183,8 @@ public class Purge extends SubCommand { return false; } - private boolean finishPurge(final int amount) { + private boolean finishPurge(final int amount) + { MainUtil.sendMessage(null, C.PURGE_SUCCESS, amount + ""); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index bc0331fd1..d679dbf58 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -28,13 +28,11 @@ import java.util.Map.Entry; import java.util.UUID; import org.apache.commons.lang.mutable.MutableInt; -import org.bukkit.Bukkit; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotInventory; @@ -46,47 +44,60 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.events.PlotRateEvent; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "rate", - permission = "plots.rate", - description = "Rate the plot", - usage = "/plot rate [#|next]", - aliases = {"rt"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Rate extends SubCommand { +command = "rate", +permission = "plots.rate", +description = "Rate the plot", +usage = "/plot rate [#|next]", +aliases = { "rt" }, +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Rate extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer player, final String[] args) { - if (args.length == 1) { - if (args[0].equalsIgnoreCase("next")) { - ArrayList plots = new ArrayList<>(PS.get().getPlots()); - Collections.sort(plots, new Comparator() { + public boolean onCommand(final PlotPlayer player, final String[] args) + { + if (args.length == 1) + { + if (args[0].equalsIgnoreCase("next")) + { + final ArrayList plots = new ArrayList<>(PS.get().getPlots()); + Collections.sort(plots, new Comparator() + { @Override - public int compare(Plot p1, Plot p2) { + public int compare(final Plot p1, final Plot p2) + { double v1 = 0; double v2 = 0; - if (p1.getSettings().ratings != null) { - for (Entry entry : p1.getRatings().entrySet()) { + if (p1.getSettings().ratings != null) + { + for (final Entry entry : p1.getRatings().entrySet()) + { v1 -= 11 - entry.getValue().getAverageRating(); } } - if (p2.getSettings().ratings != null) { - for (Entry entry : p2.getRatings().entrySet()) { + if (p2.getSettings().ratings != null) + { + for (final Entry entry : p2.getRatings().entrySet()) + { v2 -= 11 - entry.getValue().getAverageRating(); } } return v2 > v1 ? 1 : -1; } }); - UUID uuid = player.getUUID(); - for (Plot p : plots) { - if ((!Settings.REQUIRE_DONE || p.getSettings().flags.containsKey("done")) && p.isBasePlot() && (p.getSettings().ratings == null || !p.getSettings().ratings.containsKey(uuid)) && !p.isAdded(uuid)) { + final UUID uuid = player.getUUID(); + for (final Plot p : plots) + { + if ((!Settings.REQUIRE_DONE || p.getSettings().flags.containsKey("done")) + && p.isBasePlot() + && ((p.getSettings().ratings == null) || !p.getSettings().ratings.containsKey(uuid)) + && !p.isAdded(uuid)) + { MainUtil.teleportPlayer(player, player.getLocation(), p); MainUtil.sendMessage(player, C.RATE_THIS); return true; @@ -98,40 +109,49 @@ public class Rate extends SubCommand { } final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { sendMessage(player, C.RATING_NOT_OWNED); return false; } - if (plot.isOwner(player.getUUID())) { + if (plot.isOwner(player.getUUID())) + { sendMessage(player, C.RATING_NOT_YOUR_OWN); return false; } - if (Settings.REQUIRE_DONE && !plot.getSettings().flags.containsKey("done")) { + if (Settings.REQUIRE_DONE && !plot.getSettings().flags.containsKey("done")) + { sendMessage(player, C.RATING_NOT_DONE); return false; } - if (Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() != 0) { - final Runnable run = new Runnable() { + if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() != 0)) + { + final Runnable run = new Runnable() + { @Override - public void run() { - if (plot.getSettings().ratings.containsKey(player.getUUID())) { + public void run() + { + if (plot.getSettings().ratings.containsKey(player.getUUID())) + { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; } final MutableInt index = new MutableInt(0); final MutableInt rating = new MutableInt(0); - String title = Settings.RATING_CATEGORIES.get(0); - PlotInventory inventory = new PlotInventory(player, 1, title) { - public boolean onClick(int i) { + final String title = Settings.RATING_CATEGORIES.get(0); + final PlotInventory inventory = new PlotInventory(player, 1, title) + { + @Override + public boolean onClick(final int i) + { rating.add((i + 1) * Math.pow(10, index.intValue())); index.increment(); - if (index.intValue() >= Settings.RATING_CATEGORIES.size()) { + if (index.intValue() >= Settings.RATING_CATEGORIES.size()) + { close(); - int rV = rating.intValue(); - Rating result = EventUtil.manager.callRating(player, plot, new Rating(rV)); + final int rV = rating.intValue(); + final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rV)); plot.getSettings().ratings.put(player.getUUID(), result.getAggregate()); DBFunc.setRating(plot, player.getUUID(), rV); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); @@ -139,9 +159,11 @@ public class Rate extends SubCommand { return false; } setTitle(Settings.RATING_CATEGORIES.get(index.intValue())); - if (Permissions.hasPermission(player, "plots.comment")) { - Command command = MainCommand.getInstance().getCommand("comment"); - if (command != null) { + if (Permissions.hasPermission(player, "plots.comment")) + { + final Command command = MainCommand.getInstance().getCommand("comment"); + if (command != null) + { MainUtil.sendMessage(player, C.COMMENT_THIS, command.getUsage().replaceAll("{label}", "plot")); } } @@ -160,11 +182,15 @@ public class Rate extends SubCommand { inventory.openInventory(); } }; - if (plot.getSettings().ratings == null) { - if (!Settings.CACHE_RATINGS) { - TaskManager.runTaskAsync(new Runnable() { + if (plot.getSettings().ratings == null) + { + if (!Settings.CACHE_RATINGS) + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { + public void run() + { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } @@ -176,43 +202,54 @@ public class Rate extends SubCommand { run.run(); return true; } - if (args.length < 1) { + if (args.length < 1) + { sendMessage(player, C.RATING_NOT_VALID); return true; } final String arg = args[0]; final int rating; - if (MathMan.isInteger(arg) && arg.length() < 3 && arg.length() > 0) { + if (MathMan.isInteger(arg) && (arg.length() < 3) && (arg.length() > 0)) + { rating = Integer.parseInt(arg); - if (rating > 10) { + if (rating > 10) + { sendMessage(player, C.RATING_NOT_VALID); return false; } } - else { + else + { sendMessage(player, C.RATING_NOT_VALID); return false; } final UUID uuid = player.getUUID(); - final Runnable run = new Runnable() { + final Runnable run = new Runnable() + { @Override - public void run() { - if (plot.getSettings().ratings.containsKey(uuid)) { + public void run() + { + if (plot.getSettings().ratings.containsKey(uuid)) + { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; } - Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); - int resultVal = result.getAggregate(); + final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); + final int resultVal = result.getAggregate(); plot.getSettings().ratings.put(uuid, resultVal); DBFunc.setRating(plot, uuid, resultVal); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); } }; - if (plot.getSettings().ratings == null) { - if (!Settings.CACHE_RATINGS) { - TaskManager.runTaskAsync(new Runnable() { + if (plot.getSettings().ratings == null) + { + if (!Settings.CACHE_RATINGS) + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { + public void run() + { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java b/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java index 03e514ae9..5bc0d318e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java @@ -35,30 +35,35 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "regenallroads", - description = "Regenerate all roads in the map using the set road schematic", - aliases = {"rgar"}, - usage = "/plot regenallroads ", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE, - permission = "plots.regenallroads" -) -public class RegenAllRoads extends SubCommand { +command = "regenallroads", +description = "Regenerate all roads in the map using the set road schematic", +aliases = { "rgar" }, +usage = "/plot regenallroads ", +category = CommandCategory.DEBUG, +requiredType = RequiredType.CONSOLE, +permission = "plots.regenallroads") +public class RegenAllRoads extends SubCommand +{ - public RegenAllRoads() { + public RegenAllRoads() + { requiredArguments = new Argument[] { - Argument.String + Argument.String }; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { int height = 0; - if (args.length == 2) { - try { + if (args.length == 2) + { + try + { height = Integer.parseInt(args[1]); } - catch (NumberFormatException e) { + catch (final NumberFormatException e) + { MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(0, 256)"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); return false; @@ -66,7 +71,8 @@ public class RegenAllRoads extends SubCommand { } final String name = args[0]; final PlotManager manager = PS.get().getPlotManager(name); - if ((manager == null) || !(manager instanceof HybridPlotManager)) { + if ((manager == null) || !(manager instanceof HybridPlotManager)) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); return false; } @@ -76,7 +82,8 @@ public class RegenAllRoads extends SubCommand { 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(name, height); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, "&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/src/main/java/com/intellectualcrafters/plot/commands/Reload.java index 9bcf3c49a..59b6b01a9 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Reload.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Reload.java @@ -29,30 +29,35 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "reload", - permission = "plots.admin.command.reload", - description = "Reload configurations", - usage = "/plot reload", - category = CommandCategory.INFO -) -public class Reload extends SubCommand { +command = "reload", +permission = "plots.admin.command.reload", +description = "Reload configurations", +usage = "/plot reload", +category = CommandCategory.INFO) +public class Reload extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - try { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + try + { // The following won't affect world generation, as that has to be // loaded during startup unfortunately. PS.get().config.load(PS.get().configFile); PS.get().setupConfig(); C.load(PS.get().translationFile); - for (final String pw : PS.get().getPlotWorlds()) { + for (final String pw : PS.get().getPlotWorlds()) + { final PlotWorld plotworld = PS.get().getPlotWorld(pw); - ConfigurationSection section = PS.get().config.getConfigurationSection("worlds." + pw); + final ConfigurationSection section = PS.get().config.getConfigurationSection("worlds." + pw); plotworld.saveConfiguration(section); plotworld.loadDefaultConfiguration(section); } MainUtil.sendMessage(plr, C.RELOADED_CONFIGS); - } catch (final Exception e) { + } + catch (final Exception e) + { e.printStackTrace(); MainUtil.sendMessage(plr, C.RELOAD_FAILED); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Remove.java b/src/main/java/com/intellectualcrafters/plot/commands/Remove.java index 22519b91e..b581fdd22 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Remove.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Remove.java @@ -36,73 +36,84 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "remove", - aliases = {"r"}, - description = "Remove a player from a plot", - usage = "/plot remove ", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - permission = "plots.remove" -) -public class Remove extends SubCommand { +command = "remove", +aliases = { "r" }, +description = "Remove a player from a plot", +usage = "/plot remove ", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE, +permission = "plots.remove") +public class Remove extends SubCommand +{ - public Remove() { + public Remove() + { requiredArguments = new Argument[] { - Argument.PlayerName + Argument.PlayerName }; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - if (args.length != 1) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + if (args.length != 1) + { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot remove "); return true; } final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if ((plot == null) || !plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((plot == null) || !plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.remove")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.remove")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return true; } int count = 0; - switch (args[0]) { - case "unknown": { - ArrayList toRemove = new ArrayList<>(); - HashSet all = new HashSet<>(); + switch (args[0]) + { + case "unknown": + { + final ArrayList toRemove = new ArrayList<>(); + final HashSet all = new HashSet<>(); all.addAll(plot.getMembers()); all.addAll(plot.getTrusted()); all.addAll(plot.getDenied()); - for (UUID uuid : all) { - if (UUIDHandler.getName(uuid) == null) { + for (final UUID uuid : all) + { + if (UUIDHandler.getName(uuid) == null) + { toRemove.add(uuid); count++; } } - for (UUID uuid : toRemove) { + for (final UUID uuid : toRemove) + { plot.removeDenied(uuid); plot.removeTrusted(uuid); plot.removeMember(uuid); } break; } - case "*": { - ArrayList toRemove = new ArrayList<>(); - HashSet all = new HashSet<>(); + case "*": + { + final ArrayList toRemove = new ArrayList<>(); + final HashSet all = new HashSet<>(); all.addAll(plot.getMembers()); all.addAll(plot.getTrusted()); all.addAll(plot.getDenied()); - for (UUID uuid : all) { + for (final UUID uuid : all) + { toRemove.add(uuid); count++; } - for (UUID uuid : toRemove) { + for (final UUID uuid : toRemove) + { plot.removeDenied(uuid); plot.removeTrusted(uuid); plot.removeMember(uuid); @@ -110,33 +121,47 @@ public class Remove extends SubCommand { break; } default: - UUID uuid = UUIDHandler.getUUID(args[0], null); - if (uuid != null) { - if (plot.getTrusted().contains(uuid)) { - if (plot.removeTrusted(uuid)) { + final UUID uuid = UUIDHandler.getUUID(args[0], null); + if (uuid != null) + { + if (plot.getTrusted().contains(uuid)) + { + if (plot.removeTrusted(uuid)) + { count++; } - } else if (plot.getMembers().contains(uuid)) { - if (plot.removeMember(uuid)) { + } + else if (plot.getMembers().contains(uuid)) + { + if (plot.removeMember(uuid)) + { count++; } - } else if (plot.getDenied().contains(uuid)) { - if (plot.removeDenied(uuid)) { + } + else if (plot.getDenied().contains(uuid)) + { + if (plot.removeDenied(uuid)) + { count++; } } } break; } - if (count == 0) { - if (UUIDHandler.implementation instanceof SQLUUIDHandler) { + if (count == 0) + { + if (UUIDHandler.implementation instanceof SQLUUIDHandler) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER_WAIT, args[0]); - } else { + } + else + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); } return false; } - else { + else + { MainUtil.sendMessage(plr, C.REMOVED_PLAYERS, count + ""); } return true; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java b/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java index 30b9a4e44..fe8c90e07 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java @@ -2,13 +2,16 @@ package com.intellectualcrafters.plot.commands; import com.plotsquared.general.commands.CommandCaller; -public enum RequiredType { +public enum RequiredType +{ CONSOLE, PLAYER, NONE; - - public boolean allows(CommandCaller player) { - switch (this) { + + public boolean allows(final CommandCaller player) + { + switch (this) + { case NONE: return true; default: diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Save.java b/src/main/java/com/intellectualcrafters/plot/commands/Save.java index fc10a75f4..a3486088b 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Save.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Save.java @@ -19,66 +19,73 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "save", - aliases = {"backup"}, - description = "Save your plot", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE, - permission = "plots.save" -) -public class Save extends SubCommand { +command = "save", +aliases = { "backup" }, +description = "Save your plot", +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE, +permission = "plots.save") +public class Save extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - - if (!Settings.METRICS) { + public boolean onCommand(final PlotPlayer plr, final 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"); return false; } final String world = plr.getLocation().getWorld(); - if (!PS.get().isPlotWorld(world)) { - return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); - } + if (!PS.get().isPlotWorld(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } final Plot plot = MainUtil.getPlot(plr.getLocation()); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.save")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.save")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); - SchematicHandler.manager.getCompoundTag(plot.world, plot.id, new RunnableVal() { + SchematicHandler.manager.getCompoundTag(plot.world, plot.id, new RunnableVal() + { @Override - public void run() { - TaskManager.runTaskAsync(new Runnable() { + public void run() + { + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { - String time = (System.currentTimeMillis() / 1000) + ""; - String name = PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", ""); - int size = plot.getTop().getX() - plot.getBottom().getX() + 1; - PlotId id = plot.id; - String world = plot.world.replaceAll("[^A-Za-z0-9]", ""); - String file = time + "_" + world + "_" + id.x + "_" + id.y + "_" + size + "_" + name; - UUID uuid = plr.getUUID(); - - URL url = SchematicHandler.manager.upload(value, uuid, file); - if (url == null) { + public void run() + { + final String time = (System.currentTimeMillis() / 1000) + ""; + final String name = PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", ""); + final int size = (plot.getTop().getX() - plot.getBottom().getX()) + 1; + final PlotId id = plot.id; + final String world = plot.world.replaceAll("[^A-Za-z0-9]", ""); + final String file = time + "_" + world + "_" + id.x + "_" + id.y + "_" + size + "_" + name; + final UUID uuid = plr.getUUID(); + + final URL url = SchematicHandler.manager.upload(value, uuid, file); + if (url == null) + { MainUtil.sendMessage(plr, C.SAVE_FAILED); MainUtil.runners.remove(plot); return; } MainUtil.sendMessage(plr, C.SAVE_SUCCESS); - List schematics = (List) plr.getMeta("plot_schematics"); - if (schematics != null) { + final List schematics = (List) plr.getMeta("plot_schematics"); + if (schematics != null) + { schematics.add(file); } MainUtil.runners.remove(plot); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java index 1e17c68f9..9d577c2a3 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java @@ -23,7 +23,6 @@ package com.intellectualcrafters.plot.commands; import java.net.URL; import java.util.ArrayList; import java.util.Collection; -import java.util.Map; import java.util.UUID; import com.intellectualcrafters.plot.PS; @@ -32,7 +31,6 @@ import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.ConsolePlayer; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.MainUtil; @@ -45,93 +43,107 @@ import com.plotsquared.general.commands.CommandDeclaration; // TODO Add sub-subcommands @CommandDeclaration( - command = "schematic", - permission = "plots.schematic", - description = "Schematic command", - aliases = {"sch"}, - category = CommandCategory.ACTIONS, - usage = "/plot schematic " -) -public class SchematicCmd extends SubCommand { +command = "schematic", +permission = "plots.schematic", +description = "Schematic command", +aliases = { "sch" }, +category = CommandCategory.ACTIONS, +usage = "/plot schematic ") +public class SchematicCmd extends SubCommand +{ - private int counter = 0; private boolean running = false; - private int task; - @Override - public boolean onCommand(final PlotPlayer plr, final String ... args) { - if (args.length < 1) { + public boolean onCommand(final PlotPlayer plr, final String... args) + { + if (args.length < 1) + { sendMessage(plr, C.SCHEMATIC_MISSING_ARG); return true; } final String arg = args[0].toLowerCase(); final String file; final Schematic schematic; - switch (arg) { - case "paste": { - if (!Permissions.hasPermission(plr, "plots.schematic.paste")) { + switch (arg) + { + case "paste": + { + if (!Permissions.hasPermission(plr, "plots.schematic.paste")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.paste"); return false; } - if (args.length < 2) { + if (args.length < 2) + { sendMessage(plr, C.SCHEMATIC_MISSING_ARG); break; } final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.schematic.paste")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.schematic.paste")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - if (this.running) { + if (running) + { MainUtil.sendMessage(plr, "&cTask is already running."); return false; } final String location = args[1]; - this.running = true; - this.counter = 0; - TaskManager.runTaskAsync(new Runnable() { + running = true; + TaskManager.runTaskAsync(new Runnable() + { @Override - public void run() { + public void run() + { Schematic schematic; - if (location.startsWith("url:")) { - try { - UUID uuid = UUID.fromString(location.substring(4)); - URL base = new URL(Settings.WEB_URL); - URL url = new URL(base, "uploads/" + uuid + ".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"); schematic = SchematicHandler.manager.getSchematic(url); } - catch (Exception e) { + catch (final Exception e) + { e.printStackTrace(); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent url: " + location); - SchematicCmd.this.running = false; + running = false; return; } } - else { + else + { schematic = SchematicHandler.manager.getSchematic(location); } - if (schematic == null) { - SchematicCmd.this.running = false; + if (schematic == null) + { + running = false; sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); return; } - SchematicHandler.manager.paste(schematic, plot, 0, 0, new RunnableVal() { + SchematicHandler.manager.paste(schematic, plot, 0, 0, new RunnableVal() + { @Override - public void run() { - SchematicCmd.this.running = false; - if (this.value) { + public void run() + { + running = false; + if (value) + { sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); } - else { + else + { sendMessage(plr, C.SCHEMATIC_PASTE_FAILED); } } @@ -140,31 +152,37 @@ public class SchematicCmd extends SubCommand { }); break; } - case "test": { - if (!Permissions.hasPermission(plr, "plots.schematic.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) { + 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) { + if (plot == null) + { sendMessage(plr, C.NOT_IN_PLOT); return false; } file = args[1]; schematic = SchematicHandler.manager.getSchematic(file); - if (schematic == null) { + 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)) { + if ((l1 < length) || (l2 < length)) + { sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); break; } @@ -172,82 +190,97 @@ public class SchematicCmd extends SubCommand { break; } case "saveall": - case "exportall": { - if (!ConsolePlayer.isConsole(plr)) { + case "exportall": + { + if (!ConsolePlayer.isConsole(plr)) + { MainUtil.sendMessage(plr, C.NOT_CONSOLE); return false; } - if (args.length != 2) { + if (args.length != 2) + { MainUtil.sendMessage(null, "&cNeed world arg. Use &7/plots sch exportall "); return false; } - Collection plots = PS.get().getPlotsInWorld(args[1]); - if ((plots.size() == 0)) { + final Collection plots = PS.get().getPlotsInWorld(args[1]); + if ((plots.size() == 0)) + { MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall "); return false; } - boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(plr, "&aFinished mass export"); - } - }); - if (!result) { - MainUtil.sendMessage(plr, "&cTask is already running."); + final boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() + { + @Override + public void run() + { + MainUtil.sendMessage(plr, "&aFinished mass export"); + } + }); + if (!result) + { + MainUtil.sendMessage(plr, "&cTask is already running."); return false; } - else { - MainUtil.sendMessage(plr, "&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); - MainUtil.sendMessage(plr, "&3PlotSquared&8->&3Schemaitc&8: &7Found &c" + plots.size() + "&7 plots..."); + else + { + MainUtil.sendMessage(plr, "&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); + MainUtil.sendMessage(plr, "&3PlotSquared&8->&3Schemaitc&8: &7Found &c" + plots.size() + "&7 plots..."); } break; } case "export": - case "save": { - if (!Permissions.hasPermission(plr, "plots.schematic.save")) { + case "save": + { + if (!Permissions.hasPermission(plr, "plots.schematic.save")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.save"); return false; } - if (this.running) { + if (running) + { MainUtil.sendMessage(plr, "&cTask is already running."); return false; } - final String world; final Plot p2; final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { MainUtil.sendMessage(plr, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.schematic.save")) { + if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.schematic.save")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } p2 = plot; - world = loc.getWorld(); - Collection plots = new ArrayList(); + loc.getWorld(); + final Collection plots = new ArrayList(); plots.add(p2); - boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(plr, "&aFinished export"); - SchematicCmd.this.running = false; - } - }); - if (!result) { - MainUtil.sendMessage(plr, "&cTask is already running."); + final boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() + { + @Override + public void run() + { + MainUtil.sendMessage(plr, "&aFinished export"); + running = false; + } + }); + if (!result) + { + MainUtil.sendMessage(plr, "&cTask is already running."); return false; } - else { - MainUtil.sendMessage(plr, "&7Starting export..."); + else + { + MainUtil.sendMessage(plr, "&7Starting export..."); } break; } - default: { + default: + { sendMessage(plr, C.SCHEMATIC_MISSING_ARG); break; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/src/main/java/com/intellectualcrafters/plot/commands/Set.java index f53bce8cd..bd306c469 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Set.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Set.java @@ -48,81 +48,95 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.listener.PlotListener; - // TODO Make sub-subcommands @CommandDeclaration( - command = "set", - description = "Set a plot value", - aliases = {"s"}, - usage = "/plot set ", - permission = "plots.set", - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Set extends SubCommand { +command = "set", +description = "Set a plot value", +aliases = { "s" }, +usage = "/plot set ", +permission = "plots.set", +category = CommandCategory.ACTIONS, +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" }; @Override - public boolean onCommand(final PlotPlayer plr, final String ... args) { - + public boolean onCommand(final PlotPlayer plr, final String... args) + { + final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if (!plot.hasOwner()) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if (!plot.hasOwner()) + { sendMessage(plr, C.PLOT_NOT_CLAIMED); return false; } - if (!plot.isOwner(plr.getUUID())) { - if (!Permissions.hasPermission(plr, "plots.set.other")) { + if (!plot.isOwner(plr.getUUID())) + { + if (!Permissions.hasPermission(plr, "plots.set.other")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set.other"); return false; } } - if (args.length < 1) { - PlotManager manager = PS.get().getPlotManager(loc.getWorld()); - ArrayList newValues = new ArrayList(); + if (args.length < 1) + { + final PlotManager manager = PS.get().getPlotManager(loc.getWorld()); + final ArrayList newValues = new ArrayList(); newValues.addAll(Arrays.asList(values)); newValues.addAll(Arrays.asList(manager.getPlotComponents(PS.get().getPlotWorld(loc.getWorld()), plot.id))); MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(newValues)); return false; } - for (int i = 0; i < aliases.length; i++) { - if (aliases[i].equalsIgnoreCase(args[0])) { + for (int i = 0; i < aliases.length; i++) + { + if (aliases[i].equalsIgnoreCase(args[0])) + { args[0] = values[i]; break; } } - if (args[0].equalsIgnoreCase("flag")) { - if (args.length < 2) { + if (args[0].equalsIgnoreCase("flag")) + { + if (args.length < 2) + { final String message = StringMan.replaceFromMap("$2" + (StringMan.join(FlagManager.getFlags(plr), "$1, $2")), C.replacements); // final String message = StringMan.join(FlagManager.getFlags(plr), "&c, &6"); MainUtil.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", message)); return false; } AbstractFlag af; - try { + try + { af = FlagManager.getFlag(args[1].toLowerCase()); - } catch (final Exception e) { + } + catch (final Exception e) + { af = new AbstractFlag(args[1].toLowerCase()); } - if (!FlagManager.getFlags().contains(af) || FlagManager.isReserved(af.getKey())) { + if (!FlagManager.getFlags().contains(af) || FlagManager.isReserved(af.getKey())) + { MainUtil.sendMessage(plr, C.NOT_VALID_FLAG); return false; } - if (!Permissions.hasPermission(plr, "plots.set.flag." + args[1].toLowerCase())) { + if (!Permissions.hasPermission(plr, "plots.set.flag." + args[1].toLowerCase())) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase()); return false; } - if (args.length == 2) { - if (FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()) == null) { + if (args.length == 2) + { + if (FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()) == null) + { MainUtil.sendMessage(plr, C.FLAG_NOT_IN_PLOT); return false; } final boolean result = FlagManager.removePlotFlag(plot, args[1].toLowerCase()); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, C.FLAG_NOT_REMOVED); return false; } @@ -130,34 +144,43 @@ public class Set extends SubCommand { PlotListener.plotEntry(plr, plot); return true; } - try { + try + { final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); final Object parsed_value = af.parseValueRaw(value); - if (parsed_value == null) { + if (parsed_value == null) + { MainUtil.sendMessage(plr, af.getValueDesc()); return false; } final Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed_value); final boolean result = FlagManager.addPlotFlag(plot, flag); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, C.FLAG_NOT_ADDED); return false; } MainUtil.sendMessage(plr, C.FLAG_ADDED); PlotListener.plotEntry(plr, plot); return true; - } catch (final Exception e) { + } + catch (final Exception e) + { MainUtil.sendMessage(plr, "&c" + e.getMessage()); return false; } } - if (args[0].equalsIgnoreCase("home")) { - if (!Permissions.hasPermission(plr, "plots.set.home")) { + if (args[0].equalsIgnoreCase("home")) + { + if (!Permissions.hasPermission(plr, "plots.set.home")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set.home"); return false; } - if (args.length > 1) { - if (args[1].equalsIgnoreCase("none")) { + if (args.length > 1) + { + if (args[1].equalsIgnoreCase("none")) + { plot.setHome(null); return true; } @@ -172,50 +195,62 @@ public class Set extends SubCommand { plot.setHome(blockloc); return MainUtil.sendMessage(plr, C.POSITION_SET); } - if (args[0].equalsIgnoreCase("desc")) { - if (!Permissions.hasPermission(plr, "plots.set.desc")) { + if (args[0].equalsIgnoreCase("desc")) + { + if (!Permissions.hasPermission(plr, "plots.set.desc")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set.desc"); return false; } - if (args.length < 2) { + if (args.length < 2) + { MainUtil.sendMessage(plr, C.MISSING_DESC); return false; } final StringBuilder desc = new StringBuilder(); - for (int i = 1; i < args.length; i++) { + for (int i = 1; i < args.length; i++) + { desc.append(args[i]).append(" "); } - String descValue = desc.substring(0, desc.length() - 1); + final String descValue = desc.substring(0, desc.length() - 1); - Flag flag = new Flag(FlagManager.getFlag("description"), descValue); + final Flag flag = new Flag(FlagManager.getFlag("description"), descValue); final boolean result = FlagManager.addPlotFlag(plot, flag); - if (!result) { + if (!result) + { MainUtil.sendMessage(plr, C.FLAG_NOT_ADDED); return false; } MainUtil.sendMessage(plr, C.DESC_SET); return true; } - if (args[0].equalsIgnoreCase("alias")) { - if (!Permissions.hasPermission(plr, "plots.set.alias")) { + if (args[0].equalsIgnoreCase("alias")) + { + if (!Permissions.hasPermission(plr, "plots.set.alias")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set.alias"); return false; } - if (args.length < 2) { + if (args.length < 2) + { MainUtil.sendMessage(plr, C.MISSING_ALIAS); return false; } final String alias = args[1]; - if (alias.length() >= 50) { + if (alias.length() >= 50) + { MainUtil.sendMessage(plr, C.ALIAS_TOO_LONG); return false; } - for (final Plot p : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) { - if (p.getSettings().getAlias().equalsIgnoreCase(alias)) { + for (final Plot p : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) + { + if (p.getSettings().getAlias().equalsIgnoreCase(alias)) + { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); return false; } - if (UUIDHandler.nameExists(new StringWrapper(alias))) { + if (UUIDHandler.nameExists(new StringWrapper(alias))) + { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); return false; } @@ -224,39 +259,48 @@ public class Set extends SubCommand { MainUtil.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); return true; } - if (args[0].equalsIgnoreCase("biome")) { - if (!Permissions.hasPermission(plr, "plots.set.biome")) { + if (args[0].equalsIgnoreCase("biome")) + { + if (!Permissions.hasPermission(plr, "plots.set.biome")) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set.biome"); return false; } - if (args.length < 2) { + if (args.length < 2) + { MainUtil.sendMessage(plr, C.NEED_BIOME); return true; } - if (args[1].length() < 2) { + if (args[1].length() < 2) + { sendMessage(plr, C.NAME_LITTLE, "Biome", args[1].length() + "", "2"); return true; } final int biome = BlockManager.manager.getBiomeFromString(args[1]); - if (biome == -1) { + if (biome == -1) + { MainUtil.sendMessage(plr, getBiomeList(BlockManager.manager.getBiomeList())); return true; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); - plot.setBiome(args[1].toUpperCase(), new Runnable() { + plot.setBiome(args[1].toUpperCase(), new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); MainUtil.sendMessage(plr, C.BIOME_SET_TO.s() + args[1].toLowerCase()); } }); return true; } - if (args[0].equalsIgnoreCase("limit")) { + if (args[0].equalsIgnoreCase("limit")) + { // /plot set limit Empire92 +1 return true; } @@ -266,69 +310,89 @@ public class Set extends SubCommand { final PlotManager manager = PS.get().getPlotManager(world); final String[] components = manager.getPlotComponents(plotworld, plot.id); - boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(plr.getUUID()); + final boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(plr.getUUID()); - for (final String component : components) { - if (component.equalsIgnoreCase(args[0])) { - if (!Permissions.hasPermission(plr, "plots.set." + component)) { + for (final String component : components) + { + if (component.equalsIgnoreCase(args[0])) + { + if (!Permissions.hasPermission(plr, "plots.set." + component)) + { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.set." + component); return false; } PlotBlock[] blocks; - try { - if (args.length < 2) { + try + { + if (args.length < 2) + { MainUtil.sendMessage(plr, C.NEED_BLOCK); return true; } - String[] split = args[1].split(","); + final String[] split = args[1].split(","); blocks = Configuration.BLOCKLIST.parseString(args[1]); - for (int i = 0; i < blocks.length; i++) { - PlotBlock block = blocks[i]; - if (block == null) { + for (int i = 0; i < blocks.length; i++) + { + final PlotBlock block = blocks[i]; + if (block == null) + { MainUtil.sendMessage(plr, C.NOT_VALID_BLOCK, split[i]); String name; - if (split[i].contains("%")) { + if (split[i].contains("%")) + { name = split[i].split("%")[1]; } - else { + else + { name = split[i]; } - StringComparison.ComparisonResult match = BlockManager.manager.getClosestBlock(name); - if (match != null) { + final StringComparison.ComparisonResult match = BlockManager.manager.getClosestBlock(name); + if (match != null) + { name = BlockManager.manager.getClosestMatchingName(match.best); - if (name != null) { + if (name != null) + { MainUtil.sendMessage(plr, C.DID_YOU_MEAN, name.toLowerCase()); } } return false; } - else if (!allowUnsafe && !BlockManager.manager.isBlockSolid(block)) { + else if (!allowUnsafe && !BlockManager.manager.isBlockSolid(block)) + { MainUtil.sendMessage(plr, C.NOT_ALLOWED_BLOCK, block.toString()); return false; } } - if (!allowUnsafe) { - for (PlotBlock block : blocks) { - if (!BlockManager.manager.isBlockSolid(block)) { + if (!allowUnsafe) + { + for (final PlotBlock block : blocks) + { + if (!BlockManager.manager.isBlockSolid(block)) + { MainUtil.sendMessage(plr, C.NOT_ALLOWED_BLOCK, block.toString()); return false; } } } - } catch (final Exception e2) { + } + catch (final Exception e2) + { MainUtil.sendMessage(plr, C.NOT_VALID_BLOCK, args[1]); return false; } - if (MainUtil.runners.containsKey(plot)) { + if (MainUtil.runners.containsKey(plot)) + { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); manager.setComponent(plotworld, plot.id, component, blocks); MainUtil.sendMessage(plr, C.GENERATING_COMPONENT); - SetBlockQueue.addNotify(new Runnable() { + SetBlockQueue.addNotify(new Runnable() + { @Override - public void run() { + public void run() + { MainUtil.runners.remove(plot); } }); @@ -337,15 +401,21 @@ public class Set extends SubCommand { } { AbstractFlag af; - try { + try + { af = new AbstractFlag(args[0].toLowerCase()); - } catch (final Exception e) { + } + catch (final Exception e) + { af = new AbstractFlag(""); } - if (FlagManager.getFlags().contains(af)) { + if (FlagManager.getFlags().contains(af)) + { final StringBuilder a = new StringBuilder(); - if (args.length > 1) { - for (int x = 1; x < args.length; x++) { + if (args.length > 1) + { + for (int x = 1; x < args.length; x++) + { a.append(" ").append(args[x]); } } @@ -353,29 +423,34 @@ public class Set extends SubCommand { return true; } } - ArrayList newValues = new ArrayList(); + final ArrayList newValues = new ArrayList(); newValues.addAll(Arrays.asList(values)); newValues.addAll(Arrays.asList(manager.getPlotComponents(PS.get().getPlotWorld(loc.getWorld()), plot.id))); MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(newValues)); return false; } - private String getString(final String s) { + private String getString(final String s) + { return StringMan.replaceAll(C.BLOCK_LIST_ITEM.s(), "%mat%", s); } - private String getArgumentList(final List newValues) { + private String getArgumentList(final List newValues) + { final StringBuilder builder = new StringBuilder(); - for (final String s : newValues) { + for (final String s : newValues) + { builder.append(getString(s)); } return builder.toString().substring(1, builder.toString().length() - 1); } - private String getBiomeList(final String[] biomes) { + private String getBiomeList(final String[] biomes) + { final StringBuilder builder = new StringBuilder(); builder.append(C.NEED_BIOME.s()); - for (final String b : biomes) { + for (final String b : biomes) + { builder.append(getString(b)); } return builder.toString().substring(1, builder.toString().length() - 1); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java b/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java index b6fb89ecd..0d0bbd781 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java @@ -38,82 +38,98 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "setowner", - permission = "plots.set.owner", - description = "Set the plot owner", - usage = "/plot setowner ", - aliases = {"so"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class SetOwner extends SubCommand { +command = "setowner", +permission = "plots.set.owner", +description = "Set the plot owner", +usage = "/plot setowner ", +aliases = { "so" }, +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class SetOwner extends SubCommand +{ - public SetOwner() { + public SetOwner() + { requiredArguments = new Argument[] { - Argument.PlayerName + Argument.PlayerName }; } - private UUID getUUID(final String string) { + private UUID getUUID(final String string) + { return UUIDHandler.getUUID(string, null); } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if ((plot == null) || (plot.owner == null && !Permissions.hasPermission(plr, "plots.admin.command.setowner"))) { + if ((plot == null) || ((plot.owner == null) && !Permissions.hasPermission(plr, "plots.admin.command.setowner"))) + { MainUtil.sendMessage(plr, C.NOT_IN_PLOT); return false; } - if (args.length < 1) { + if (args.length < 1) + { MainUtil.sendMessage(plr, C.NEED_USER); return false; } - + final PlotId bot = MainUtil.getBottomPlot(plot).id; final PlotId top = MainUtil.getTopPlot(plot).id; final ArrayList plots = MainUtil.getPlotSelectionIds(bot, top); - - PlotPlayer other = UUIDHandler.getPlayer(args[0]); - if (other == null) { - if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) { - MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); - return false; - } + + final PlotPlayer other = UUIDHandler.getPlayer(args[0]); + if (other == null) + { + if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) + { + MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); + return false; + } } - else { - if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) { - int size = plots.size(); + else + { + if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) + { + final int size = plots.size(); final int currentPlots = (Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(other) : MainUtil.getPlayerPlotCount(loc.getWorld(), other)) + size; - if (currentPlots > MainUtil.getAllowedPlots(other)) { + if (currentPlots > MainUtil.getAllowedPlots(other)) + { sendMessage(plr, C.CANT_TRANSFER_MORE_PLOTS); return false; } - } + } } - - if (!plot.isOwner(plr.getUUID())) { - if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) { - MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.admin.command.setowner"); - return false; - } + + if (!plot.isOwner(plr.getUUID())) + { + if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) + { + MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.admin.command.setowner"); + return false; + } } - + final String world = loc.getWorld(); final UUID uuid = getUUID(args[0]); - if (uuid == null) { + if (uuid == null) + { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - for (final PlotId id : plots) { + for (final PlotId id : plots) + { Plot current = PS.get().getPlot(world, id); - if (current == null) { + if (current == null) + { current = MainUtil.getPlot(world, id); current.owner = uuid; current.create(); } - else { + else + { current.owner = uuid; DBFunc.setOwner(current, current.owner); } @@ -121,8 +137,9 @@ public class SetOwner extends SubCommand { } MainUtil.setSign(args[0], plot); MainUtil.sendMessage(plr, C.SET_OWNER); - if (other != null) { - MainUtil.sendMessage(other, C.NOW_OWNER, plot.world + ";" + plot.id); + if (other != null) + { + MainUtil.sendMessage(other, C.NOW_OWNER, plot.world + ";" + plot.id); } return true; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/src/main/java/com/intellectualcrafters/plot/commands/Setup.java index 502d53491..e18b84d0b 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Setup.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Setup.java @@ -39,26 +39,31 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "setup", - permission = "plots.admin.command.setup", - description = "Setup wizard for plot worlds", - usage = "/plot setup", - aliases = {"create"}, - category = CommandCategory.ACTIONS -) -public class Setup extends SubCommand { +command = "setup", +permission = "plots.admin.command.setup", +description = "Setup wizard for plot worlds", +usage = "/plot setup", +aliases = { "create" }, +category = CommandCategory.ACTIONS) +public class Setup extends SubCommand +{ - public void displayGenerators(PlotPlayer plr) { - StringBuffer message = new StringBuffer(); + public void displayGenerators(final PlotPlayer plr) + { + final StringBuffer message = new StringBuffer(); message.append("&6What generator do you want?"); - for (Entry> entry : SetupUtils.generators.entrySet()) { - if (entry.getKey().equals("PlotSquared")) { + for (final Entry> entry : SetupUtils.generators.entrySet()) + { + if (entry.getKey().equals("PlotSquared")) + { message.append("\n&8 - &2" + entry.getKey() + " (Default Generator)"); } - else if (entry.getValue().isFull()) { + else if (entry.getValue().isFull()) + { message.append("\n&8 - &7" + entry.getKey() + " (Plot Generator)"); } - else { + else + { message.append("\n&8 - &7" + entry.getKey() + " (Unknown structure)"); } } @@ -66,10 +71,12 @@ public class Setup extends SubCommand { } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { // going through setup - String name = plr.getName(); - if (!SetupUtils.setupMap.containsKey(name)) { + final String name = plr.getName(); + if (!SetupUtils.setupMap.containsKey(name)) + { final SetupObject object = new SetupObject(); SetupUtils.setupMap.put(name, object); SetupUtils.manager.updateGenerators(); @@ -77,29 +84,38 @@ public class Setup extends SubCommand { displayGenerators(plr); return false; } - if (args.length == 1) { - if (args[0].equalsIgnoreCase("cancel")) { + if (args.length == 1) + { + if (args[0].equalsIgnoreCase("cancel")) + { SetupUtils.setupMap.remove(name); MainUtil.sendMessage(plr, "&aCancelled setup"); return false; } - if (args[0].equalsIgnoreCase("back")) { + if (args[0].equalsIgnoreCase("back")) + { final SetupObject object = SetupUtils.setupMap.get(name); - if (object.setup_index > 0) { + 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() + ""); return false; - } else if (object.current > 0) { + } + else if (object.current > 0) + { object.current--; } } } final SetupObject object = SetupUtils.setupMap.get(name); final int index = object.current; - switch (index) { - case 0: { // choose generator - if ((args.length != 1) || !SetupUtils.generators.containsKey(args[0])) { + 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")); sendMessage(plr, C.SETUP_INIT); @@ -111,40 +127,50 @@ public class Setup extends SubCommand { 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 - List allTypes = Arrays.asList(new String[] { "default", "augmented", "partial"}); - List allDesc = Arrays.asList(new String[] { "Standard plot generation", "Plot generation with vanilla terrain", "Vanilla with clusters of plots"}); - ArrayList types = new ArrayList<>(); - if (SetupUtils.generators.get(object.setupGenerator).isFull()) { + case 1: + { // choose world type + final List allTypes = Arrays.asList(new String[] { "default", "augmented", "partial" }); + final List allDesc = Arrays.asList(new String[] { "Standard plot generation", "Plot generation with vanilla terrain", "Vanilla with clusters of plots" }); + final ArrayList types = new ArrayList<>(); + if (SetupUtils.generators.get(object.setupGenerator).isFull()) + { types.add("default"); } types.add("augmented"); - if (Settings.ENABLE_CLUSTERS) { + if (Settings.ENABLE_CLUSTERS) + { types.add("partial"); } - if ((args.length != 1) || !types.contains(args[0].toLowerCase())) { + if ((args.length != 1) || !types.contains(args[0].toLowerCase())) + { MainUtil.sendMessage(plr, "&cYou must choose a world type!"); - for (String type : types) { - int i = allTypes.indexOf(type); - if (type.equals("default")) { + for (final String type : types) + { + final int i = allTypes.indexOf(type); + if (type.equals("default")) + { MainUtil.sendMessage(plr, "&8 - &2" + type + " &8-&7 " + allDesc.get(i)); } - else { + else + { MainUtil.sendMessage(plr, "&8 - &7" + type + " &8-&7 " + allDesc.get(i)); } } return false; } object.type = allTypes.indexOf(args[0].toLowerCase()); - PlotGenerator gen = SetupUtils.generators.get(object.setupGenerator); - if (object.type == 0) { + final PlotGenerator gen = SetupUtils.generators.get(object.setupGenerator); + if (object.type == 0) + { object.current++; - if (object.step == null) { + if (object.step == null) + { object.plotManager = object.setupGenerator; object.step = SetupUtils.generators.get(object.plotManager).getNewPlotWorld(null).getSettingNodes(); SetupUtils.generators.get(object.plotManager).processSetup(object); } - if (object.step.length == 0) { + if (object.step.length == 0) + { object.current = 4; MainUtil.sendMessage(plr, "&6What do you want your world to be called?"); object.setup_index = 0; @@ -152,93 +178,125 @@ public class Setup extends SubCommand { } final 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()) { + } + else + { + if (gen.isFull()) + { object.plotManager = object.setupGenerator; object.setupGenerator = null; object.step = SetupUtils.generators.get(object.plotManager).getNewPlotWorld(null).getSettingNodes(); SetupUtils.generators.get(object.plotManager).processSetup(object); } - else { + 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).getNewPlotWorld(null).getSettingNodes(); } - 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 seperated by roads" + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + 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 seperated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); } object.current++; break; } - case 2: { // Choose terrain + case 2: + { // Choose terrain final List terrain = Arrays.asList(new String[] { "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 seperated by roads" + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + 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 seperated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); return false; } object.terrain = terrain.indexOf(args[0].toLowerCase()); object.current++; - if (object.step == null) { + if (object.step == null) + { object.step = SetupUtils.generators.get(object.plotManager).getNewPlotWorld(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() + ""); break; } - case 3: { // world setup - if (object.setup_index == object.step.length) { + case 3: + { // world setup + if (object.setup_index == object.step.length) + { MainUtil.sendMessage(plr, "&6What do you want your world to be called?"); object.setup_index = 0; object.current++; return true; } ConfigurationNode step = object.step[object.setup_index]; - if (args.length < 1) { + if (args.length < 1) + { 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]); - if (valid) { + if (valid) + { sendMessage(plr, C.SETUP_VALID_ARG, step.getConstant(), args[0]); step.setValue(args[0]); object.setup_index++; - if (object.setup_index == object.step.length) { + if (object.setup_index == object.step.length) + { onCommand(plr, args); return false; } step = object.step[object.setup_index]; sendMessage(plr, C.SETUP_STEP, object.setup_index + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); return false; - } else { + } + 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() + ""); return false; } } - case 4: { - if (args.length != 1) { + case 4: + { + if (args.length != 1) + { MainUtil.sendMessage(plr, "&cYou need to choose a world name!"); return false; } - if (BlockManager.manager.isWorld(args[0])) { - if (PS.get().isPlotWorld(args[0])) { + if (BlockManager.manager.isWorld(args[0])) + { + if (PS.get().isPlotWorld(args[0])) + { MainUtil.sendMessage(plr, "&cThat world name is already taken!"); 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!"); + 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!"); } object.world = args[0]; SetupUtils.setupMap.remove(name); final String world; - if (object.setupManager == null) { + if (object.setupManager == null) + { world = SetupUtils.manager.setupWorld(object); } - else { + else + { world = object.setupManager.setupWorld(object); } - try { + try + { plr.teleport(BlockManager.manager.getSpawn(world)); - } catch (final Exception e) { + } + catch (final Exception e) + { plr.sendMessage("&cAn error occured. See console for more information"); e.printStackTrace(); } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java b/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java index 3ea1ca413..6311e5e95 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java @@ -1,52 +1,53 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.commands; - -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotPlayer; - -/** - * SubCommand class - * - * @author Citymonstret - */ -@SuppressWarnings({ "deprecation", "unused" }) -public abstract class SubCommand extends com.plotsquared.general.commands.Command { - - /** - * The category - */ - public CommandCategory category; - - /** - * Send a message - * - * @param plr Player who will receive the mssage - * @param c Caption - * @param args Arguments (%s's) - * - * @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, C, String...) - */ - public boolean sendMessage(PlotPlayer plr, final C c, final String... args) { - c.send(plr, args); - return true; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.commands; + +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.object.PlotPlayer; + +/** + * SubCommand class + * + */ +@SuppressWarnings({ "deprecation", "unused" }) +public abstract class SubCommand extends com.plotsquared.general.commands.Command +{ + + /** + * The category + */ + public CommandCategory category; + + /** + * Send a message + * + * @param plr Player who will receive the mssage + * @param c Caption + * @param args Arguments (%s's) + * + * @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, C, String...) + */ + public boolean sendMessage(final PlotPlayer plr, final C c, final String... args) + { + c.send(plr, args); + return true; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Swap.java b/src/main/java/com/intellectualcrafters/plot/commands/Swap.java index edcdbbd70..d7abf8d07 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Swap.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Swap.java @@ -36,95 +36,104 @@ import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "swap", - description = "Swap two plots", - aliases = {"switch"}, - category = CommandCategory.ACTIONS, - requiredType = RequiredType.NONE -) -public class Swap extends SubCommand { +command = "swap", +description = "Swap two plots", +aliases = { "switch" }, +category = CommandCategory.ACTIONS, +requiredType = RequiredType.NONE) +public class Swap extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { - + public boolean onCommand(final PlotPlayer plr, final String[] args) + { + MainUtil.sendMessage(plr, "&cThis command has not been optimized for large selections yet. Please bug me if this becomes an issue."); - if (args.length < 1) { + if (args.length < 1) + { MainUtil.sendMessage(plr, C.NEED_PLOT_ID); MainUtil.sendMessage(plr, C.SWAP_SYNTAX); return false; } final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if (plot == null) { - return !sendMessage(plr, C.NOT_IN_PLOT); - } - if ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.swap")) { + if (plot == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } + if ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.swap")) + { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } - - Plot bot1 = MainUtil.getBottomPlot(plot); - Plot top1 = MainUtil.getTopPlot(plot); - - PlotId id2 = PlotId.fromString(args[0]); - if (id2 == null) { + + final Plot bot1 = MainUtil.getBottomPlot(plot); + final Plot top1 = MainUtil.getTopPlot(plot); + + final PlotId id2 = PlotId.fromString(args[0]); + if (id2 == null) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.SWAP_SYNTAX); return false; } final String world = loc.getWorld(); - Plot plot2 = MainUtil.getPlot(world, id2); - PlotId id3 = new PlotId(id2.x + top1.id.x - bot1.id.x, id2.y + top1.id.y - bot1.id.y); - Plot plot3 = MainUtil.getPlot(world, id3); - + final Plot plot2 = MainUtil.getPlot(world, id2); + final PlotId id3 = new PlotId((id2.x + top1.id.x) - bot1.id.x, (id2.y + top1.id.y) - bot1.id.y); + final Plot plot3 = MainUtil.getPlot(world, id3); + // Getting secon selection - Plot bot2 = MainUtil.getBottomPlot(plot2); - Plot top2 = MainUtil.getTopPlot(plot3); + final Plot bot2 = MainUtil.getBottomPlot(plot2); + final Plot top2 = MainUtil.getTopPlot(plot3); // cancel swap if intersection - PlotCluster cluster1 = new PlotCluster(world, bot1.id, top1.id, null); - PlotClusterId cluster2id = new PlotClusterId(bot2.id, top2.id); - if (ClusterManager.intersects(cluster1, cluster2id)) { + final PlotCluster cluster1 = new PlotCluster(world, bot1.id, top1.id, null); + final PlotClusterId cluster2id = new PlotClusterId(bot2.id, top2.id); + if (ClusterManager.intersects(cluster1, cluster2id)) + { MainUtil.sendMessage(plr, C.SWAP_OVERLAP); return false; } - + // Check dimensions - if (top1.id.x - bot1.id.x != top2.id.x - bot2.id.x || top1.id.y - bot1.id.y != top2.id.y - bot2.id.y ) { + if (((top1.id.x - bot1.id.x) != (top2.id.x - bot2.id.x)) || ((top1.id.y - bot1.id.y) != (top2.id.y - bot2.id.y))) + { MainUtil.sendMessage(plr, C.SWAP_DIMENSIONS, "1"); MainUtil.sendMessage(plr, C.SWAP_SYNTAX); return false; } - + // Getting selections as ids final ArrayList selection1 = MainUtil.getPlotSelectionIds(bot1.id, top1.id); final ArrayList selection2 = MainUtil.getPlotSelectionIds(bot2.id, top2.id); // Getting selections as location coordinates - Location pos1 = MainUtil.getPlotBottomLocAbs(world, bot1.id); - Location pos2 = MainUtil.getPlotTopLocAbs(world, top1.id).subtract(1, 0, 1); - Location pos3 = MainUtil.getPlotBottomLocAbs(world, bot2.id); - Location pos4 = MainUtil.getPlotTopLocAbs(world, top2.id).subtract(1, 0, 1); - - if (MainUtil.getPlot(pos2) != null) { + final Location pos1 = MainUtil.getPlotBottomLocAbs(world, bot1.id); + final Location pos2 = MainUtil.getPlotTopLocAbs(world, top1.id).subtract(1, 0, 1); + final Location pos3 = MainUtil.getPlotBottomLocAbs(world, bot2.id); + final Location pos4 = MainUtil.getPlotTopLocAbs(world, top2.id).subtract(1, 0, 1); + + if (MainUtil.getPlot(pos2) != null) + { pos1.add(1, 0, 1); pos2.add(1, 0, 1); pos3.add(1, 0, 1); pos4.add(1, 0, 1); } - + // Swapping the blocks, states and entites ChunkManager.manager.swap(world, pos1, pos2, pos3, pos4); - + // Swapping the plot data - for (int i = 0; i < selection1.size(); i++) { - final boolean last = i == selection1.size() - 1; - PlotId swaper = selection1.get(i); - PlotId swapee = selection2.get(i); - MainUtil.swapData(world, swaper, swapee, new Runnable() { + for (int i = 0; i < selection1.size(); i++) + { + final boolean last = i == (selection1.size() - 1); + final PlotId swaper = selection1.get(i); + final PlotId swapee = selection2.get(i); + MainUtil.swapData(world, swaper, swapee, new Runnable() + { @Override - public void run() { - if (last) { + public void run() + { + if (last) + { MainUtil.sendMessage(plr, C.SWAP_SUCCESS); } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/TP.java b/src/main/java/com/intellectualcrafters/plot/commands/TP.java index f0337a99f..d414a2d66 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/TP.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/TP.java @@ -34,74 +34,84 @@ import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "tp", - description = "Teleport to a plot", - permission = "plots.tp", - usage = "/plot tp ", - requiredType = RequiredType.NONE, - category = CommandCategory.TELEPORT -) -public class TP extends SubCommand { +command = "tp", +description = "Teleport to a plot", +permission = "plots.tp", +usage = "/plot tp ", +requiredType = RequiredType.NONE, +category = CommandCategory.TELEPORT) +public class TP extends SubCommand +{ - public TP() { + public TP() + { requiredArguments = new Argument[] { - Argument.String + Argument.String }; } @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final String id = args[0]; PlotId plotid; final Location loc = plr.getLocation(); final String pworld = loc.getWorld(); String world = pworld; - if (args.length == 2) { - if (BlockManager.manager.isWorld(args[1])) { + if (args.length == 2) + { + if (BlockManager.manager.isWorld(args[1])) + { world = args[1]; } } - if (!PS.get().isPlotWorld(world)) { + if (!PS.get().isPlotWorld(world)) + { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; } Plot temp; - if ((temp = isAlias(world, id)) != null) { + if ((temp = isAlias(world, id)) != null) + { MainUtil.teleportPlayer(plr, plr.getLocation(), temp); return true; } - try { + try + { plotid = new PlotId(Integer.parseInt(id.split(";")[0]), Integer.parseInt(id.split(";")[1])); MainUtil.teleportPlayer(plr, plr.getLocation(), MainUtil.getPlot(world, plotid)); return true; - } catch (final Exception e) { + } + catch (final Exception e) + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); } return false; } - private Plot isAlias(final String world, String a) { + private Plot isAlias(final String world, String a) + { int index = 0; - if (a.contains(";")) { + if (a.contains(";")) + { final String[] split = a.split(";"); - if ((split[1].length() > 0) && MathMan.isInteger(split[1])) { + if ((split[1].length() > 0) && MathMan.isInteger(split[1])) + { index = Integer.parseInt(split[1]); } a = split[0]; } final PlotPlayer player = UUIDHandler.getPlayer(a); - if (player != null) { + if (player != null) + { final java.util.Set plotMainPlots = PS.get().getPlots(world, player); final Plot[] plots = plotMainPlots.toArray(new Plot[plotMainPlots.size()]); - if (plots.length > index) { - return plots[index]; - } + if (plots.length > index) { return plots[index]; } return null; } - for (final Plot p : PS.get().getPlotsInWorld(world)) { - if ((p.getSettings().getAlias().length() > 0) && p.getSettings().getAlias().equalsIgnoreCase(a)) { - return p; - } + for (final Plot p : PS.get().getPlotsInWorld(world)) + { + if ((p.getSettings().getAlias().length() > 0) && p.getSettings().getAlias().equalsIgnoreCase(a)) { return p; } } return null; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Target.java b/src/main/java/com/intellectualcrafters/plot/commands/Target.java index 1d4926053..e4716a6b9 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Target.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Target.java @@ -28,41 +28,47 @@ import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "target", - usage = "/plot target ", - description = "Target a plot with your compass", - permission = "plots.target", - requiredType = RequiredType.NONE, - category = CommandCategory.ACTIONS -) -public class Target extends SubCommand { +command = "target", +usage = "/plot target ", +description = "Target a plot with your compass", +permission = "plots.target", +requiredType = RequiredType.NONE, +category = CommandCategory.ACTIONS) +public class Target extends SubCommand +{ @Override - public boolean onCommand(final PlotPlayer plr, final String[] args) { + public boolean onCommand(final PlotPlayer plr, final String[] args) + { final Location ploc = plr.getLocation(); - if (!PS.get().isPlotWorld(ploc.getWorld())) { + if (!PS.get().isPlotWorld(ploc.getWorld())) + { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; } PlotId id = MainUtil.parseId(args[0]); - if (id == null) { - if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) { + if (id == null) + { + if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) + { Plot closest = null; int distance = Integer.MAX_VALUE; - for (Plot plot : PS.get().getPlotsInWorld(ploc.getWorld())) { - double current = plot.getBottom().getEuclideanDistanceSquared(ploc); - if (current < distance) { + for (final Plot plot : PS.get().getPlotsInWorld(ploc.getWorld())) + { + final double current = plot.getBottom().getEuclideanDistanceSquared(ploc); + if (current < distance) + { distance = (int) current; closest = plot; } } id = closest.id; } - else { + else + { MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/src/main/java/com/intellectualcrafters/plot/commands/Template.java index b73eecb22..a5f72d2f0 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Template.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Template.java @@ -47,35 +47,38 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( - command = "template", - permission = "plots.admin", - description = "Create or use a world template", - usage = "/plot template [import|export]