diff --git a/.gitignore b/.gitignore index 44b07f9a7..ef5120f08 100644 --- a/.gitignore +++ b/.gitignore @@ -100,4 +100,5 @@ hs_err_pid* /target /plotsquared/target *.MF -PlotSquared/schematic.zip \ No newline at end of file +PlotSquared/schematic.zip +*.bat \ No newline at end of file diff --git a/PlotSquared/pom.xml b/PlotSquared/pom.xml index feb9f887b..2798001d1 100644 --- a/PlotSquared/pom.xml +++ b/PlotSquared/pom.xml @@ -8,7 +8,7 @@ UTF-8 PlotSquared - 2.11.27 + 2.12.5 PlotSquared jar @@ -48,10 +48,6 @@ - - bukkit-repo - http://repo.bukkit.org/content/groups/public/ - empcraft-repo http://empcraft.com/maven2 @@ -82,7 +78,7 @@ org.bukkit bukkit - 1.8.3-R0.1-SNAPSHOT + 1.8-R0.1-SNAPSHOT com.sk89q @@ -107,5 +103,10 @@ 1.5 provided + + com.google.code.gson + gson + 2.3.1 + \ No newline at end of file diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/Configuration.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/Configuration.java new file mode 100644 index 000000000..a912b5323 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/Configuration.java @@ -0,0 +1,84 @@ +package com.intellectualcrafters.configuration; + +import java.util.Map; + +/** + * Represents a source of configurable options and settings + */ +public interface Configuration extends ConfigurationSection { + /** + * Sets the default value of the given path as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

+ * If value is null, the value will be removed from the default + * Configuration source. + * + * @param path Path of the value to set. + * @param value Value to set the default to. + * @throws IllegalArgumentException Thrown if path is null. + */ + public void addDefault(String path, Object value); + + /** + * Sets the default values of the given paths as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default values. + * + * @param defaults A map of Path->Values to add to defaults. + * @throws IllegalArgumentException Thrown if defaults is null. + */ + public void addDefaults(Map defaults); + + /** + * Sets the default values of the given paths as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

+ * This method will not hold a reference to the specified Configuration, + * nor will it automatically update if that Configuration ever changes. If + * you require this, you should set the default source with {@link + * #setDefaults(com.intellectualcrafters.configuration.Configuration)}. + * + * @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); + + /** + * Sets the source of all default values for this {@link Configuration}. + *

+ * If a previous source was set, or previous default values were defined, + * then they will not be copied to the new source. + * + * @param defaults New source of default values for this configuration. + * @throws IllegalArgumentException Thrown if defaults is null or this. + */ + public void setDefaults(Configuration defaults); + + /** + * Gets the source {@link Configuration} for this configuration. + *

+ * If no configuration source was set, but default values were added, then + * a {@link MemoryConfiguration} will be returned. If no source was set + * and no defaults were set, then this method will return null. + * + * @return Configuration source for default values, or null if none exist. + */ + public Configuration getDefaults(); + + /** + * Gets the {@link ConfigurationOptions} for this {@link Configuration}. + *

+ * All setters through this method are chainable. + * + * @return Options for this configuration + */ + public ConfigurationOptions options(); +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java new file mode 100644 index 000000000..4f32c6545 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java @@ -0,0 +1,90 @@ +package com.intellectualcrafters.configuration; + +/** + * Various settings for controlling the input and output of a {@link + * Configuration} + */ +public class ConfigurationOptions { + private char pathSeparator = '.'; + private boolean copyDefaults = false; + private final Configuration configuration; + + protected ConfigurationOptions(Configuration configuration) { + this.configuration = configuration; + } + + /** + * Returns the {@link Configuration} that this object is responsible for. + * + * @return Parent configuration + */ + public Configuration configuration() { + return configuration; + } + + /** + * Gets the char that will be used to separate {@link + * ConfigurationSection}s + *

+ * This value does not affect how the {@link Configuration} is stored, + * only in how you access the data. The default value is '.'. + * + * @return Path separator + */ + public char pathSeparator() { + return pathSeparator; + } + + /** + * Sets the char that will be used to separate {@link + * ConfigurationSection}s + *

+ * This value does not affect how the {@link Configuration} is stored, + * only in how you access the data. The default value is '.'. + * + * @param value Path separator + * @return This object, for chaining + */ + public ConfigurationOptions pathSeparator(char value) { + this.pathSeparator = value; + return this; + } + + /** + * Checks if the {@link Configuration} should copy values from its default + * {@link Configuration} directly. + *

+ * If this is true, all values in the default Configuration will be + * directly copied, making it impossible to distinguish between values + * that were set and values that are provided by default. As a result, + * {@link ConfigurationSection#contains(java.lang.String)} will always + * return the same value as {@link + * ConfigurationSection#isSet(java.lang.String)}. The default value is + * false. + * + * @return Whether or not defaults are directly copied + */ + public boolean copyDefaults() { + return copyDefaults; + } + + /** + * Sets if the {@link Configuration} should copy values from its default + * {@link Configuration} directly. + *

+ * If this is true, all values in the default Configuration will be + * directly copied, making it impossible to distinguish between values + * that were set and values that are provided by default. As a result, + * {@link ConfigurationSection#contains(java.lang.String)} will always + * return the same value as {@link + * ConfigurationSection#isSet(java.lang.String)}. The default value is + * false. + * + * @param value Whether or not defaults are directly copied + * @return This object, for chaining + */ + public ConfigurationOptions copyDefaults(boolean value) { + this.copyDefaults = value; + return this; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java new file mode 100644 index 000000000..9e368b566 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java @@ -0,0 +1,642 @@ +package com.intellectualcrafters.configuration; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Represents a section of a {@link Configuration} + */ +public interface ConfigurationSection { + /** + * Gets a set containing all keys in this section. + *

+ * If deep is set to true, then this will contain all the keys within any + * child {@link ConfigurationSection}s (and their children, etc). These + * will be in a valid path notation for you to use. + *

+ * If deep is set to false, then this will contain only the keys of any + * direct children, and not their own children. + * + * @param deep Whether or not to get a deep list, as opposed to a shallow + * list. + * @return Set of keys contained within this ConfigurationSection. + */ + public Set getKeys(boolean deep); + + /** + * Gets a Map containing all keys and their values for this section. + *

+ * If deep is set to true, then this will contain all the keys and values + * within any child {@link ConfigurationSection}s (and their children, + * etc). These keys will be in a valid path notation for you to use. + *

+ * If deep is set to false, then this will contain only the keys and + * values of any direct children, and not their own children. + * + * @param deep Whether or not to get a deep list, as opposed to a shallow + * list. + * @return Map of keys and values of this section. + */ + public Map getValues(boolean deep); + + /** + * Checks if this {@link ConfigurationSection} contains the given path. + *

+ * If the value for the requested path does not exist but a default value + * has been specified, this will return true. + * + * @param path Path to check for existence. + * @return True if this section contains the requested path, either via + * default or being set. + * @throws IllegalArgumentException Thrown when path is null. + */ + public boolean contains(String path); + + /** + * Checks if this {@link ConfigurationSection} has a value set for the + * given path. + *

+ * If the value for the requested path does not exist but a default value + * has been specified, this will still return false. + * + * @param path Path to check for existence. + * @return True if this section contains the requested path, regardless of + * having a default. + * @throws IllegalArgumentException Thrown when path is null. + */ + public boolean isSet(String path); + + /** + * Gets the path of this {@link ConfigurationSection} from its root {@link + * Configuration} + *

+ * For any {@link Configuration} themselves, this will return an empty + * string. + *

+ * If the section is no longer contained within its root for any reason, + * such as being replaced with a different value, this may return null. + *

+ * To retrieve the single name of this section, that is, the final part of + * the path returned by this method, you may use {@link #getName()}. + * + * @return Path of this section relative to its root + */ + public String getCurrentPath(); + + /** + * Gets the name of this individual {@link ConfigurationSection}, in the + * path. + *

+ * This will always be the final part of {@link #getCurrentPath()}, unless + * the section is orphaned. + * + * @return Name of this section + */ + public String getName(); + + /** + * Gets the root {@link Configuration} that contains this {@link + * ConfigurationSection} + *

+ * For any {@link Configuration} themselves, this will return its own + * object. + *

+ * If the section is no longer contained within its root for any reason, + * such as being replaced with a different value, this may return null. + * + * @return Root configuration containing this section. + */ + public Configuration getRoot(); + + /** + * Gets the parent {@link ConfigurationSection} that directly contains + * this {@link ConfigurationSection}. + *

+ * For any {@link Configuration} themselves, this will return null. + *

+ * If the section is no longer contained within its parent for any reason, + * such as being replaced with a different value, this may return null. + * + * @return Parent section containing this section. + */ + public ConfigurationSection getParent(); + + /** + * Gets the requested Object by path. + *

+ * If the Object does not exist but a default value has been specified, + * this will return the default value. If the Object does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Object to get. + * @return Requested Object. + */ + public Object get(String path); + + /** + * Gets the requested Object by path, returning a default value if not + * found. + *

+ * If the Object does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Object to get. + * @param def The default value to return if the path is not found. + * @return Requested Object. + */ + public Object get(String path, Object def); + + /** + * Sets the specified path to the given value. + *

+ * If value is null, the entry will be removed. Any existing entry will be + * replaced, regardless of what the new value is. + *

+ * Some implementations may have limitations on what you may store. See + * their individual javadocs for details. No implementations should allow + * you to store {@link Configuration}s or {@link ConfigurationSection}s, + * please use {@link #createSection(java.lang.String)} for that. + * + * @param path Path of the object to set. + * @param value New value to set the path to. + */ + public void set(String path, Object value); + + /** + * Creates an empty {@link ConfigurationSection} at the specified path. + *

+ * Any value that was previously set at this path will be overwritten. If + * the previous value was itself a {@link ConfigurationSection}, it will + * be orphaned. + * + * @param path Path to create the section at. + * @return Newly created section + */ + public ConfigurationSection createSection(String path); + + /** + * Creates a {@link ConfigurationSection} at the specified path, with + * specified values. + *

+ * Any value that was previously set at this path will be overwritten. If + * the previous value was itself a {@link ConfigurationSection}, it will + * be orphaned. + * + * @param path Path to create the section at. + * @param map The values to used. + * @return Newly created section + */ + public ConfigurationSection createSection(String path, Map map); + + // Primitives + /** + * Gets the requested String by path. + *

+ * If the String does not exist but a default value has been specified, + * this will return the default value. If the String does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the String to get. + * @return Requested String. + */ + public String getString(String path); + + /** + * Gets the requested String by path, returning a default value if not + * found. + *

+ * If the String does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the String to get. + * @param def The default value to return if the path is not found or is + * not a String. + * @return Requested String. + */ + public String getString(String path, String def); + + /** + * Checks if the specified path is a String. + *

+ * If the path exists but is not a String, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a String and return appropriately. + * + * @param path Path of the String to check. + * @return Whether or not the specified path is a String. + */ + public boolean isString(String path); + + /** + * Gets the requested int by path. + *

+ * If the int does not exist but a default value has been specified, this + * will return the default value. If the int does not exist and no default + * value was specified, this will return 0. + * + * @param path Path of the int to get. + * @return Requested int. + */ + public int getInt(String path); + + /** + * Gets the requested int by path, returning a default value if not found. + *

+ * If the int does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the int to get. + * @param def The default value to return if the path is not found or is + * not an int. + * @return Requested int. + */ + public int getInt(String path, int def); + + /** + * Checks if the specified path is an int. + *

+ * If the path exists but is not a int, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a int and return appropriately. + * + * @param path Path of the int to check. + * @return Whether or not the specified path is an int. + */ + public boolean isInt(String path); + + /** + * Gets the requested boolean by path. + *

+ * If the boolean does not exist but a default value has been specified, + * this will return the default value. If the boolean does not exist and + * no default value was specified, this will return false. + * + * @param path Path of the boolean to get. + * @return Requested boolean. + */ + public boolean getBoolean(String path); + + /** + * Gets the requested boolean by path, returning a default value if not + * found. + *

+ * If the boolean does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the boolean to get. + * @param def The default value to return if the path is not found or is + * not a boolean. + * @return Requested boolean. + */ + public boolean getBoolean(String path, boolean def); + + /** + * Checks if the specified path is a boolean. + *

+ * If the path exists but is not a boolean, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a boolean and return appropriately. + * + * @param path Path of the boolean to check. + * @return Whether or not the specified path is a boolean. + */ + public boolean isBoolean(String path); + + /** + * Gets the requested double by path. + *

+ * If the double does not exist but a default value has been specified, + * this will return the default value. If the double does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the double to get. + * @return Requested double. + */ + public double getDouble(String path); + + /** + * Gets the requested double by path, returning a default value if not + * found. + *

+ * If the double does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the double to get. + * @param def The default value to return if the path is not found or is + * not a double. + * @return Requested double. + */ + public double getDouble(String path, double def); + + /** + * Checks if the specified path is a double. + *

+ * If the path exists but is not a double, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a double and return appropriately. + * + * @param path Path of the double to check. + * @return Whether or not the specified path is a double. + */ + public boolean isDouble(String path); + + /** + * Gets the requested long by path. + *

+ * If the long does not exist but a default value has been specified, this + * will return the default value. If the long does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the long to get. + * @return Requested long. + */ + public long getLong(String path); + + /** + * Gets the requested long by path, returning a default value if not + * found. + *

+ * If the long does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the long to get. + * @param def The default value to return if the path is not found or is + * not a long. + * @return Requested long. + */ + public long getLong(String path, long def); + + /** + * Checks if the specified path is a long. + *

+ * If the path exists but is not a long, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a long and return appropriately. + * + * @param path Path of the long to check. + * @return Whether or not the specified path is a long. + */ + public boolean isLong(String path); + + // Java + /** + * Gets the requested List by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the List to get. + * @return Requested List. + */ + public List getList(String path); + + /** + * Gets the requested List by path, returning a default value if not + * found. + *

+ * If the List does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the List to get. + * @param def The default value to return if the path is not found or is + * not a List. + * @return Requested List. + */ + public List getList(String path, List def); + + /** + * Checks if the specified path is a List. + *

+ * If the path exists but is not a List, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a List and return appropriately. + * + * @param path Path of the List to check. + * @return Whether or not the specified path is a List. + */ + public boolean isList(String path); + + /** + * Gets the requested List of String by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a String if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of String. + */ + public List getStringList(String path); + + /** + * Gets the requested List of Integer by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Integer if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Integer. + */ + public List getIntegerList(String path); + + /** + * Gets the requested List of Boolean by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Boolean if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Boolean. + */ + public List getBooleanList(String path); + + /** + * Gets the requested List of Double by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Double if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Double. + */ + public List getDoubleList(String path); + + /** + * Gets the requested List of Float by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Float if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Float. + */ + public List getFloatList(String path); + + /** + * Gets the requested List of Long by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Long if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Long. + */ + public List getLongList(String path); + + /** + * Gets the requested List of Byte by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Byte if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Byte. + */ + public List getByteList(String path); + + /** + * Gets the requested List of Character by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Character if + * possible, but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Character. + */ + public List getCharacterList(String path); + + /** + * Gets the requested List of Short by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Short if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Short. + */ + public List getShortList(String path); + + /** + * Gets the requested List of Maps by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Map if possible, but + * may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Maps. + */ + public List> getMapList(String path); + + /** + * Gets the requested ConfigurationSection by path. + *

+ * If the ConfigurationSection does not exist but a default value has been + * specified, this will return the default value. If the + * ConfigurationSection does not exist and no default value was specified, + * this will return null. + * + * @param path Path of the ConfigurationSection to get. + * @return Requested ConfigurationSection. + */ + public ConfigurationSection getConfigurationSection(String path); + + /** + * Checks if the specified path is a ConfigurationSection. + *

+ * If the path exists but is not a ConfigurationSection, this will return + * false. If the path does not exist, this will return false. If the path + * does not exist but a default value has been specified, this will check + * if that default value is a ConfigurationSection and return + * appropriately. + * + * @param path Path of the ConfigurationSection to check. + * @return Whether or not the specified path is a ConfigurationSection. + */ + public boolean isConfigurationSection(String path); + + /** + * Gets the equivalent {@link ConfigurationSection} from the default + * {@link Configuration} defined in {@link #getRoot()}. + *

+ * If the root contains no defaults, or the defaults doesn't contain a + * value for this path, or the value at this path is not a {@link + * ConfigurationSection} then this will return null. + * + * @return Equivalent section in root configuration + */ + public ConfigurationSection getDefaultSection(); + + /** + * Sets the default value in the root at the given path as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

+ * If value is null, the value will be removed from the default + * Configuration source. + *

+ * If the value as returned by {@link #getDefaultSection()} is null, then + * this will create a new section at the path, replacing anything that may + * have existed there previously. + * + * @param path Path of the value to set. + * @param value Value to set the default to. + * @throws IllegalArgumentException Thrown if path is null. + */ + public void addDefault(String path, Object value); +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java new file mode 100644 index 000000000..38e9b0cb3 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java @@ -0,0 +1,45 @@ +package com.intellectualcrafters.configuration; + +/** + * Exception thrown when attempting to load an invalid {@link Configuration} + */ +@SuppressWarnings("serial") +public class InvalidConfigurationException extends Exception { + + /** + * Creates a new instance of InvalidConfigurationException without a + * message or cause. + */ + public InvalidConfigurationException() {} + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified message. + * + * @param msg The details of the exception. + */ + public InvalidConfigurationException(String msg) { + super(msg); + } + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified cause. + * + * @param cause The cause of the exception. + */ + public InvalidConfigurationException(Throwable cause) { + super(cause); + } + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified message and cause. + * + * @param cause The cause of the exception. + * @param msg The details of the exception. + */ + public InvalidConfigurationException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java new file mode 100644 index 000000000..ad81ab8f8 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java @@ -0,0 +1,76 @@ +package com.intellectualcrafters.configuration; + +import java.util.Map; + +/** + * This is a {@link Configuration} implementation that does not save or load + * 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 { + protected Configuration defaults; + protected MemoryConfigurationOptions options; + + /** + * Creates an empty {@link MemoryConfiguration} with no default values. + */ + public MemoryConfiguration() {} + + /** + * Creates an empty {@link MemoryConfiguration} using the specified {@link + * Configuration} as a source for all default values. + * + * @param defaults Default value provider + * @throws IllegalArgumentException Thrown if defaults is null + */ + public MemoryConfiguration(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) { + defaults = new MemoryConfiguration(); + } + + defaults.set(path, value); + } + + public void addDefaults(Map defaults) { + if (defaults == null) throw new NullPointerException("Defaults may not be null"); + + for (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"); + + addDefaults(defaults.getValues(true)); + } + + public void setDefaults(Configuration defaults) { + if (defaults == null) throw new NullPointerException("Defaults may not be null"); + + this.defaults = defaults; + } + + public Configuration getDefaults() { + return defaults; + } + + @Override + public ConfigurationSection getParent() { + return null; + } + + public MemoryConfigurationOptions options() { + if (options == null) { + options = new MemoryConfigurationOptions(this); + } + + return options; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java new file mode 100644 index 000000000..1720118c6 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java @@ -0,0 +1,28 @@ +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) { + super(configuration); + } + + @Override + public MemoryConfiguration configuration() { + return (MemoryConfiguration) super.configuration(); + } + + @Override + public MemoryConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public MemoryConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemorySection.java new file mode 100644 index 000000000..ef7f33af5 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/MemorySection.java @@ -0,0 +1,755 @@ +package com.intellectualcrafters.configuration; + +import static org.bukkit.util.NumberConversions.toDouble; +import static org.bukkit.util.NumberConversions.toInt; +import static org.bukkit.util.NumberConversions.toLong; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A type of {@link ConfigurationSection} that is stored in memory. + */ +public class MemorySection implements ConfigurationSection { + protected final Map map = new LinkedHashMap(); + private final Configuration root; + private final ConfigurationSection parent; + private final String path; + private final String fullPath; + + /** + * Creates an empty MemorySection for use as a root {@link Configuration} + * section. + *

+ * Note that calling this without being yourself a {@link Configuration} + * will throw an exception! + * + * @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"); + } + + this.path = ""; + this.fullPath = ""; + this.parent = null; + this.root = (Configuration) this; + } + + /** + * Creates an empty MemorySection with the specified parent and path. + * + * @param parent Parent section that contains this own section. + * @param path Path that you may access this section from via the root + * {@link Configuration}. + * @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"); + + this.path = path; + this.parent = parent; + this.root = parent.getRoot(); + + if (root == null) throw new NullPointerException("Path may not be orphaned"); + + this.fullPath = createPath(parent, path); + } + + public Set getKeys(boolean deep) { + Set result = new LinkedHashSet(); + + Configuration root = getRoot(); + if (root != null && root.options().copyDefaults()) { + ConfigurationSection defaults = getDefaultSection(); + + if (defaults != null) { + result.addAll(defaults.getKeys(deep)); + } + } + + mapChildrenKeys(result, this, deep); + + return result; + } + + public Map getValues(boolean deep) { + Map result = new LinkedHashMap(); + + Configuration root = getRoot(); + if (root != null && root.options().copyDefaults()) { + ConfigurationSection defaults = getDefaultSection(); + + if (defaults != null) { + result.putAll(defaults.getValues(deep)); + } + } + + mapChildrenValues(result, this, deep); + + return result; + } + + public boolean contains(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); + } + return get(path, null) != null; + } + + public String getCurrentPath() { + return fullPath; + } + + public String getName() { + return path; + } + + public Configuration getRoot() { + return root; + } + + public ConfigurationSection getParent() { + return parent; + } + + public void addDefault(String path, 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"); + } + root.addDefault(createPath(this, path), value); + } + + public ConfigurationSection getDefaultSection() { + Configuration root = getRoot(); + Configuration defaults = root == null ? null : root.getDefaults(); + + 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"); + + 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) { + section = section.createSection(node); + } else { + section = subSection; + } + } + + String key = path.substring(i2); + if (section == this) { + if (value == null) { + map.remove(key); + } else { + map.put(key, value); + } + } else { + section.set(key, value); + } + } + + public Object get(String path) { + return get(path, getDefault(path)); + } + + public Object get(String path, Object def) { + if (path == null) throw new NullPointerException("Path cannot be null"); + + if (path.length() == 0) { + return this; + } + + 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) { + section = section.getConfigurationSection(path.substring(i2, i1)); + if (section == null) { + return def; + } + } + + String key = path.substring(i2); + if (section == this) { + 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"); + } + + 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) { + section = section.createSection(node); + } else { + section = subSection; + } + } + + String key = path.substring(i2); + if (section == this) { + 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); + + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() instanceof Map) { + section.createSection(entry.getKey().toString(), (Map) entry.getValue()); + } else { + section.set(entry.getKey().toString(), entry.getValue()); + } + } + + return section; + } + + // Primitives + public String getString(String path) { + Object def = getDefault(path); + return getString(path, def != null ? def.toString() : null); + } + + public String getString(String path, String def) { + Object val = get(path, def); + return (val != null) ? val.toString() : def; + } + + public boolean isString(String path) { + Object val = get(path); + return val instanceof String; + } + + public int getInt(String path) { + Object def = getDefault(path); + return getInt(path, (def instanceof Number) ? toInt(def) : 0); + } + + public int getInt(String path, int def) { + Object val = get(path, def); + return (val instanceof Number) ? toInt(val) : def; + } + + public boolean isInt(String path) { + Object val = get(path); + return val instanceof Integer; + } + + public boolean getBoolean(String path) { + 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); + return (val instanceof Boolean) ? (Boolean) val : def; + } + + public boolean isBoolean(String path) { + Object val = get(path); + return val instanceof Boolean; + } + + public double getDouble(String path) { + Object def = getDefault(path); + return getDouble(path, (def instanceof Number) ? toDouble(def) : 0); + } + + public double getDouble(String path, double def) { + Object val = get(path, def); + return (val instanceof Number) ? toDouble(val) : def; + } + + public boolean isDouble(String path) { + Object val = get(path); + return val instanceof Double; + } + + public long getLong(String path) { + Object def = getDefault(path); + return getLong(path, (def instanceof Number) ? toLong(def) : 0); + } + + public long getLong(String path, long def) { + Object val = get(path, def); + return (val instanceof Number) ? toLong(val) : def; + } + + public boolean isLong(String path) { + Object val = get(path); + return val instanceof Long; + } + + // Java + public List getList(String path) { + 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); + return (List) ((val instanceof List) ? val : def); + } + + public boolean isList(String path) { + Object val = get(path); + return val instanceof List; + } + + public List getStringList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if ((object instanceof String) || (isPrimitiveWrapper(object))) { + result.add(String.valueOf(object)); + } + } + + return result; + } + + public List getIntegerList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Integer) { + result.add((Integer) object); + } else if (object instanceof String) { + try { + result.add(Integer.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((int) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).intValue()); + } + } + + return result; + } + + public List getBooleanList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Boolean) { + result.add((Boolean) object); + } else if (object instanceof String) { + if (Boolean.TRUE.toString().equals(object)) { + result.add(true); + } else if (Boolean.FALSE.toString().equals(object)) { + result.add(false); + } + } + } + + return result; + } + + public List getDoubleList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Double) { + result.add((Double) object); + } else if (object instanceof String) { + try { + result.add(Double.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((double) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).doubleValue()); + } + } + + return result; + } + + public List getFloatList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Float) { + result.add((Float) object); + } else if (object instanceof String) { + try { + result.add(Float.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((float) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).floatValue()); + } + } + + return result; + } + + public List getLongList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Long) { + result.add((Long) object); + } else if (object instanceof String) { + try { + result.add(Long.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((long) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).longValue()); + } + } + + return result; + } + + public List getByteList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Byte) { + result.add((Byte) object); + } else if (object instanceof String) { + try { + result.add(Byte.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((byte) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).byteValue()); + } + } + + return result; + } + + public List getCharacterList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Character) { + result.add((Character) object); + } else if (object instanceof String) { + String str = (String) object; + + if (str.length() == 1) { + result.add(str.charAt(0)); + } + } else if (object instanceof Number) { + result.add((char) ((Number) object).intValue()); + } + } + + return result; + } + + public List getShortList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Short) { + result.add((Short) object); + } else if (object instanceof String) { + try { + result.add(Short.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((short) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).shortValue()); + } + } + + return result; + } + + public List> getMapList(String path) { + List list = getList(path); + List> result = new ArrayList>(); + + if (list == null) { + return result; + } + + for (Object object : list) { + if (object instanceof Map) { + result.add((Map) object); + } + } + + return result; + } + + public ConfigurationSection getConfigurationSection(String path) { + Object val = get(path, 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); + 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 Object getDefault(String path) { + if (path == null) throw new NullPointerException("Path may not be null"); + + Configuration root = getRoot(); + 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; + + for (Map.Entry entry : sec.map.entrySet()) { + output.add(createPath(section, entry.getKey(), this)); + + if ((deep) && (entry.getValue() instanceof ConfigurationSection)) { + ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); + mapChildrenKeys(output, subsection, deep); + } + } + } else { + Set keys = section.getKeys(deep); + + for (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; + + for (Map.Entry entry : sec.map.entrySet()) { + output.put(createPath(section, entry.getKey(), this), entry.getValue()); + + if (entry.getValue() instanceof ConfigurationSection) { + if (deep) { + mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep); + } + } + } + } else { + Map values = section.getValues(deep); + + for (Map.Entry entry : values.entrySet()) { + output.put(createPath(section, entry.getKey(), this), entry.getValue()); + } + } + } + + /** + * Creates a full path to the given {@link ConfigurationSection} from its + * root {@link Configuration}. + *

+ * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. + * + * @param section Section to create a path for. + * @param key Name of the specified section. + * @return Full path of the section from its root. + */ + public static String createPath(ConfigurationSection section, String key) { + return createPath(section, key, (section == null) ? null : section.getRoot()); + } + + /** + * Creates a relative path to the given {@link ConfigurationSection} from + * the given relative section. + *

+ * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. + * + * @param section Section to create a path for. + * @param key Name of the specified section. + * @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(); + + 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); + } + + builder.insert(0, parent.getName()); + } + } + + if ((key != null) && (key.length() > 0)) { + if (builder.length() > 0) { + builder.append(separator); + } + + builder.append(key); + } + + return builder.toString(); + } + + @Override + public String toString() { + Configuration root = getRoot(); + return new StringBuilder() + .append(getClass().getSimpleName()) + .append("[path='") + .append(getCurrentPath()) + .append("', root='") + .append(root == null ? null : root.getClass().getSimpleName()) + .append("']") + .toString(); + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java new file mode 100644 index 000000000..caa269918 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java @@ -0,0 +1,286 @@ +package com.intellectualcrafters.configuration.file; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import com.intellectualcrafters.configuration.Configuration; +import com.intellectualcrafters.configuration.InvalidConfigurationException; +import com.intellectualcrafters.configuration.MemoryConfiguration; + +/** + * This is a base class for all File based implementations of {@link + * Configuration} + */ +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 + * is a strict-subset of UTF8 already (plain ASCII). + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean UTF8_OVERRIDE; + /** + * This value specifies if the system default encoding is unicode, but + * cannot parse standard ASCII. + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean UTF_BIG; + /** + * This value specifies if the system supports unicode. + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean SYSTEM_UTF; + static { + final byte[] testBytes = Base64Coder.decode("ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4NCg=="); + final String testString = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n"; + final Charset defaultCharset = Charset.defaultCharset(); + final String resultString = new String(testBytes, defaultCharset); + final boolean trueUTF = defaultCharset.name().contains("UTF"); + UTF8_OVERRIDE = !testString.equals(resultString) || defaultCharset.equals(Charset.forName("US-ASCII")); + SYSTEM_UTF = trueUTF || UTF8_OVERRIDE; + UTF_BIG = trueUTF && UTF8_OVERRIDE; + } + + /** + * Creates an empty {@link FileConfiguration} with no default values. + */ + public FileConfiguration() { + super(); + } + + /** + * Creates an empty {@link FileConfiguration} using the specified {@link + * Configuration} as a source for all default values. + * + * @param defaults Default value provider + */ + public FileConfiguration(Configuration defaults) { + super(defaults); + } + + /** + * Saves this {@link FileConfiguration} to the specified location. + *

+ * If the file does not exist, it will be created. If already exists, it + * will be overwritten. If it cannot be overwritten or created, an + * exception will be thrown. + *

+ * This method will save using the system default encoding, or possibly + * using UTF8. + * + * @param file File to save to. + * @throws IOException Thrown when the given file cannot be written to for + * 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"); + file.getParentFile().mkdirs(); + + String data = saveToString(); + + Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset()); + + try { + writer.write(data); + } finally { + writer.close(); + } + } + + /** + * Saves this {@link FileConfiguration} to the specified location. + *

+ * If the file does not exist, it will be created. If already exists, it + * will be overwritten. If it cannot be overwritten or created, an + * exception will be thrown. + *

+ * This method will save using the system default encoding, or possibly + * using UTF8. + * + * @param file File to save to. + * @throws IOException Thrown when the given file cannot be written to for + * 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"); + + save(new File(file)); + } + + /** + * Saves this {@link FileConfiguration} to a string, and returns it. + * + * @return String containing this configuration. + */ + public abstract String saveToString(); + + /** + * Loads this {@link FileConfiguration} from the specified location. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given file. + *

+ * If the file cannot be loaded for any reason, an exception will be + * thrown. + *

+ * This will attempt to use the {@link Charset#defaultCharset()} for + * files, unless {@link #UTF8_OVERRIDE} but not {@link #UTF_BIG} is + * specified. + * + * @param file File to load from. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { + if (file == null) throw new NullPointerException("File cannot be null"); + + final FileInputStream stream = new FileInputStream(file); + + load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset())); + } + + /** + * Loads this {@link FileConfiguration} from the specified stream. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given stream. + *

+ * This will attempt to use the {@link Charset#defaultCharset()}, unless + * {@link #UTF8_OVERRIDE} or {@link #UTF_BIG} is specified. + * + * @param stream Stream to load from + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when stream is null. + * @deprecated This does not consider encoding + * @see #load(Reader) + */ + @Deprecated + public void load(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())); + } + + /** + * Loads this {@link FileConfiguration} from the specified reader. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given stream. + * + * @param reader the reader to load from + * @throws IOException thrown when underlying reader throws an IOException + * @throws InvalidConfigurationException thrown when the reader does not + * 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); + + StringBuilder builder = new StringBuilder(); + + try { + String line; + + while ((line = input.readLine()) != null) { + builder.append(line); + builder.append('\n'); + } + } finally { + input.close(); + } + + loadFromString(builder.toString()); + } + + /** + * Loads this {@link FileConfiguration} from the specified location. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given file. + *

+ * If the file cannot be loaded for any reason, an exception will be + * thrown. + * + * @param file File to load from. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void load(String file) throws FileNotFoundException, IOException, InvalidConfigurationException { + if (file == null) throw new NullPointerException("File cannot be null"); + + load(new File(file)); + } + + /** + * Loads this {@link FileConfiguration} from the specified string, as + * opposed to from file. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given string. + *

+ * If the string is invalid in any way, an exception will be thrown. + * + * @param contents Contents of a Configuration to load. + * @throws InvalidConfigurationException Thrown if the specified string is + * invalid. + * @throws IllegalArgumentException Thrown if contents is null. + */ + public abstract void loadFromString(String contents) throws InvalidConfigurationException; + + /** + * Compiles the header for this {@link FileConfiguration} and returns the + * result. + *

+ * This will use the header from {@link #options()} -> {@link + * FileConfigurationOptions#header()}, respecting the rules of {@link + * FileConfigurationOptions#copyHeader()} if set. + * + * @return Compiled header + */ + protected abstract String buildHeader(); + + @Override + public FileConfigurationOptions options() { + if (options == null) { + options = new FileConfigurationOptions(this); + } + + return (FileConfigurationOptions) options; + } +} \ No newline at end of file diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java new file mode 100644 index 000000000..72936c667 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java @@ -0,0 +1,119 @@ +package com.intellectualcrafters.configuration.file; + +import com.intellectualcrafters.configuration.MemoryConfiguration; +import com.intellectualcrafters.configuration.MemoryConfigurationOptions; + +/** + * Various settings for controlling the input and output of a {@link + * FileConfiguration} + */ +public class FileConfigurationOptions extends MemoryConfigurationOptions { + private String header = null; + private boolean copyHeader = true; + + protected FileConfigurationOptions(MemoryConfiguration configuration) { + super(configuration); + } + + @Override + public FileConfiguration configuration() { + return (FileConfiguration) super.configuration(); + } + + @Override + public FileConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public FileConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } + + /** + * Gets the header that will be applied to the top of the saved output. + *

+ * This header will be commented out and applied directly at the top of + * the generated output of the {@link FileConfiguration}. It is not + * required to include a newline at the end of the header as it will + * automatically be applied, but you may include one if you wish for extra + * spacing. + *

+ * Null is a valid value which will indicate that no header is to be + * applied. The default value is null. + * + * @return Header + */ + public String header() { + return header; + } + + /** + * Sets the header that will be applied to the top of the saved output. + *

+ * This header will be commented out and applied directly at the top of + * the generated output of the {@link FileConfiguration}. It is not + * required to include a newline at the end of the header as it will + * automatically be applied, but you may include one if you wish for extra + * spacing. + *

+ * Null is a valid value which will indicate that no header is to be + * applied. + * + * @param value New header + * @return This object, for chaining + */ + public FileConfigurationOptions header(String value) { + this.header = value; + return this; + } + + /** + * Gets whether or not the header should be copied from a default source. + *

+ * If this is true, if a default {@link FileConfiguration} is passed to + * {@link + * FileConfiguration#setDefaults(com.intellectualcrafters.configuration.Configuration)} + * then upon saving it will use the header from that config, instead of + * the one provided here. + *

+ * If no default is set on the configuration, or the default is not of + * type FileConfiguration, or that config has no header ({@link #header()} + * returns null) then the header specified in this configuration will be + * used. + *

+ * Defaults to true. + * + * @return Whether or not to copy the header + */ + public boolean copyHeader() { + return copyHeader; + } + + /** + * Sets whether or not the header should be copied from a default source. + *

+ * If this is true, if a default {@link FileConfiguration} is passed to + * {@link + * FileConfiguration#setDefaults(com.intellectualcrafters.configuration.Configuration)} + * then upon saving it will use the header from that config, instead of + * the one provided here. + *

+ * If no default is set on the configuration, or the default is not of + * type FileConfiguration, or that config has no header ({@link #header()} + * returns null) then the header specified in this configuration will be + * used. + *

+ * Defaults to true. + * + * @param value Whether or not to copy the header + * @return This object, for chaining + */ + public FileConfigurationOptions copyHeader(boolean value) { + copyHeader = value; + + return this; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java new file mode 100644 index 000000000..4f395b580 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java @@ -0,0 +1,265 @@ +package com.intellectualcrafters.configuration.file; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.Map; + +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.representer.Representer; + +import com.intellectualcrafters.configuration.Configuration; +import com.intellectualcrafters.configuration.ConfigurationSection; +import com.intellectualcrafters.configuration.InvalidConfigurationException; +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 { + protected static final String COMMENT_PREFIX = "# "; + protected static final String BLANK_CONFIG = "{}\n"; + private final DumperOptions yamlOptions = new DumperOptions(); + private final Representer yamlRepresenter = new YamlRepresenter(); + private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); + + @Override + public String saveToString() { + yamlOptions.setIndent(options().indent()); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yamlOptions.setAllowUnicode(SYSTEM_UTF); + yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + String header = buildHeader(); + String dump = yaml.dump(getValues(false)); + + if (dump.equals(BLANK_CONFIG)) { + dump = ""; + } + + return header + dump; + } + + @Override + public void loadFromString(String contents) throws InvalidConfigurationException { + if (contents == null) throw new NullPointerException("Contents cannot be null"); + + Map input; + try { + input = (Map) yaml.load(contents); + } catch (YAMLException e) { + throw new InvalidConfigurationException(e); + } catch (ClassCastException e) { + throw new InvalidConfigurationException("Top level is not a Map."); + } + + String header = parseHeader(contents); + if (header.length() > 0) { + options().header(header); + } + + 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(); + + if (value instanceof Map) { + convertMapsToSections((Map) value, section.createSection(key)); + } else { + section.set(key, value); + } + } + } + + protected String parseHeader(String input) { + String[] lines = input.split("\r?\n", -1); + StringBuilder result = new StringBuilder(); + boolean readingHeader = true; + boolean foundHeader = false; + + for (int i = 0; (i < lines.length) && (readingHeader); i++) { + String line = lines[i]; + + if (line.startsWith(COMMENT_PREFIX)) { + if (i > 0) { + result.append("\n"); + } + + if (line.length() > COMMENT_PREFIX.length()) { + result.append(line.substring(COMMENT_PREFIX.length())); + } + + foundHeader = true; + } else if ((foundHeader) && (line.length() == 0)) { + result.append("\n"); + } else if (foundHeader) { + readingHeader = false; + } + } + + return result.toString(); + } + + @Override + protected String buildHeader() { + String header = options().header(); + + if (options().copyHeader()) { + Configuration def = getDefaults(); + + if ((def != null) && (def instanceof FileConfiguration)) { + FileConfiguration filedefaults = (FileConfiguration) def; + String defaultsHeader = filedefaults.buildHeader(); + + if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { + return defaultsHeader; + } + } + } + + if (header == null) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + String[] lines = header.split("\r?\n", -1); + boolean startedHeader = false; + + for (int i = lines.length - 1; i >= 0; i--) { + builder.insert(0, "\n"); + + if ((startedHeader) || (lines[i].length() != 0)) { + builder.insert(0, lines[i]); + builder.insert(0, COMMENT_PREFIX); + startedHeader = true; + } + } + + return builder.toString(); + } + + @Override + public YamlConfigurationOptions options() { + if (options == null) { + options = new YamlConfigurationOptions(this); + } + + return (YamlConfigurationOptions) options; + } + + /** + * Creates a new {@link YamlConfiguration}, loading from the given file. + *

+ * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + *

+ * The encoding used may follow the system dependent default. + * + * @param file Input file + * @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"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(file); + } catch (Exception ex) { + try { + String path = file.getAbsolutePath() + "_broken"; + File dest = new File(file.getAbsolutePath() + "_broken"); + int i = 0; + while (dest.exists()) { + dest = new File(file.getAbsolutePath() + "_broken_" + i++); + } + Files.copy( file.toPath(), dest.toPath() , StandardCopyOption.REPLACE_EXISTING); + PS.log("&dCould not read: &7" + file); + PS.log("&drenamed to: &7" + dest.getName()); + PS.log("&c============ Full stacktrace ============"); + ex.printStackTrace(); + PS.log("&c========================================="); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return config; + } + + /** + * Creates a new {@link YamlConfiguration}, loading from the given stream. + *

+ * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + * + * @param stream Input stream + * @return Resulting configuration + * @throws IllegalArgumentException Thrown if stream is null + * @deprecated does not properly consider encoding + * @see #load(InputStream) + * @see #loadConfiguration(Reader) + */ + @Deprecated + public static YamlConfiguration loadConfiguration(InputStream stream) { + if (stream == null) throw new NullPointerException("Stream cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(stream); + } catch (IOException ex) { + PS.log("Cannot load configuration from stream"); + ex.printStackTrace(); + } catch (InvalidConfigurationException ex) { + ex.printStackTrace(); + PS.log("Cannot load configuration from stream"); + } + + return config; + } + + + /** + * Creates a new {@link YamlConfiguration}, loading from the given reader. + *

+ * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + * + * @param reader input + * @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"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(reader); + } catch (IOException ex) { + PS.log("Cannot load configuration from stream"); + ex.printStackTrace(); + } catch (InvalidConfigurationException ex) { + PS.log("Cannot load configuration from stream"); + ex.printStackTrace(); + } + + return config; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java new file mode 100644 index 000000000..6783d5ce4 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java @@ -0,0 +1,69 @@ +package com.intellectualcrafters.configuration.file; + +/** + * Various settings for controlling the input and output of a {@link + * YamlConfiguration} + */ +public class YamlConfigurationOptions extends FileConfigurationOptions { + private int indent = 2; + + protected YamlConfigurationOptions(YamlConfiguration configuration) { + super(configuration); + } + + @Override + public YamlConfiguration configuration() { + return (YamlConfiguration) super.configuration(); + } + + @Override + public YamlConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public YamlConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } + + @Override + public YamlConfigurationOptions header(String value) { + super.header(value); + return this; + } + + @Override + public YamlConfigurationOptions copyHeader(boolean value) { + super.copyHeader(value); + return this; + } + + /** + * Gets how much spaces should be used to indent each line. + *

+ * The minimum value this may be is 2, and the maximum is 9. + * + * @return How much to indent by + */ + public int indent() { + return indent; + } + + /** + * Sets how much spaces should be used to indent each line. + *

+ * The minimum value this may be is 2, and the maximum is 9. + * + * @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"); + + this.indent = value; + return this; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java new file mode 100644 index 000000000..5a8b41732 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java @@ -0,0 +1,49 @@ +package com.intellectualcrafters.configuration.file; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.Tag; + +import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; + +public class YamlConstructor extends SafeConstructor { + + public YamlConstructor() { + this.yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); + } + + private class ConstructCustomObject extends ConstructYamlMap { + @Override + public Object construct(Node node) { + if (node.isTwoStepsConstruction()) { + throw new YAMLException("Unexpected referential mapping structure. Node: " + node); + } + + 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()) { + typed.put(entry.getKey().toString(), entry.getValue()); + } + + try { + return ConfigurationSerialization.deserializeObject(typed); + } catch (IllegalArgumentException ex) { + throw new YAMLException("Could not deserialize object", ex); + } + } + + return raw; + } + + @Override + public void construct2ndStep(Node node, Object object) { + throw new YAMLException("Unexpected referential mapping structure. Node: " + node); + } + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java new file mode 100644 index 000000000..d4ef6da29 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java @@ -0,0 +1,38 @@ +package com.intellectualcrafters.configuration.file; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.representer.Representer; + +import com.intellectualcrafters.configuration.ConfigurationSection; +import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; +import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; + +public class YamlRepresenter extends Representer { + + public YamlRepresenter() { + this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); + this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); + } + + private class RepresentConfigurationSection extends RepresentMap { + @Override + public Node representData(Object data) { + return super.representData(((ConfigurationSection) data).getValues(false)); + } + } + + private class RepresentConfigurationSerializable extends RepresentMap { + @Override + public Node representData(Object data) { + ConfigurationSerializable serializable = (ConfigurationSerializable) data; + Map values = new LinkedHashMap(); + values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); + values.putAll(serializable.serialize()); + + return super.representData(values); + } + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java new file mode 100644 index 000000000..e403ebed9 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java @@ -0,0 +1,35 @@ +package com.intellectualcrafters.configuration.serialization; + +import java.util.Map; + +/** + * Represents an object that may be serialized. + *

+ * These objects MUST implement one of the following, in addition to the + * methods as defined by this interface: + *

+ * In addition to implementing this interface, you must register the class + * with {@link ConfigurationSerialization#registerClass(Class)}. + * + * @see DelegateDeserialization + * @see SerializableAs + */ +public interface ConfigurationSerializable { + + /** + * Creates a Map representation of this class. + *

+ * This class must provide a method to restore this class, as defined in + * the {@link ConfigurationSerializable} interface javadocs. + * + * @return Map containing the current state of this class + */ + public Map serialize(); +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java new file mode 100644 index 000000000..4c2f4a5bc --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java @@ -0,0 +1,266 @@ +package com.intellectualcrafters.configuration.serialization; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.intellectualcrafters.configuration.Configuration; + +/** + * Utility class for storing and retrieving classes for {@link Configuration}. + */ +public class ConfigurationSerialization { + public static final String SERIALIZED_TYPE_KEY = "=="; + private final Class clazz; + private static Map> aliases = new HashMap>(); + + protected ConfigurationSerialization(Class clazz) { + this.clazz = clazz; + } + + protected Method getMethod(String name, boolean isStatic) { + try { + Method method = clazz.getDeclaredMethod(name, Map.class); + + if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { + return null; + } + if (Modifier.isStatic(method.getModifiers()) != isStatic) { + return null; + } + + return method; + } catch (NoSuchMethodException ex) { + return null; + } catch (SecurityException ex) { + return null; + } + } + + protected Constructor getConstructor() { + try { + return clazz.getConstructor(Map.class); + } catch (NoSuchMethodException ex) { + return null; + } catch (SecurityException ex) { + return null; + } + } + + protected ConfigurationSerializable deserializeViaMethod(Method method, Map args) { + try { + 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 { + return result; + } + } catch (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); + } + + return null; + } + + protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map args) { + try { + return ctor.newInstance(args); + } catch (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); + } + + return null; + } + + public ConfigurationSerializable deserialize(Map args) { + if (args == null) { + throw new NullPointerException("Args must not be null"); + } + ConfigurationSerializable result = null; + Method method = null; + + if (result == null) { + method = getMethod("deserialize", true); + + if (method != null) { + result = deserializeViaMethod(method, args); + } + } + + if (result == null) { + method = getMethod("valueOf", true); + + if (method != null) { + result = deserializeViaMethod(method, args); + } + } + + if (result == null) { + Constructor constructor = getConstructor(); + + if (constructor != null) { + result = deserializeViaCtor(constructor, args); + } + } + + return result; + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * given class. + *

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

+ * If a new instance could not be made, an example being the class not + * fully implementing the interface, null will be returned. + * + * @param args Arguments for deserialization + * @param clazz Class to deserialize into + * @return New instance of the specified class + */ + public static ConfigurationSerializable deserializeObject(Map args, Class clazz) { + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * given class. + *

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

+ * If a new instance could not be made, an example being the class not + * fully implementing the interface, null will be returned. + * + * @param args Arguments for deserialization + * @return New instance of the specified class + */ + public static ConfigurationSerializable deserializeObject(Map args) { + Class clazz = null; + + if (args.containsKey(SERIALIZED_TYPE_KEY)) { + try { + String alias = (String) args.get(SERIALIZED_TYPE_KEY); + + if (alias == null) { + throw new IllegalArgumentException("Cannot have null alias"); + } + clazz = getClassByAlias(alias); + if (clazz == null) { + throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); + } + } catch (ClassCastException ex) { + ex.fillInStackTrace(); + throw ex; + } + } else { + throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); + } + + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Registers the given {@link ConfigurationSerializable} class by its + * alias + * + * @param clazz Class to register + */ + public static void registerClass(Class clazz) { + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + + if (delegate == null) { + registerClass(clazz, getAlias(clazz)); + registerClass(clazz, clazz.getName()); + } + } + + /** + * Registers the given alias to the specified {@link + * ConfigurationSerializable} class + * + * @param clazz Class to register + * @param alias Alias to register as + * @see SerializableAs + */ + public static void registerClass(Class clazz, String alias) { + aliases.put(alias, clazz); + } + + /** + * Unregisters the specified alias to a {@link ConfigurationSerializable} + * + * @param alias Alias to unregister + */ + public static void unregisterClass(String alias) { + aliases.remove(alias); + } + + /** + * Unregisters any aliases for the specified {@link + * ConfigurationSerializable} class + * + * @param clazz Class to unregister + */ + public static void unregisterClass(Class clazz) { + while (aliases.values().remove(clazz)) { + ; + } + } + + /** + * Attempts to get a registered {@link ConfigurationSerializable} class by + * its alias + * + * @param alias Alias of the serializable + * @return Registered class, or null if not found + */ + public static Class getClassByAlias(String alias) { + return aliases.get(alias); + } + + /** + * Gets the correct alias for the given {@link ConfigurationSerializable} + * class + * + * @param clazz Class to get alias for + * @return Alias to use for the class + */ + public static String getAlias(Class clazz) { + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + + if (delegate != null) { + if ((delegate.value() == null) || (delegate.value() == clazz)) { + delegate = null; + } else { + return getAlias(delegate.value()); + } + } + + if (delegate == null) { + SerializableAs alias = clazz.getAnnotation(SerializableAs.class); + + if ((alias != null) && (alias.value() != null)) { + return alias.value(); + } + } + + return clazz.getName(); + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java new file mode 100644 index 000000000..bc505ccf2 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java @@ -0,0 +1,22 @@ +package com.intellectualcrafters.configuration.serialization; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Applies to a {@link ConfigurationSerializable} that will delegate all + * deserialization to another {@link ConfigurationSerializable}. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface DelegateDeserialization { + /** + * Which class should be used as a delegate for this classes + * deserialization + * + * @return Delegate class + */ + public Class value(); +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java new file mode 100644 index 000000000..668da9ac9 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java @@ -0,0 +1,34 @@ +package com.intellectualcrafters.configuration.serialization; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Represents an "alias" that a {@link ConfigurationSerializable} may be + * stored as. + * If this is not present on a {@link ConfigurationSerializable} class, it + * will use the fully qualified name of the class. + *

+ * This value will be stored in the configuration so that the configuration + * deserialization can determine what type it is. + *

+ * Using this annotation on any other class than a {@link + * ConfigurationSerializable} will have no effect. + * + * @see ConfigurationSerialization#registerClass(Class, String) + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SerializableAs { + /** + * This is the name your class will be stored and retrieved as. + *

+ * This name MUST be unique. We recommend using names such as + * "MyPluginThing" instead of "Thing". + * + * @return Name to serialize the class as. + */ + public String value(); +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java index 452784981..54a6f895a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java @@ -270,4 +270,12 @@ public final class NBTOutputStream implements Closeable { public void close() throws IOException { this.os.close(); } + + /** + * Flush output + * @throws IOException + */ + public void flush() throws IOException { + this.os.flush(); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/BukkitMain.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/BukkitMain.java index 37ffcfbbf..701c58d4f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/BukkitMain.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/BukkitMain.java @@ -1,49 +1,162 @@ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.commands.*; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Stack; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.PluginCommand; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.plugin.java.JavaPluginLoader; + +import com.intellectualcrafters.plot.commands.Add; +import com.intellectualcrafters.plot.commands.Auto; +import com.intellectualcrafters.plot.commands.BukkitCommand; +import com.intellectualcrafters.plot.commands.Chat; +import com.intellectualcrafters.plot.commands.Claim; +import com.intellectualcrafters.plot.commands.Clear; +import com.intellectualcrafters.plot.commands.Cluster; +import com.intellectualcrafters.plot.commands.Comment; +import com.intellectualcrafters.plot.commands.Condense; +import com.intellectualcrafters.plot.commands.Confirm; +import com.intellectualcrafters.plot.commands.Copy; +import com.intellectualcrafters.plot.commands.CreateRoadSchematic; +import com.intellectualcrafters.plot.commands.Database; +import com.intellectualcrafters.plot.commands.Debug; +import com.intellectualcrafters.plot.commands.DebugClaimTest; +import com.intellectualcrafters.plot.commands.DebugClear; +import com.intellectualcrafters.plot.commands.DebugExec; +import com.intellectualcrafters.plot.commands.DebugFill; +import com.intellectualcrafters.plot.commands.DebugFixFlags; +import com.intellectualcrafters.plot.commands.DebugLoadTest; +import com.intellectualcrafters.plot.commands.DebugRoadRegen; +import com.intellectualcrafters.plot.commands.DebugSaveTest; +import com.intellectualcrafters.plot.commands.DebugUUID; +import com.intellectualcrafters.plot.commands.Delete; +import com.intellectualcrafters.plot.commands.Deny; +import com.intellectualcrafters.plot.commands.Disable; +import com.intellectualcrafters.plot.commands.Download; +import com.intellectualcrafters.plot.commands.FlagCmd; +import com.intellectualcrafters.plot.commands.Help; +import com.intellectualcrafters.plot.commands.Home; +import com.intellectualcrafters.plot.commands.Inbox; +import com.intellectualcrafters.plot.commands.Info; +import com.intellectualcrafters.plot.commands.Inventory; +import com.intellectualcrafters.plot.commands.Kick; +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.commands.Merge; +import com.intellectualcrafters.plot.commands.Move; +import com.intellectualcrafters.plot.commands.MusicSubcommand; +import com.intellectualcrafters.plot.commands.Purge; +import com.intellectualcrafters.plot.commands.Rate; +import com.intellectualcrafters.plot.commands.RegenAllRoads; +import com.intellectualcrafters.plot.commands.Reload; +import com.intellectualcrafters.plot.commands.Remove; +import com.intellectualcrafters.plot.commands.SchematicCmd; +import com.intellectualcrafters.plot.commands.Set; +import com.intellectualcrafters.plot.commands.SetOwner; +import com.intellectualcrafters.plot.commands.Setup; +import com.intellectualcrafters.plot.commands.Swap; +import com.intellectualcrafters.plot.commands.TP; +import com.intellectualcrafters.plot.commands.Target; +import com.intellectualcrafters.plot.commands.Template; +import com.intellectualcrafters.plot.commands.Toggle; +import com.intellectualcrafters.plot.commands.Trim; +import com.intellectualcrafters.plot.commands.Trust; +import com.intellectualcrafters.plot.commands.Unclaim; +import com.intellectualcrafters.plot.commands.Undeny; +import com.intellectualcrafters.plot.commands.Unlink; +import com.intellectualcrafters.plot.commands.Untrust; +import com.intellectualcrafters.plot.commands.Update; +import com.intellectualcrafters.plot.commands.Visit; +import com.intellectualcrafters.plot.commands.WE_Anywhere; +import com.intellectualcrafters.plot.commands.list; +import com.intellectualcrafters.plot.commands.plugin; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.plotme.ClassicPlotMeConnector; import com.intellectualcrafters.plot.database.plotme.LikePlotMeConverter; +import com.intellectualcrafters.plot.database.plotme.PlotMeConnector_017; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.generator.BukkitHybridUtils; import com.intellectualcrafters.plot.generator.HybridGen; import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.listeners.*; +import com.intellectualcrafters.plot.listeners.APlotListener; +import com.intellectualcrafters.plot.listeners.ChunkListener; +import com.intellectualcrafters.plot.listeners.ForceFieldListener; +import com.intellectualcrafters.plot.listeners.InventoryListener; +import com.intellectualcrafters.plot.listeners.PlayerEvents; +import com.intellectualcrafters.plot.listeners.PlayerEvents_1_8; +import com.intellectualcrafters.plot.listeners.PlayerEvents_1_8_3; +import com.intellectualcrafters.plot.listeners.PlotListener; +import com.intellectualcrafters.plot.listeners.PlotPlusListener; +import com.intellectualcrafters.plot.listeners.TNTListener; +import com.intellectualcrafters.plot.listeners.WorldEvents; import com.intellectualcrafters.plot.listeners.worldedit.WEListener; import com.intellectualcrafters.plot.listeners.worldedit.WESubscriber; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.titles.AbstractTitle; import com.intellectualcrafters.plot.titles.DefaultTitle; -import com.intellectualcrafters.plot.util.*; -import com.intellectualcrafters.plot.util.bukkit.*; +import com.intellectualcrafters.plot.util.BlockManager; +import com.intellectualcrafters.plot.util.BlockUpdateUtil; +import com.intellectualcrafters.plot.util.ChunkManager; +import com.intellectualcrafters.plot.util.ConsoleColors; +import com.intellectualcrafters.plot.util.EconHandler; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.InventoryUtil; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.PlayerManager; +import com.intellectualcrafters.plot.util.SetupUtils; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.bukkit.BukkitChunkManager; +import com.intellectualcrafters.plot.util.bukkit.BukkitEconHandler; +import com.intellectualcrafters.plot.util.bukkit.BukkitEventUtil; +import com.intellectualcrafters.plot.util.bukkit.BukkitInventoryUtil; +import com.intellectualcrafters.plot.util.bukkit.BukkitPlayerManager; +import com.intellectualcrafters.plot.util.bukkit.BukkitSetBlockManager; +import com.intellectualcrafters.plot.util.bukkit.BukkitSetupUtils; +import com.intellectualcrafters.plot.util.bukkit.BukkitTaskManager; +import com.intellectualcrafters.plot.util.bukkit.BukkitUtil; +import com.intellectualcrafters.plot.util.bukkit.Metrics; +import com.intellectualcrafters.plot.util.bukkit.SendChunk; +import com.intellectualcrafters.plot.util.bukkit.SetBlockFast; +import com.intellectualcrafters.plot.util.bukkit.SetBlockFast_1_8; +import com.intellectualcrafters.plot.util.bukkit.SetBlockSlow; +import com.intellectualcrafters.plot.util.bukkit.SetGenCB; +import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.uuid.DefaultUUIDWrapper; import com.intellectualcrafters.plot.uuid.LowerOfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.OfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.WorldEditPlugin; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.command.PluginCommand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { - + public static BukkitMain THIS = null; - + private int[] version; @Override @@ -57,18 +170,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (version.length == 3) { version[2] = Integer.parseInt(split[2]); } - } - catch (Exception e) { + } catch (Exception e) { return false; } } return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && (version[2] >= minor2)); } - + @Override public void onEnable() { THIS = this; - PlotSquared.instance = new PlotSquared(this); + PS.instance = new PS(this); if (Settings.METRICS) { try { final Metrics metrics = new Metrics(this); @@ -80,6 +192,18 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } else { log("&dUsing metrics will allow us to improve the plugin, please consider it :)"); } +// File file = new File(this.getDirectory() + File.separator + "disabled.yml"); +// if (file.exists()) { +// file.delete(); +// try { +// String[] split = new String(Files.readAllBytes(file.toPath())).split(","); +// for (String plugin : split) { +// loadPlugin(plugin); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } List worlds = Bukkit.getWorlds(); if (worlds.size() > 0) { UUIDHandler.cacheAll(worlds.get(0).getName()); @@ -94,40 +218,48 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } } - @Override public void onDisable() { - PlotSquared.getInstance().disable(); + PS.get().disable(); + try { + unloadRecursively(this); + } + catch (Exception e) { + e.printStackTrace(); + }; THIS = null; } - + @Override public void log(String message) { if (message == null) { return; } message = message.replaceAll("\u00B2", "2"); - if ((THIS == null) || (Bukkit.getServer().getConsoleSender() == null)) { - System.out.println(ChatColor.stripColor(ConsoleColors.fromString(message))); - } else { - message = ChatColor.translateAlternateColorCodes('&', message); - if (!Settings.CONSOLE_COLOR) { - message = ChatColor.stripColor(message); + if (THIS != null && Bukkit.getServer().getConsoleSender() != null) { + try { + message = ChatColor.translateAlternateColorCodes('&', message); + if (!Settings.CONSOLE_COLOR) { + message = ChatColor.stripColor(message); + } + Bukkit.getServer().getConsoleSender().sendMessage(message); + return; } - Bukkit.getServer().getConsoleSender().sendMessage(message); + catch (Throwable e) {}; } + System.out.println(ConsoleColors.fromString(message)); } - + @Override public void disable() { onDisable(); } - + @Override public String getVersion() { return this.getDescription().getVersion(); } - + @Override public void handleKick(UUID uuid, C c) { Player player = Bukkit.getPlayer(uuid); @@ -136,10 +268,13 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { player.teleport(player.getWorld().getSpawnLocation()); } } - + @Override public void registerCommands() { new MainCommand(); + MainCommand.subCommands.add(new Download()); + MainCommand.subCommands.add(new Disable()); + MainCommand.subCommands.add(new Update()); MainCommand.subCommands.add(new Template()); MainCommand.subCommands.add(new Setup()); MainCommand.subCommands.add(new DebugUUID()); @@ -162,14 +297,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (Settings.ENABLE_CLUSTERS) { MainCommand.subCommands.add(new Cluster()); } - MainCommand.subCommands.add(new Trust()); MainCommand.subCommands.add(new Add()); MainCommand.subCommands.add(new Deny()); MainCommand.subCommands.add(new Untrust()); MainCommand.subCommands.add(new Remove()); MainCommand.subCommands.add(new Undeny()); - MainCommand.subCommands.add(new Info()); MainCommand.subCommands.add(new list()); MainCommand.subCommands.add(new Help()); @@ -207,17 +340,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot")); plotCommand.setTabCompleter(bcmd); } - + @Override public File getDirectory() { return getDataFolder(); } - + @Override public TaskManager getTaskManager() { return new BukkitTaskManager(); } - + @Override public void runEntityTask() { log(C.PREFIX.s() + "KillAllEntities started."); @@ -235,7 +368,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { this.error = 0l; } World world; - for (final String w : PlotSquared.getInstance().getPlotWorlds()) { + for (final String w : PS.get().getPlotWorlds()) { world = Bukkit.getWorld(w); try { if (world.getLoadedChunks().length < 1) { @@ -259,11 +392,168 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } }, 20); } - + + public boolean unloadPlugin(Plugin plugin) { + try { + plugin.getClass().getClassLoader().getResources("*"); + } catch (IOException e1) { + e1.printStackTrace(); + } + PluginManager pm = Bukkit.getServer().getPluginManager(); + Map ln; + List pl; + try { + Field lnF = pm.getClass().getDeclaredField("lookupNames"); + lnF.setAccessible(true); + ln = (Map) lnF.get(pm); + + Field plF = pm.getClass().getDeclaredField("plugins"); + plF.setAccessible(true); + pl = (List) plF.get(pm); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + pm.disablePlugin(plugin); + synchronized (pm) { + ln.remove(plugin.getName()); + pl.remove(plugin); + } + JavaPluginLoader jpl = (JavaPluginLoader) plugin.getPluginLoader(); + Field loadersF = null; + try { + loadersF = jpl.getClass().getDeclaredField("loaders"); + loadersF.setAccessible(true); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Map loaderMap = (Map) loadersF.get(jpl); + loaderMap.remove(plugin.getDescription().getName()); + } catch (Exception e) { + e.printStackTrace(); + } + closeClassLoader(plugin); + System.gc(); + System.gc(); + return true; + } + + public boolean closeClassLoader(Plugin plugin) { + try { + ((URLClassLoader) plugin.getClass().getClassLoader()).close(); + return true; + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + public boolean unloadRecursively(Plugin plugin) { + try { + Stack pluginFiles = unloadRecursively(plugin.getName(), plugin, new Stack()); + File file = new File(this.getDirectory() + File.separator + "disabled.yml"); + file.createNewFile(); + String prefix = ""; + String all = ""; + while (pluginFiles.size() > 0) { + String pop = pluginFiles.pop(); + all += prefix + pop.substring(0, pop.length() - 4); + prefix = ","; + } + if (all.length() != 0) { + PrintWriter out = new PrintWriter(this.getDirectory() + File.separator + "disabled.yml"); + out.write(all); + out.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return true; + } + + @Override + public void loadPlugin(String name) { + try { + PluginManager manager = Bukkit.getServer().getPluginManager(); + Plugin plugin = manager.getPlugin(name); + if (plugin != null) { + manager.enablePlugin(plugin); + return; + } + plugin = manager.loadPlugin(new File("plugins" + File.separator + name + (name.endsWith(".jar") ? "" : ".jar"))); + plugin.onLoad(); + manager.enablePlugin(plugin); + } catch (Exception e) {} + } + + @Override + public File getFile() { + return getFile(this); + } + + public File getFile(JavaPlugin p) { + try { + Field f = JavaPlugin.class.getDeclaredField("file"); + f.setAccessible(true); + return (File) f.get(p); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public Stack unloadRecursively(String doNotLoad, Plugin plugin, Stack pluginFiles) { + if (!plugin.getName().equals(doNotLoad)) { + File file = getFile((JavaPlugin) plugin); + pluginFiles.push(file.getName()); + } + PluginManager pm = Bukkit.getPluginManager(); + for (Plugin p : pm.getPlugins()) { + List depend = p.getDescription().getDepend(); + if (depend != null) { + for (String s : depend) { + if (s.equals(plugin.getName())) { + unloadRecursively(doNotLoad, p, pluginFiles); + } + } + } + List softDepend = p.getDescription().getSoftDepend(); + if (softDepend != null) { + for (String s : softDepend) { + if (s.equals(plugin.getName())) { + unloadRecursively(doNotLoad, p, pluginFiles); + } + } + } + } + if (unloadPlugin(plugin)) { + List depend = plugin.getDescription().getDepend(); + if (depend != null) { + for (String s : depend) { + Plugin p = pm.getPlugin(s); + if (p != null) { + unloadRecursively(doNotLoad, p, pluginFiles); + } + } + } + List softDepend = plugin.getDescription().getSoftDepend(); + if (softDepend != null) { + for (String s : softDepend) { + Plugin p = pm.getPlugin(s); + if (p != null) { + unloadRecursively(doNotLoad, p, pluginFiles); + } + } + } + } + return pluginFiles; + } + @Override final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { WorldEvents.lastWorld = world; - if (!PlotSquared.getInstance().setupPlotWorld(world, id)) { + if (!PS.get().setupPlotWorld(world, id)) { return null; } HybridGen result = new HybridGen(world); @@ -277,7 +567,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { }, 20); return result; } - + @Override public void registerPlayerEvents() { getServer().getPluginManager().registerEvents(new PlayerEvents(), this); @@ -288,28 +578,28 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { getServer().getPluginManager().registerEvents(new PlayerEvents_1_8_3(), this); } } - + @Override public void registerInventoryEvents() { getServer().getPluginManager().registerEvents(new InventoryListener(), this); } - + @Override public void registerPlotPlusEvents() { PlotPlusListener.startRunnable(this); getServer().getPluginManager().registerEvents(new PlotPlusListener(), this); } - + @Override public void registerForceFieldEvents() { getServer().getPluginManager().registerEvents(new ForceFieldListener(), this); } - + @Override public void registerWorldEditEvents() { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { - PlotSquared.getInstance().worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); - final String version = PlotSquared.getInstance().worldEdit.getDescription().getVersion(); + PS.get().worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); + final String version = PS.get().worldEdit.getDescription().getVersion(); if ((version != null) && version.startsWith("5.")) { log("&cThis version of WorldEdit does not support PlotSquared."); log("&cPlease use WorldEdit 6+ for masking support"); @@ -321,7 +611,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } } } - + @Override public EconHandler getEconomyHandler() { try { @@ -333,7 +623,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } return null; } - + @Override public BlockManager initBlockManager() { if (checkVersion(1, 8, 0)) { @@ -360,20 +650,20 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { BlockUpdateUtil.setBlockManager = BukkitSetBlockManager.setBlockManager; return BlockManager.manager = new BukkitUtil(); } - + @Override public boolean initPlotMeConverter() { TaskManager.runTaskLaterAsync(new Runnable() { @Override public void run() { - if (!(new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector()))) { - new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector()); - } + if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) return; + if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) return; + if (new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector())) return; } }, 20); return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null; } - + @Override public ChunkGenerator getGenerator(final String world, final String name) { final Plugin gen_plugin = Bukkit.getPluginManager().getPlugin(name); @@ -383,7 +673,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { return new HybridGen(world); } } - + @Override public HybridUtils initHybridUtils() { return new BukkitHybridUtils(); @@ -400,8 +690,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (Settings.OFFLINE_MODE) { if (Settings.UUID_LOWERCASE) { UUIDHandler.uuidWrapper = new LowerOfflineUUIDWrapper(); - } - else { + } else { UUIDHandler.uuidWrapper = new OfflineUUIDWrapper(); } Settings.OFFLINE_MODE = true; @@ -411,8 +700,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } else { if (Settings.UUID_LOWERCASE) { UUIDHandler.uuidWrapper = new LowerOfflineUUIDWrapper(); - } - else { + } else { UUIDHandler.uuidWrapper = new OfflineUUIDWrapper(); } Settings.OFFLINE_MODE = true; @@ -425,8 +713,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { AbstractTitle.TITLE_CLASS = new DefaultTitle(); if (UUIDHandler.uuidWrapper instanceof DefaultUUIDWrapper) { Settings.TWIN_MODE_UUID = true; - } - else if (UUIDHandler.uuidWrapper instanceof OfflineUUIDWrapper && !Bukkit.getOnlineMode()) { + } else if (UUIDHandler.uuidWrapper instanceof OfflineUUIDWrapper && !Bukkit.getOnlineMode()) { Settings.TWIN_MODE_UUID = true; } } @@ -442,27 +729,27 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { public ChunkManager initChunkManager() { return new BukkitChunkManager(); } - + @Override public EventUtil initEventUtil() { return new BukkitEventUtil(); } - + @Override public void registerTNTListener() { getServer().getPluginManager().registerEvents(new TNTListener(), this); } - + @Override public void unregister(PlotPlayer player) { BukkitUtil.removePlayer(player.getName()); } - + @Override public APlotListener initPlotListener() { return new PlotListener(); } - + @Override public void registerChunkProcessor() { getServer().getPluginManager().registerEvents(new ChunkListener(), this); @@ -472,12 +759,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { public void registerWorldEvents() { getServer().getPluginManager().registerEvents(new WorldEvents(), this); } - + @Override public PlayerManager initPlayerManager() { return new BukkitPlayerManager(); } - + @Override public InventoryUtil initInventoryUtil() { return new BukkitInventoryUtil(); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/IPlotMain.java index 4ea64b9d3..4ec0296c0 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/IPlotMain.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/IPlotMain.java @@ -23,6 +23,8 @@ public interface IPlotMain { public void log(String message); public File getDirectory(); + + public File getFile(); public void disable(); @@ -79,4 +81,6 @@ public interface IPlotMain { public PlayerManager initPlayerManager(); public boolean checkVersion(int major, int minor, int minor2); + + public void loadPlugin(String plugin); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquared.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PS.java similarity index 81% rename from PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquared.java rename to PlotSquared/src/main/java/com/intellectualcrafters/plot/PS.java index 3ed63c504..737eef604 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquared.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PS.java @@ -1,35 +1,85 @@ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Configuration; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.*; -import com.intellectualcrafters.plot.flag.AbstractFlag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.flag.FlagValue; -import com.intellectualcrafters.plot.generator.*; -import com.intellectualcrafters.plot.listeners.APlotListener; -import com.intellectualcrafters.plot.object.*; -import com.intellectualcrafters.plot.object.comment.CommentManager; -import com.intellectualcrafters.plot.util.*; -import com.intellectualcrafters.plot.util.Logger.LogLevel; -import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import com.sk89q.worldedit.bukkit.WorldEditPlugin; - -import org.bukkit.configuration.file.YamlConfiguration; - +import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import org.bukkit.Bukkit; + +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Configuration; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.database.Database; +import com.intellectualcrafters.plot.database.MySQL; +import com.intellectualcrafters.plot.database.SQLManager; +import com.intellectualcrafters.plot.database.SQLite; +import com.intellectualcrafters.plot.flag.AbstractFlag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.flag.FlagValue; +import com.intellectualcrafters.plot.generator.AugmentedPopulator; +import com.intellectualcrafters.plot.generator.ClassicPlotWorld; +import com.intellectualcrafters.plot.generator.HybridGen; +import com.intellectualcrafters.plot.generator.HybridPlotWorld; +import com.intellectualcrafters.plot.generator.HybridUtils; +import com.intellectualcrafters.plot.generator.SquarePlotManager; +import com.intellectualcrafters.plot.generator.SquarePlotWorld; +import com.intellectualcrafters.plot.listeners.APlotListener; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotBlock; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotGenerator; +import com.intellectualcrafters.plot.object.PlotHandler; +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.object.comment.CommentManager; +import com.intellectualcrafters.plot.util.BlockManager; +import com.intellectualcrafters.plot.util.ChunkManager; +import com.intellectualcrafters.plot.util.ClusterManager; +import com.intellectualcrafters.plot.util.EconHandler; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.ExpireManager; +import com.intellectualcrafters.plot.util.InventoryUtil; +import com.intellectualcrafters.plot.util.Logger; +import com.intellectualcrafters.plot.util.Logger.LogLevel; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.PlayerManager; +import com.intellectualcrafters.plot.util.SetupUtils; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; + /** * An implementation of the core, * with a static getter for easy access @@ -37,14 +87,11 @@ import java.util.zip.ZipInputStream; * @author Sauilitired | Citymonstret * @author boy0001 | Empire92 */ -public class PlotSquared { - - // public static final: - public static final String MAIN_PERMISSION = "plots.use"; +public class PS { // protected static: - protected static PlotSquared instance; - + protected static PS instance; + // private final: private final HashMap plotworlds = new HashMap<>(); private final HashMap plotmanagers = new HashMap<>(); @@ -52,17 +99,20 @@ public class PlotSquared { // public: public WorldEditPlugin worldEdit = null; public File configFile; + public File translationFile; + public YamlConfiguration style; public YamlConfiguration config; public YamlConfiguration storage; public IPlotMain IMP = null; public TaskManager TASK; + public URL update; // private: private File styleFile; - private YamlConfiguration style; private File storageFile; private File FILE = null; // This file private String VERSION = null; + private String LAST_VERSION; private boolean LOADING_WORLD = false; private LinkedHashMap> plots; private Database database; @@ -72,18 +122,17 @@ public class PlotSquared { * Initialize PlotSquared with the desired Implementation class * @param imp_class */ - protected PlotSquared(final IPlotMain imp_class) { + protected PS(final IPlotMain imp_class) { + instance = this; SetupUtils.generators = new HashMap<>(); IMP = imp_class; try { - FILE = new File(PlotSquared.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); + FILE = new File(PS.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); } catch (Exception e) { log("Could not determine file path"); } VERSION = IMP.getVersion(); EconHandler.manager = IMP.getEconomyHandler(); - C.setupTranslations(); - C.saveTranslations(); 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 @@ -99,6 +148,8 @@ public class PlotSquared { log(C.ENABLED.s()); } setupConfigs(); + this.translationFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "PlotSquared.use_THIS.yml"); + C.load(translationFile); setupDefaultFlags(); setupDatabase(); CommentManager.registerDefaultInboxes(); @@ -139,6 +190,23 @@ public class PlotSquared { // Player manager PlayerManager.manager = IMP.initPlayerManager(); + // Check for updates + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + URL url = getUpdate(); + if (url != null) { + update = url; + log("&6You are running an older version of PlotSquared..."); + log("&8 - &3Use: &7/plot update"); + log("&8 - &3Or: &7" + url); + } + else if (LAST_VERSION != null && !VERSION.equals(LAST_VERSION)) { + log("&aThanks for updating from: " + LAST_VERSION + " to " + VERSION); + } + } + }); + // PlotMe if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME) { TaskManager.runTaskLater(new Runnable() { @@ -167,15 +235,31 @@ public class PlotSquared { copyFile("italian.yml", "translations"); showDebug(); } - + /** * Get the instance of PlotSquared * * @return the instance created by IPlotMain */ - public static PlotSquared getInstance() { + public static PS get() { return instance; } + + /** + * Get the last PlotSquared version + * @return last version in config or null + */ + public String getLastVersion() { + return LAST_VERSION; + } + + /** + * Get the current PlotSquared version + * @return current version in config or null + */ + public String getVersion() { + return VERSION; + } /** * Log a message to the IPlotMain logger @@ -184,7 +268,7 @@ public class PlotSquared { * @see IPlotMain#log(String) */ public static void log(final String message) { - getInstance().IMP.log(message); + get().IMP.log(message); } /** @@ -383,7 +467,6 @@ public class PlotSquared { /** * Sort a collection of plots by world, then by hashcode * @param plots - * @param priorityWorld * @see #sortPlots(Collection, String) to sort with a specific priority world * @see #sortPlots(Collection) to sort plots just by hashcode * @return ArrayList of plot @@ -532,7 +615,11 @@ public class PlotSquared { if (callEvent) { EventUtil.manager.callDelete(world, id); } - Plot plot = plots.get(world).remove(id); + HashMap allPlots = plots.get(world); + if (allPlots == null) { + return false; + } + 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); @@ -638,10 +725,19 @@ public class PlotSquared { 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; } + + log(C.PREFIX.s() + "&aDetected world load for '" + world + "'"); + log(C.PREFIX.s() + "&3 - generator: &7" + gen_class.getClass().getName()); + log(C.PREFIX.s() + "&3 - plotworld: &7" + plotWorld.getClass().getName()); + 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)) { + log(C.PREFIX.s() + "&3 - &7| cluster: " + cluster); new AugmentedPopulator(world, gen_class, cluster, plotWorld.TERRAIN == 2, plotWorld.TERRAIN != 2); } } @@ -752,6 +848,123 @@ public class PlotSquared { } return true; } + + public boolean canUpdate(String current, String other) { + String s1 = normalisedVersion(current); + String s2 = normalisedVersion(other); + int cmp = s1.compareTo(s2); + return cmp < 0; + } + + public String normalisedVersion(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) { + 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 resource = "plotsquared.1177"; + String url = "https://www.spigotmc.org/resources/" + resource + "/history"; + String download = ""; + try { + URL history = new URL(url); + URLConnection con = history.openConnection(); + con.addRequestProperty("User-Agent", "Mozilla/4.0"); + InputStream stream = con.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(stream)); + String l; + URL link = null; + String cur_ver = config.getString("version"); + String new_ver = null; + while ((l = in.readLine()) != null) { + if (l.length() > version.length() && l.startsWith(version)) { + new_ver = l.substring(version.length(), l.length() - 5); + break; + } + if (link == null && l.length() > download.length() && l.startsWith(download)) { + String subString = l.substring(download.length()); + link = new URL("https://www.spigotmc.org/resources/" + resource + "/download?version=" + subString.substring(0, subString.indexOf("\""))); + continue; + } + } + stream.close(); + in.close(); + if (new_ver == null || !canUpdate(cur_ver, new_ver)) { + PS.log("&7PlotSquared is already up to date!"); + return null; + } + if (link == null) { + PS.log("&dCould not check for updates"); + PS.log("&7 - Manually check for updates: " + url); + return null; + } + return link; + } catch (Exception e) { + PS.log("&dCould not check for updates"); + PS.log("&7 - Manually check for updates: " + url); + return null; + } + } + + public boolean update(URL url) { + if (url == null) { + return false; + } + try { + File jar = PS.get().IMP.getFile(); + File newJar = new File("plugins/update/PlotSquared.jar"); + PS.log("&6Downloading from provided URL: &7" + url); + PS.log("&7 - User-Agent: " + "Mozilla/4.0"); + URLConnection con = url.openConnection(); + con.addRequestProperty("User-Agent", "Mozilla/4.0"); + InputStream stream = con.getInputStream(); + File parent = newJar.getParentFile(); + if (!parent.exists()) { + parent.mkdirs(); + } + PS.log("&7 - Output: " + newJar); + newJar.delete(); + Files.copy(stream, newJar.toPath()); + stream.close(); + PS.log("&6Disabling PlotSquared"); + PS.get().IMP.disable(); + System.out.println("Deleting file: " + jar); + jar.delete(); + System.out.println("Copying: " + jar + " >> " + newJar); + try { + Files.move(newJar.toPath(), jar.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + System.out.println("Failed to reload PlotSquared"); + System.out.println(" - Restart the server manually"); + System.out.println("============ Stacktrace ============"); + e.printStackTrace(); + System.out.println("===================================="); + return false; + } + Bukkit.reload(); + return true; + } + catch (Exception e) { + System.out.println("Failed to update PlotSquared"); + System.out.println(" - Please update manually"); + System.out.println("============ Stacktrace ============"); + e.printStackTrace(); + System.out.println("===================================="); + } + return false; + } /** @@ -824,7 +1037,7 @@ public class PlotSquared { public void setupDatabase() { if (Settings.DB.USE_MYSQL) { try { - database = new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); + database = new MySQL(Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); connection = database.openConnection(); { if (DBFunc.dbManager == null) { @@ -852,7 +1065,7 @@ public class PlotSquared { log(C.PREFIX.s() + "MongoDB is not yet implemented"); } else if (Settings.DB.USE_SQLITE) { try { - this.database = new SQLite(this, IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db"); + this.database = new SQLite(IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db"); connection = this.database.openConnection(); { DBFunc.dbManager = new SQLManager(connection, Settings.DB.PREFIX); @@ -905,6 +1118,7 @@ public class PlotSquared { FlagManager.addFlag(new AbstractFlag("disable-physics", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("fly", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("explosion", new FlagValue.BooleanValue())); + FlagManager.addFlag(new AbstractFlag("mob-place", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("hostile-interact", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("hostile-attack", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("animal-interact", new FlagValue.BooleanValue())); @@ -912,11 +1126,15 @@ public class PlotSquared { FlagManager.addFlag(new AbstractFlag("tamed-interact", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("tamed-attack", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("misc-interact", new FlagValue.BooleanValue())); + FlagManager.addFlag(new AbstractFlag("misc-place", new FlagValue.BooleanValue())); + FlagManager.addFlag(new AbstractFlag("misc-break", new FlagValue.BooleanValue())); + FlagManager.addFlag(new AbstractFlag("hanging-interact", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("hanging-place", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("hanging-break", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("vehicle-use", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("vehicle-place", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("vehicle-break", new FlagValue.BooleanValue())); + FlagManager.addFlag(new AbstractFlag("device-interact", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("place", new FlagValue.PlotBlockListValue())); FlagManager.addFlag(new AbstractFlag("break", new FlagValue.PlotBlockListValue())); FlagManager.addFlag(new AbstractFlag("use", new FlagValue.PlotBlockListValue())); @@ -980,6 +1198,7 @@ public class PlotSquared { * Setup the default configuration (settings.yml) */ public void setupConfig() { + LAST_VERSION = config.getString("version"); config.set("version", VERSION); final Map options = new HashMap<>(); @@ -1023,6 +1242,10 @@ public class PlotSquared { // Schematics options.put("schematics.save_path", Settings.SCHEMATIC_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); @@ -1073,7 +1296,7 @@ public class PlotSquared { Settings.CONFIRM_UNLINK = config.getBoolean("confirmation.unlink"); // Protection - Settings.REDSTONE_DISABLER = config.getBoolean("protection.tnt-listener.enabled"); + Settings.REDSTONE_DISABLER = config.getBoolean("protection.redstone.disable-offline"); Settings.TNT_LISTENER = config.getBoolean("protection.tnt-listener.enabled"); Settings.PISTON_FALLING_BLOCK_CHECK = config.getBoolean("protection.piston.falling-blocks"); @@ -1107,6 +1330,10 @@ public class PlotSquared { // Schematics Settings.SCHEMATIC_SAVE_PATH = config.getString("schematics.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"); @@ -1152,7 +1379,7 @@ public class PlotSquared { 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") || !IMP.checkVersion(1, 7, 0)) { + if (!config.getBoolean("chat.fancy") || !IMP.checkVersion(1, 8, 0)) { Settings.FANCY_CHAT = false; } Settings.METRICS = config.getBoolean("metrics"); @@ -1173,6 +1400,9 @@ public class PlotSquared { try { styleFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "style.yml"); if (!styleFile.exists()) { + if (!styleFile.getParentFile().exists()) { + styleFile.getParentFile().mkdirs(); + } if (!styleFile.createNewFile()) { log("Could not create the style file, please create \"translations/style.yml\" manually"); } @@ -1180,6 +1410,7 @@ public class PlotSquared { style = YamlConfiguration.loadConfiguration(styleFile); setupStyle(); } catch (final Exception err) { + err.printStackTrace(); Logger.add(LogLevel.DANGER, "Failed to save style.yml"); log("failed to save style.yml"); } @@ -1259,10 +1490,6 @@ public class PlotSquared { * Show startup debug information */ public void showDebug() { - C.COLOR_1 = "&" + (style.getString("color.1")); - C.COLOR_2 = "&" + (style.getString("color.2")); - C.COLOR_3 = "&" + (style.getString("color.3")); - C.COLOR_4 = "&" + (style.getString("color.4")); if (Settings.DEBUG) { final Map settings = new HashMap<>(); settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); @@ -1287,12 +1514,12 @@ public class PlotSquared { private void setupStyle() { style.set("version", VERSION); final Map o = new HashMap<>(); - o.put("color.1", C.COLOR_1.substring(1)); - o.put("color.2", C.COLOR_2.substring(1)); - o.put("color.3", C.COLOR_3.substring(1)); - o.put("color.4", C.COLOR_4.substring(1)); - for (final Entry node : o.entrySet()) { - if (!style.contains(node.getKey())) { + o.put("color.1", "6"); + o.put("color.2", "7"); + o.put("color.3", "8"); + o.put("color.4", "3"); + if (!style.contains("color")) { + for (final Entry node : o.entrySet()) { style.set(node.getKey(), node.getValue()); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java index b2d5e2a58..1fd47fd74 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java @@ -21,27 +21,37 @@ package com.intellectualcrafters.plot.api; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; + +import org.bukkit.Location; +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.*; -import com.intellectualcrafters.plot.util.*; +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.bukkit.BukkitSetBlockManager; import com.intellectualcrafters.plot.util.bukkit.BukkitUtil; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Set; /** * PlotSquared API @@ -68,7 +78,7 @@ import java.util.Set; * * @throws com.intellectualcrafters.plot.util.PlotSquaredException if the program fails to fetch the PlotSquared * instance - * @see com.intellectualcrafters.plot.PlotSquared + * @see com.intellectualcrafters.plot.PS */ @Deprecated public PlotAPI(final JavaPlugin plugin) { @@ -82,10 +92,10 @@ import java.util.Set; * * @return all plots * - * @see com.intellectualcrafters.plot.PlotSquared#getPlots() + * @see com.intellectualcrafters.plot.PS#getPlots() */ public Set getAllPlots() { - return PlotSquared.getInstance().getPlots(); + return PS.get().getPlots(); } /** @@ -96,7 +106,7 @@ import java.util.Set; * @return all plots that a player owns */ public Set getPlayerPlots(final Player player) { - return PlotSquared.getInstance().getPlots(BukkitUtil.getPlayer(player)); + return PS.get().getPlots(BukkitUtil.getPlayer(player)); } /** @@ -106,29 +116,29 @@ import java.util.Set; * @param plotWorld Plot World Object * @param manager World Manager * - * @see com.intellectualcrafters.plot.PlotSquared#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotWorld, + * @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) { - PlotSquared.getInstance().addPlotWorld(world, plotWorld, manager); + PS.get().addPlotWorld(world, plotWorld, manager); } /** * @return main configuration * - * @see com.intellectualcrafters.plot.PlotSquared#config + * @see com.intellectualcrafters.plot.PS#config */ public YamlConfiguration getConfig() { - return PlotSquared.getInstance().config; + return PS.get().config; } /** * @return storage configuration * - * @see com.intellectualcrafters.plot.PlotSquared#storage + * @see com.intellectualcrafters.plot.PS#storage */ public YamlConfiguration getStorage() { - return PlotSquared.getInstance().storage; + return PS.get().storage; } /** @@ -137,10 +147,10 @@ import java.util.Set; * * @return PlotSquared PlotSquared Main Class * - * @see com.intellectualcrafters.plot.PlotSquared + * @see com.intellectualcrafters.plot.PS */ - public PlotSquared getMain() { - return PlotSquared.getInstance(); + public PS getMain() { + return PS.get(); } /** @@ -240,8 +250,8 @@ import java.util.Set; * @see com.intellectualcrafters.plot.util.Permissions */ @Deprecated - public Permissions getPermissions() { - return new Permissions(); + public Permissions[] getPermissions() { + return Permissions.values(); } /** @@ -275,10 +285,10 @@ import java.util.Set; * @return PlotManager * * @see com.intellectualcrafters.plot.object.PlotManager - * @see PlotSquared#getPlotManager(String) + * @see PS#getPlotManager(String) */ public PlotManager getPlotManager(final World world) { - return PlotSquared.getInstance().getPlotManager(world.getName()); + return PS.get().getPlotManager(world.getName()); } /** @@ -289,11 +299,11 @@ import java.util.Set; * * @return PlotManager * - * @see PlotSquared#getPlotManager(String) + * @see PS#getPlotManager(String) * @see com.intellectualcrafters.plot.object.PlotManager */ public PlotManager getPlotManager(final String world) { - return PlotSquared.getInstance().getPlotManager(world); + return PS.get().getPlotManager(world); } /** @@ -304,11 +314,11 @@ import java.util.Set; * * @return PlotWorld class for that world ! will return null if not a plot world world * - * @see PlotSquared#getPlotWorld(String) + * @see PS#getPlotWorld(String) * @see com.intellectualcrafters.plot.object.PlotWorld */ public PlotWorld getWorldSettings(final World world) { - return PlotSquared.getInstance().getPlotWorld(world.getName()); + return PS.get().getPlotWorld(world.getName()); } /** @@ -318,11 +328,11 @@ import java.util.Set; * * @return PlotWorld class for that world ! will return null if not a plot world world * - * @see PlotSquared#getPlotWorld(String) + * @see PS#getPlotWorld(String) * @see com.intellectualcrafters.plot.object.PlotWorld */ public PlotWorld getWorldSettings(final String world) { - return PlotSquared.getInstance().getPlotWorld(world); + return PS.get().getPlotWorld(world); } /** @@ -464,7 +474,7 @@ import java.util.Set; */ public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) { final ArrayList pPlots = new ArrayList<>(); - for (final Plot plot : PlotSquared.getInstance().getPlots(world.getName()).values()) { + for (final Plot plot : PS.get().getPlots(world.getName()).values()) { if (just_owner) { if ((plot.owner != null) && (plot.owner.equals(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr))))) { pPlots.add(plot); @@ -485,11 +495,11 @@ import java.util.Set; * * @return Plot[] - array of plot objects in world * - * @see PlotSquared#getPlots(String) + * @see PS#getPlots(String) * @see com.intellectualcrafters.plot.object.Plot */ public Plot[] getPlots(final World world) { - Collection plots = PlotSquared.getInstance().getPlots(world.getName()).values(); + Collection plots = PS.get().getPlots(world.getName()).values(); return plots.toArray(new Plot[plots.size()]); } @@ -498,10 +508,10 @@ import java.util.Set; * * @return World[] - array of plot worlds * - * @see com.intellectualcrafters.plot.PlotSquared#getPlotWorlds() + * @see com.intellectualcrafters.plot.PS#getPlotWorlds() */ public String[] getPlotWorlds() { - Set worlds = PlotSquared.getInstance().getPlotWorlds(); + Set worlds = PS.get().getPlotWorlds(); return worlds.toArray(new String[worlds.size()]); } @@ -512,10 +522,10 @@ import java.util.Set; * * @return boolean (if plot world or not) * - * @see com.intellectualcrafters.plot.PlotSquared#isPlotWorld(String) + * @see com.intellectualcrafters.plot.PS#isPlotWorld(String) */ public boolean isPlotWorld(final World world) { - return PlotSquared.getInstance().isPlotWorld(world.getName()); + return PS.get().isPlotWorld(world.getName()); } /** @@ -611,10 +621,10 @@ import java.util.Set; * * @return PlotSquared Class * - * @see com.intellectualcrafters.plot.PlotSquared + * @see com.intellectualcrafters.plot.PS */ - public PlotSquared getPlotSquared() { - return PlotSquared.getInstance(); + public PS getPlotSquared() { + return PS.get(); } /** @@ -639,12 +649,12 @@ import java.util.Set; * * @return a set containing the players plots * - * @see com.intellectualcrafters.plot.PlotSquared#getPlots(String, PlotPlayer) + * @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 PlotSquared.getInstance().getPlots(world.getName(), BukkitUtil.getPlayer(player)); + return PS.get().getPlots(world.getName(), BukkitUtil.getPlayer(player)); } /** diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Add.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Add.java index c938517d1..1c0a6a45a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Add.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Add.java @@ -20,7 +20,9 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.UUID; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Location; @@ -31,8 +33,6 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.UUID; - public class Add extends SubCommand { public Add() { super(Command.ADD, "Allow a user to build while you are online", "add ", CommandCategory.ACTIONS, true); @@ -67,34 +67,29 @@ public class Add extends SubCommand { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - if (!plot.members.contains(uuid)) { - if (plot.isOwner(uuid)) { - MainUtil.sendMessage(plr, C.ALREADY_OWNER); - return false; - } - if (plot.trusted.contains(uuid)) { - plot.trusted.remove(uuid); - DBFunc.removeTrusted(loc.getWorld(), plot, uuid); - } - if (plot.denied.contains(uuid)) { - if (plot.members.size() + plot.trusted.size() >= PlotSquared.getInstance().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) { - MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS); - return false; - } - plot.denied.remove(uuid); - DBFunc.removeDenied(loc.getWorld(), plot, uuid); - } - plot.addMember(uuid); - DBFunc.setMember(loc.getWorld(), plot, uuid); - EventUtil.manager.callMember(plr, plot, uuid, true); - } else { + if (plot.isOwner(uuid)) { + MainUtil.sendMessage(plr, C.ALREADY_OWNER); + return false; + } + + if (plot.members.contains(uuid)) { MainUtil.sendMessage(plr, C.ALREADY_ADDED); return false; } - if (plot.members.size() + plot.trusted.size() >= PlotSquared.getInstance().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) { - MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS); - return false; + if (plot.removeTrusted(uuid)) { + plot.addMember(uuid); } + else { + if (plot.members.size() + plot.trusted.size() >= PS.get().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) { + MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS); + return false; + } + if (plot.denied.contains(uuid)) { + plot.removeDenied(uuid); + } + plot.addMember(uuid); + } + EventUtil.manager.callMember(plr, plot, uuid, true); MainUtil.sendMessage(plr, C.MEMBER_ADDED); return true; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java index 98459cfc4..0c98eebb4 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java @@ -20,10 +20,15 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +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; @@ -70,11 +75,11 @@ public class Auto extends SubCommand { int size_x = 1; int size_z = 1; String schematic = ""; - if (PlotSquared.getInstance().getPlotWorlds().size() == 1) { - world = PlotSquared.getInstance().getPlotWorlds().iterator().next(); + if (PS.get().getPlotWorlds().size() == 1) { + world = PS.get().getPlotWorlds().iterator().next(); } else { world = plr.getLocation().getWorld(); - if (!PlotSquared.getInstance().isPlotWorld(world)) { + if (!PS.get().isPlotWorld(world)) { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; } @@ -122,7 +127,7 @@ public class Auto extends SubCommand { } return false; } - final PlotWorld pWorld = PlotSquared.getInstance().getPlotWorld(world); + final PlotWorld pWorld = PS.get().getPlotWorld(world); if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) { double cost = pWorld.PLOT_PRICE; cost = (size_x * size_z) * cost; @@ -148,7 +153,7 @@ public class Auto extends SubCommand { // } } final String worldname = world; - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(worldname); + final PlotWorld plotworld = PS.get().getPlotWorld(worldname); if (plotworld.TYPE == 2) { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(new Location(worldname, loc.getX(), loc.getY(), loc.getZ())); @@ -199,7 +204,7 @@ public class Auto extends SubCommand { MainUtil.lastPlot.put(worldname, start); if (lastPlot) { } - if ((PlotSquared.getInstance().getPlots(worldname).get(start) != null) && (PlotSquared.getInstance().getPlots(worldname).get(start).owner != null)) { + if ((PS.get().getPlots(worldname).get(start) != null) && (PS.get().getPlots(worldname).get(start).owner != null)) { continue; } else { lastPlot = false; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Buy.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Buy.java index 36769c9cb..35fffb747 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Buy.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Buy.java @@ -20,13 +20,18 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +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.Flag; import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotHandler; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; @@ -46,7 +51,7 @@ public class Buy extends SubCommand { } final Location loc = plr.getLocation(); final String world = loc.getWorld(); - if (!PlotSquared.getInstance().isPlotWorld(world)) { + if (!PS.get().isPlotWorld(world)) { return sendMessage(plr, C.NOT_IN_PLOT_WORLD); } Plot plot; @@ -83,7 +88,7 @@ public class Buy extends SubCommand { final PlotId id = plot.id; final PlotId id2 = MainUtil.getTopPlot(plot).id; final int size = MainUtil.getPlotSelectionIds(id, id2).size(); - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); + final PlotWorld plotworld = PS.get().getPlotWorld(world); if (plotworld.USE_ECONOMY) { price += plotworld.PLOT_PRICE * size; initPrice += plotworld.SELL_PRICE * size; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Chat.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Chat.java index c3a63c616..7b8a521af 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Chat.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Chat.java @@ -1,6 +1,6 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotWorld; @@ -13,7 +13,7 @@ public class Chat extends SubCommand { @Override public boolean execute(PlotPlayer plr, String... args) { final String world = plr.getLocation().getWorld(); - if (!PlotSquared.getInstance().isPlotWorld(world)) { + if (!PS.get().isPlotWorld(world)) { return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); } boolean enable = !(plr.getMeta("chat") != null && (Boolean) plr.getMeta("chat")); @@ -24,7 +24,7 @@ public class Chat extends SubCommand { enable = false; } } - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); + final PlotWorld plotworld = PS.get().getPlotWorld(world); if (!enable && plotworld.PLOT_CHAT) { return !sendMessage(plr, C.PLOT_CHAT_FORCED); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java index 52cdecbe3..1fae73967 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java @@ -20,14 +20,18 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotWorld; -import com.intellectualcrafters.plot.util.*; +import com.intellectualcrafters.plot.util.EconHandler; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; /** @@ -56,8 +60,8 @@ public class Claim extends SubCommand { MainUtil.teleportPlayer(player, loc, plot); } final String world = plot.world; - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); - final Plot plot2 = PlotSquared.getInstance().getPlots(world).get(plot.id); + final PlotWorld plotworld = PS.get().getPlotWorld(world); + final Plot plot2 = PS.get().getPlots(world).get(plot.id); if (plotworld.SCHEMATIC_ON_CLAIM) { Schematic sch; if (schematic.equals("")) { @@ -70,7 +74,7 @@ public class Claim extends SubCommand { } SchematicHandler.manager.paste(sch, plot2, 0, 0); } - PlotSquared.getInstance().getPlotManager(world).claimPlot(plotworld, plot); + PS.get().getPlotManager(world).claimPlot(plotworld, plot); } return result; } @@ -93,7 +97,7 @@ public class Claim extends SubCommand { if (!MainUtil.canClaim(plr, plot)) { return sendMessage(plr, C.PLOT_IS_CLAIMED); } - final PlotWorld world = PlotSquared.getInstance().getPlotWorld(plot.world); + final PlotWorld world = PS.get().getPlotWorld(plot.world); if ((EconHandler.manager != null) && world.USE_ECONOMY) { final double cost = world.PLOT_PRICE; if (cost > 0d) { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java index 2b96075e1..93d34131e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java @@ -20,7 +20,9 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.Set; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.Location; @@ -33,8 +35,6 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.Set; - public class Clear extends SubCommand { public Clear() { super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, false); @@ -45,25 +45,25 @@ public class Clear extends SubCommand { if (plr == null) { // Is console if (args.length < 2) { - PlotSquared.log("You need to specify two arguments: ID (0;0) & World (world)"); + PS.log("You need to specify two arguments: ID (0;0) & World (world)"); } else { final PlotId id = PlotId.fromString(args[0]); final String world = args[1]; if (id == null) { - PlotSquared.log("Invalid Plot ID: " + args[0]); + PS.log("Invalid Plot ID: " + args[0]); } else { - if (!PlotSquared.getInstance().isPlotWorld(world)) { - PlotSquared.log("Invalid plot world: " + world); + if (!PS.get().isPlotWorld(world)) { + PS.log("Invalid plot world: " + world); } else { final Plot plot = MainUtil.getPlot(world, id); if (plot == null) { - PlotSquared.log("Could not find plot " + args[0] + " in world " + world); + PS.log("Could not find plot " + args[0] + " in world " + world); } else { Runnable runnable = new Runnable() { @Override public void run() { - MainUtil.clear(world, plot, plot.owner == null, null); - PlotSquared.log("Plot " + plot.getId().toString() + " cleared."); + MainUtil.clear(plot, plot.owner == null, null); + PS.log("Plot " + plot.getId().toString() + " cleared."); } }; if (Settings.CONFIRM_CLEAR && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { @@ -84,7 +84,7 @@ public class Clear extends SubCommand { PlotId id = PlotId.fromString(args[0]); if (id == null) { if (args[1].equalsIgnoreCase("mine")) { - Set plots = PlotSquared.getInstance().getPlots(plr); + Set plots = PS.get().getPlots(plr); if (plots.size() == 0) { MainUtil.sendMessage(plr, C.NO_PLOTS); return false; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java index 68d282e47..ed1aef502 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java @@ -20,21 +20,29 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.UUID; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.generator.AugmentedPopulator; import com.intellectualcrafters.plot.generator.HybridGen; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.BlockLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotClusterId; +import com.intellectualcrafters.plot.object.PlotGenerator; +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.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.UUID; - public class Cluster extends SubCommand { public Cluster() { super(Command.CLUSTER, "Manage a plot cluster", "cluster", CommandCategory.ACTIONS, true); @@ -121,25 +129,25 @@ public class Cluster extends SubCommand { } ClusterManager.clusters.get(world).add(cluster); // Add any existing plots to the current cluster - for (final Plot plot : PlotSquared.getInstance().getPlots(plr.getLocation().getWorld()).values()) { + for (final Plot plot : PS.get().getPlots(plr.getLocation().getWorld()).values()) { final PlotCluster current = ClusterManager.getCluster(plot); if (cluster.equals(current) && !cluster.isAdded(plot.owner)) { cluster.invited.add(plot.owner); DBFunc.setInvited(world, cluster, plot.owner); } } - PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); + PlotWorld plotworld = PS.get().getPlotWorld(world); if (plotworld == null) { - PlotSquared.getInstance().config.createSection("worlds." + world); - PlotSquared.getInstance().loadWorld(world, null); + PS.get().config.createSection("worlds." + world); + PS.get().loadWorld(world, null); } else { - final String gen_string = PlotSquared.getInstance().config.getString("worlds." + world + "." + "generator.plugin"); + final String gen_string = PS.get().config.getString("worlds." + world + "." + "generator.plugin"); PlotGenerator generator; if (gen_string == null) { generator = new HybridGen(world); } else { - generator = (PlotGenerator) PlotSquared.getInstance().IMP.getGenerator(world, gen_string); + generator = (PlotGenerator) PS.get().IMP.getGenerator(world, gen_string); } new AugmentedPopulator(world, generator, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2); } @@ -177,17 +185,17 @@ public class Cluster extends SubCommand { return false; } } - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(plr.getLocation().getWorld()); + final PlotWorld plotworld = PS.get().getPlotWorld(plr.getLocation().getWorld()); if (plotworld.TYPE == 2) { final ArrayList toRemove = new ArrayList<>(); - for (final Plot plot : PlotSquared.getInstance().getPlots(plr.getLocation().getWorld()).values()) { + for (final Plot plot : PS.get().getPlots(plr.getLocation().getWorld()).values()) { final PlotCluster other = ClusterManager.getCluster(plot); if (cluster.equals(other)) { toRemove.add(plot); } } for (final Plot plot : toRemove) { - DBFunc.delete(plot.world, plot); + plot.unclaim(); } } DBFunc.delete(cluster); @@ -361,11 +369,11 @@ public class Cluster extends SubCommand { if (player != null) { MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); } - for (final Plot plot : PlotSquared.getInstance().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(); - DBFunc.delete(world, plot); + plot.unclaim(); } } MainUtil.sendMessage(plr, C.CLUSTER_KICKED_USER); @@ -411,11 +419,11 @@ public class Cluster extends SubCommand { cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); MainUtil.sendMessage(plr, C.CLUSTER_REMOVED, cluster.getName()); - for (final Plot plot : PlotSquared.getInstance().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(); - DBFunc.delete(world, plot); + plot.unclaim(); } } return true; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java index 5521b76da..e6ebde753 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java @@ -38,13 +38,11 @@ public enum Command { ADD("add","a"), TRUST("trust", "t"), DENY("deny", "d"), - REMOVE("remove", "r"), UNTRUST("untrust", "ut"), UNDENY("undeny", "ud"), - TOGGLE("toggle", "attribute"), - + DOWNLOAD("download", "dl"), MOVE("move"), FLAG("flag", "f"), TARGET("target"), diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Condense.java index 28b715b15..d9022220b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Condense.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Condense.java @@ -20,17 +20,21 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; -import org.apache.commons.lang.StringUtils; - -import java.util.*; -import java.util.Set; public class Condense extends SubCommand { public static boolean TASK = false; @@ -40,7 +44,7 @@ public class Condense extends SubCommand { } public static void sendMessage(final String message) { - PlotSquared.log("&3PlotSquared -> Plot condense&8: &7" + message); + PS.log("&3PlotSquared -> Plot condense&8: &7" + message); } @Override @@ -54,7 +58,7 @@ public class Condense extends SubCommand { return false; } final String worldname = args[0]; - if (!BlockManager.manager.isWorld(worldname) || !PlotSquared.getInstance().isPlotWorld(worldname)) { + if (!BlockManager.manager.isWorld(worldname) || !PS.get().isPlotWorld(worldname)) { MainUtil.sendMessage(plr, "INVALID WORLD"); return false; } @@ -77,7 +81,7 @@ public class Condense extends SubCommand { return false; } final int radius = Integer.parseInt(args[2]); - final Collection plots = PlotSquared.getInstance().getPlots(worldname).values(); + final Collection plots = PS.get().getPlots(worldname).values(); final int size = plots.size(); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); if (radius < minimum_radius) { @@ -95,7 +99,7 @@ public class Condense extends SubCommand { start = Auto.getNextPlot(start, 1); } if (free.size() == 0 || to_move.size() == 0) { - MainUtil.sendMessage(plr, "NO PLOTS FOUND"); + 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() { @@ -166,7 +170,7 @@ public class Condense extends SubCommand { return false; } final int radius = Integer.parseInt(args[2]); - final Collection plots = PlotSquared.getInstance().getPlots(worldname).values(); + final Collection plots = PS.get().getPlots(worldname).values(); final int size = plots.size(); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); if (radius < minimum_radius) { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java index 0be56253d..996a744d4 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java @@ -50,7 +50,7 @@ public class Copy extends SubCommand { if (plot1 == null) { return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); } - if (!plot1.isAdded(plr.getUUID()) && !plr.hasPermission(Permissions.ADMIN)) { + if (!plot1.isAdded(plr.getUUID()) && !plr.hasPermission(Permissions.ADMIN.s)) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java index 7abfed0a4..32661bf60 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.generator.HybridPlotWorld; import com.intellectualcrafters.plot.generator.HybridUtils; @@ -41,7 +41,7 @@ public class CreateRoadSchematic extends SubCommand { if (plot == null) { return sendMessage(player, C.NOT_IN_PLOT); } - if (!(PlotSquared.getInstance().getPlotWorld(loc.getWorld()) instanceof HybridPlotWorld)) { + if (!(PS.get().getPlotWorld(loc.getWorld()) instanceof HybridPlotWorld)) { return sendMessage(player, C.NOT_IN_PLOT_WORLD); } HybridUtils.manager.setupRoadSchematic(plot); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Database.java index 68d0054ff..f1e3dbd4f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Database.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Database.java @@ -1,6 +1,11 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.UUID; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.MySQL; import com.intellectualcrafters.plot.database.SQLManager; @@ -11,11 +16,6 @@ import com.intellectualcrafters.plot.util.StringComparison; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.UUID; - /** * Created 2014-11-15 for PlotSquared * @@ -28,7 +28,7 @@ public class Database extends SubCommand { private static boolean sendMessageU(final UUID uuid, final String msg) { if (uuid == null) { - PlotSquared.log(msg); + PS.log(msg); } else { final PlotPlayer p = UUIDHandler.getPlayer(uuid); if ((p != null) && p.isOnline()) { @@ -41,7 +41,7 @@ public class Database extends SubCommand { } public static void insertPlots(final SQLManager manager, final UUID requester, final Connection c) { - final java.util.Set plots = PlotSquared.getInstance().getPlots(); + final java.util.Set plots = PS.get().getPlots(); TaskManager.runTaskAsync(new Runnable() { @Override public void run() { @@ -92,7 +92,7 @@ public class Database extends SubCommand { } Connection n; try { - n = new MySQL(PlotSquared.getInstance(), host, port, database, username, password).openConnection(); + n = new MySQL(host, port, database, username, password).openConnection(); // Connection if (n.isClosed()) { return sendMessage(plr, "Failed to open connection"); @@ -128,7 +128,7 @@ public class Database extends SubCommand { private boolean sendMessage(final PlotPlayer player, final String msg) { if (player == null) { - PlotSquared.log(msg); + PS.log(msg); } else { MainUtil.sendMessage(player, msg); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java index 7f1e6329b..9c1be1085 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.Lag; @@ -51,7 +51,7 @@ public class Debug extends SubCommand { } { final StringBuilder worlds = new StringBuilder(""); - for (final String world : PlotSquared.getInstance().getPlotWorlds()) { + for (final String world : PS.get().getPlotWorlds()) { worlds.append(world).append(" "); } information.append(header); @@ -61,7 +61,7 @@ public class Debug extends SubCommand { information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); information.append(getSection(section, "PlotWorld")); information.append(getLine(line, "Plot Worlds", worlds)); - information.append(getLine(line, "Owned Plots", PlotSquared.getInstance().getPlots().size())); + information.append(getLine(line, "Owned Plots", PS.get().getPlots().size())); information.append(getSection(section, "Messages")); information.append(getLine(line, "Total Messages", C.values().length)); information.append(getLine(line, "View all captions", "/plot debug msg")); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java index 8fb5dc78c..de467d6d2 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java @@ -20,20 +20,27 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; +import java.util.ArrayList; +import java.util.UUID; + import com.google.common.collect.BiMap; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; +import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.ArrayList; -import java.util.UUID; - /** * @author Citymonstret */ @@ -66,7 +73,7 @@ public class DebugClaimTest extends SubCommand { 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) || !PlotSquared.getInstance().isPlotWorld(world)) { + if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) { return !MainUtil.sendMessage(null, "&cInvalid plot world!"); } PlotId min, max; @@ -80,12 +87,12 @@ public class DebugClaimTest extends SubCommand { } 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 = PlotSquared.getInstance().getPlotManager(world); - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); + 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)) { final Plot plot = MainUtil.getPlot(world, id); - final boolean contains = PlotSquared.getInstance().getPlots(world).containsKey(plot.id); + final boolean contains = PS.get().getPlots(world).containsKey(plot.id); if (contains) { MainUtil.sendMessage(null, " - &cDB Already contains: " + plot.id); continue; @@ -134,7 +141,7 @@ public class DebugClaimTest extends SubCommand { } }); for (final Plot plot : plots) { - PlotSquared.getInstance().updatePlot(plot); + PS.get().updatePlot(plot); } MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); } else { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java index 524d38270..9adbc94da 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClear.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.generator.SquarePlotWorld; import com.intellectualcrafters.plot.object.Location; @@ -42,19 +42,19 @@ public class DebugClear extends SubCommand { if (plr == null) { // Is console if (args.length < 2) { - PlotSquared.log("You need to specify two arguments: ID (0;0) & World (world)"); + PS.log("You need to specify two arguments: ID (0;0) & World (world)"); } else { final PlotId id = PlotId.fromString(args[0]); final String world = args[1]; if (id == null) { - PlotSquared.log("Invalid Plot ID: " + args[0]); + PS.log("Invalid Plot ID: " + args[0]); } else { - if (!PlotSquared.getInstance().isPlotWorld(world) || !(PlotSquared.getInstance().getPlotWorld(world) instanceof SquarePlotWorld)) { - PlotSquared.log("Invalid plot world: " + world); + if (!PS.get().isPlotWorld(world) || !(PS.get().getPlotWorld(world) instanceof SquarePlotWorld)) { + PS.log("Invalid plot world: " + world); } else { final Plot plot = MainUtil.getPlot(world, id); if (plot == null) { - PlotSquared.log("Could not find plot " + args[0] + " in world " + world); + PS.log("Could not find plot " + args[0] + " in world " + world); } else { final Location pos1 = MainUtil.getPlotBottomLoc(world, plot.id).add(1, 0, 1); final Location pos2 = MainUtil.getPlotTopLoc(world, plot.id); @@ -67,8 +67,8 @@ public class DebugClear extends SubCommand { @Override public void run() { MainUtil.runners.remove(plot); - PlotSquared.log("Plot " + plot.getId().toString() + " cleared."); - PlotSquared.log("&aDone!"); + PS.log("Plot " + plot.getId().toString() + " cleared."); + PS.log("&aDone!"); } }); } @@ -79,7 +79,7 @@ public class DebugClear extends SubCommand { } final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); - if ((plot == null) || !(PlotSquared.getInstance().getPlotWorld(loc.getWorld()) instanceof SquarePlotWorld)) { + 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))) { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java index d21a3e9d6..91d971378 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java @@ -20,26 +20,36 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.generator.BukkitHybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.OfflinePlotPlayer; +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.ChunkManager; import com.intellectualcrafters.plot.util.ExpireManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.PrintWriter; -import java.sql.Timestamp; -import java.util.*; public class DebugExec extends SubCommand { public DebugExec() { @@ -82,11 +92,11 @@ public class DebugExec extends SubCommand { } case "remove-flag": { if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec reset-flat "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag "); return false; } String flag = args[1]; - for (Plot plot : PlotSquared.getInstance().getPlots()) { + for (Plot plot : PS.get().getPlots()) { if (FlagManager.getPlotFlag(plot, flag) != null) { FlagManager.removePlotFlag(plot, flag); } @@ -95,11 +105,11 @@ public class DebugExec extends SubCommand { } case "start-rgar": { if (args.length != 2) { - PlotSquared.log("&cInvalid syntax: /plot debugexec start-rgar "); + PS.log("&cInvalid syntax: /plot debugexec start-rgar "); return false; } boolean result; - if (!PlotSquared.getInstance().isPlotWorld(args[1])) { + if (!PS.get().isPlotWorld(args[1])) { MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); return false; } @@ -110,26 +120,26 @@ public class DebugExec extends SubCommand { result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0); } if (!result) { - PlotSquared.log("&cCannot schedule mass schematic update! (Is one already in progress?)"); + PS.log("&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } return true; } case "stop-rgar": { if (((BukkitHybridUtils)(HybridUtils.manager)).task == 0) { - PlotSquared.log("&cTASK NOT RUNNING!"); + PS.log("&cTASK NOT RUNNING!"); return false; } ((BukkitHybridUtils)(HybridUtils.manager)).task = 0; Bukkit.getScheduler().cancelTask(((BukkitHybridUtils)(HybridUtils.manager)).task); - PlotSquared.log("&cCancelling task..."); + PS.log("&cCancelling task..."); while (BukkitHybridUtils.chunks.size() > 0) { ChunkLoc chunk = BukkitHybridUtils.chunks.get(0); BukkitHybridUtils.chunks.remove(0); HybridUtils.manager.regenerateRoad(BukkitHybridUtils.world, chunk, 0); ChunkManager.manager.unloadChunk(BukkitHybridUtils.world, chunk); } - PlotSquared.log("&cCancelled!"); + PS.log("&cCancelled!"); return true; } case "start-expire": { @@ -197,7 +207,7 @@ public class DebugExec extends SubCommand { return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run"); } final String world = args[1]; - if (!BlockManager.manager.isWorld(world) || !PlotSquared.getInstance().isPlotWorld(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<>(); @@ -208,7 +218,7 @@ public class DebugExec extends SubCommand { Trim.sendMessage(" - MCA #: " + empty.size()); Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)"); Trim.sendMessage("Exporting log for manual approval..."); - final File file = new File(PlotSquared.getInstance().IMP.getDirectory() + File.separator + "trim.txt"); + final File file = new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt"); PrintWriter writer; try { writer = new PrintWriter(file); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java index efe5d2981..016046b4d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java @@ -20,7 +20,11 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.flag.Flag; @@ -30,10 +34,6 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - public class DebugFixFlags extends SubCommand { public DebugFixFlags() { super(Command.DEBUGFIXFLAGS, "Attempt to fix all flags for a world", "debugclear", CommandCategory.DEBUG, false); @@ -50,12 +50,12 @@ public class DebugFixFlags extends SubCommand { return false; } final String world = args[0]; - if (!BlockManager.manager.isWorld(world) || !PlotSquared.getInstance().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 : PlotSquared.getInstance().getPlots(world).values()) { + for (final Plot plot : PS.get().getPlots(world).values()) { final HashMap flags = plot.settings.flags; Iterator> i = flags.entrySet().iterator(); boolean changed = false; @@ -66,7 +66,7 @@ public class DebugFixFlags extends SubCommand { } } if (changed) { - DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); + DBFunc.setFlags(plot, plot.settings.flags.values()); } } MainUtil.sendMessage(plr, "&aDone!"); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java index 12b79ecb3..6bdaf9d3b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java @@ -22,7 +22,7 @@ package com.intellectualcrafters.plot.commands; import java.lang.reflect.Field; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; @@ -39,13 +39,13 @@ public class DebugLoadTest extends SubCommand { public boolean execute(final PlotPlayer plr, final String... args) { if (plr == null) { try { - final Field fPlots = PlotSquared.class.getDeclaredField("plots"); + final Field fPlots = PS.class.getDeclaredField("plots"); fPlots.setAccessible(true); fPlots.set(null, DBFunc.getPlots()); } catch (final Exception e) { - PlotSquared.log("&3===FAILED&3==="); + PS.log("&3===FAILED&3==="); e.printStackTrace(); - PlotSquared.log("&3===END OF STACKTRACE==="); + PS.log("&3===END OF STACKTRACE==="); } } else { MainUtil.sendMessage(plr, "&6This command can only be executed by console as it has been deemed unsafe if abused.."); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java index 7e9b8b106..862609aaa 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.generator.HybridPlotWorld; import com.intellectualcrafters.plot.generator.HybridUtils; @@ -38,7 +38,7 @@ public class DebugRoadRegen extends SubCommand { public boolean execute(final PlotPlayer player, final String... args) { final Location loc = player.getLocation(); final String world = loc.getWorld(); - if (!(PlotSquared.getInstance().getPlotWorld(world) instanceof HybridPlotWorld)) { + if (!(PS.get().getPlotWorld(world) instanceof HybridPlotWorld)) { return sendMessage(player, C.NOT_IN_PLOT_WORLD); } final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java index f4854901d..b49bbd730 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java @@ -20,14 +20,14 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; -import java.util.ArrayList; - /** * @author Citymonstret */ @@ -40,7 +40,7 @@ public class DebugSaveTest extends SubCommand { public boolean execute(final PlotPlayer plr, final String... args) { if (plr == null) { final ArrayList plots = new ArrayList(); - plots.addAll(PlotSquared.getInstance().getPlots()); + plots.addAll(PS.get().getPlots()); MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`"); DBFunc.createPlotsAndData(plots, new Runnable() { @Override diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java index aea05eb04..7d95dc9ef 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugUUID.java @@ -20,7 +20,17 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map.Entry; +import java.util.UUID; + +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; @@ -37,15 +47,6 @@ import com.intellectualcrafters.plot.uuid.DefaultUUIDWrapper; import com.intellectualcrafters.plot.uuid.LowerOfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.OfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import org.bukkit.Bukkit; - -import java.io.File; -import java.io.FilenameFilter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map.Entry; -import java.util.UUID; public class DebugUUID extends SubCommand { public DebugUUID() { @@ -139,7 +140,7 @@ public class DebugUUID extends SubCommand { final UUID uuid = UUID.fromString(s); uuids.add(uuid); } catch (final Exception e) { - PlotSquared.log(C.PREFIX.s() + "Invalid playerdata: " + current); + PS.log(C.PREFIX.s() + "Invalid playerdata: " + current); } } } @@ -170,7 +171,7 @@ public class DebugUUID extends SubCommand { uCReverse.put(uuid2, uuid); } } catch (final Throwable e) { - PlotSquared.log(C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat"); + PS.log(C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } for (final String name : names) { @@ -215,7 +216,7 @@ public class DebugUUID extends SubCommand { MainUtil.sendConsoleMessage("&7 - Updating plot objects"); - for (Plot plot : PlotSquared.getInstance().getPlotsRaw()) { + for (Plot plot : PS.get().getPlotsRaw()) { UUID value = uCMap.get(plot.owner); if (value != null) { plot.owner = value; @@ -235,13 +236,13 @@ public class DebugUUID extends SubCommand { database.createTables(Settings.DB.USE_MYSQL ? "mysql" : "sqlite"); if (!result) { MainUtil.sendConsoleMessage("&cConversion failed! Attempting recovery"); - for (Plot plot : PlotSquared.getInstance().getPlots()) { + for (Plot plot : PS.get().getPlots()) { UUID value = uCReverse.get(plot.owner); if (value != null) { plot.owner = value; } } - database.createPlotsAndData(new ArrayList<>(PlotSquared.getInstance().getPlots()), new Runnable() { + database.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() { @Override public void run() { MainUtil.sendMessage(null, "&6Recovery was successful!"); @@ -256,19 +257,19 @@ public class DebugUUID extends SubCommand { } if (newWrapper instanceof OfflineUUIDWrapper) { - PlotSquared.getInstance().config.set("UUID.force-lowercase", false); - PlotSquared.getInstance().config.set("UUID.offline", true); + PS.get().config.set("UUID.force-lowercase", false); + PS.get().config.set("UUID.offline", true); } else if (newWrapper instanceof LowerOfflineUUIDWrapper) { - PlotSquared.getInstance().config.set("UUID.force-lowercase", true); - PlotSquared.getInstance().config.set("UUID.offline", true); + PS.get().config.set("UUID.force-lowercase", true); + PS.get().config.set("UUID.offline", true); } else if (newWrapper instanceof DefaultUUIDWrapper) { - PlotSquared.getInstance().config.set("UUID.force-lowercase", false); - PlotSquared.getInstance().config.set("UUID.offline", false); + PS.get().config.set("UUID.force-lowercase", false); + PS.get().config.set("UUID.offline", false); } try { - PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile); + PS.get().config.save(PS.get().configFile); } catch (Exception e) { MainUtil.sendConsoleMessage("Could not save configuration. It will need to be manuall set!"); @@ -279,7 +280,7 @@ public class DebugUUID extends SubCommand { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { - ArrayList plots = new ArrayList<>(PlotSquared.getInstance().getPlots()); + ArrayList plots = new ArrayList<>(PS.get().getPlots()); database.createPlotsAndData(plots, new Runnable() { @Override public void run() { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java index e3659f964..1d731a78c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; @@ -28,7 +28,11 @@ import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotWorld; -import com.intellectualcrafters.plot.util.*; +import com.intellectualcrafters.plot.util.CmdConfirm; +import com.intellectualcrafters.plot.util.EconHandler; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; public class Delete extends SubCommand { @@ -50,7 +54,7 @@ public class Delete extends SubCommand { return !sendMessage(plr, C.NO_PLOT_PERMS); } assert plot != null; - final PlotWorld pWorld = PlotSquared.getInstance().getPlotWorld(plot.world); + final PlotWorld pWorld = PS.get().getPlotWorld(plot.world); if (MainUtil.runners.containsKey(plot)) { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; @@ -65,7 +69,7 @@ public class Delete extends SubCommand { sendMessage(plr, C.ADDED_BALANCE, c + ""); } } - PlotSquared.getInstance().removePlot(loc.getWorld(), plot.id, true); + PS.get().removePlot(loc.getWorld(), plot.id, true); final long start = System.currentTimeMillis(); final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() { @Override @@ -76,7 +80,7 @@ public class Delete extends SubCommand { if (!result) { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); } - DBFunc.delete(loc.getWorld(), plot); + DBFunc.delete(plot); } }; if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Deny.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Deny.java index 3697e7ab5..d50bf4f63 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Deny.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Deny.java @@ -20,7 +20,9 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.UUID; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Location; @@ -31,8 +33,6 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.UUID; - public class Deny extends SubCommand { public Deny() { super(Command.DENY, "Deny a user from a plot", "deny ", CommandCategory.ACTIONS, true); @@ -67,29 +67,22 @@ public class Deny extends SubCommand { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } - if (!plot.denied.contains(uuid)) { - if (plot.isOwner(uuid)) { - MainUtil.sendMessage(plr, C.ALREADY_OWNER); - return false; - } - if (plot.trusted.contains(uuid)) { - plot.trusted.remove(uuid); - DBFunc.removeTrusted(loc.getWorld(), plot, uuid); - } - if (plot.members.contains(uuid)) { - plot.members.remove(uuid); - DBFunc.removeMember(loc.getWorld(), plot, uuid); - } - plot.addDenied(uuid); - DBFunc.setDenied(loc.getWorld(), plot, uuid); - EventUtil.manager.callDenied(plr, plot, uuid, true); - } else { + if (plot.isOwner(uuid)) { + MainUtil.sendMessage(plr, C.ALREADY_OWNER); + return false; + } + + if (plot.denied.contains(uuid)) { MainUtil.sendMessage(plr, C.ALREADY_ADDED); return false; } + plot.removeMember(uuid); + plot.removeTrusted(uuid); + plot.addDenied(uuid); + EventUtil.manager.callDenied(plr, plot, uuid, true); MainUtil.sendMessage(plr, C.DENIED_ADDED); if (!uuid.equals(DBFunc.everyone)) { - PlotSquared.getInstance().IMP.handleKick(uuid, C.YOU_GOT_DENIED); + PS.get().IMP.handleKick(uuid, C.YOU_GOT_DENIED); } return true; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Disable.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Disable.java new file mode 100644 index 000000000..9880a6766 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Disable.java @@ -0,0 +1,47 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////// +// 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.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.TaskManager; + +public class Disable extends SubCommand { + public static String downloads, version; + + public Disable() { + super("disable", "plots.admin", "Disable PlotSquared", "disable", "unload", CommandCategory.DEBUG, false); + } + + @Override + public boolean execute(final PlotPlayer plr, final String... args) { + PS.log("&cDisabling PlotSquared and all dependencies!"); + PS.get().IMP.disable(); + return true; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Download.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Download.java new file mode 100644 index 000000000..7d81d6948 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Download.java @@ -0,0 +1,56 @@ +package com.intellectualcrafters.plot.commands; + +import java.net.URL; + +import com.intellectualcrafters.jnbt.CompoundTag; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.SchematicHandler; +import com.intellectualcrafters.plot.util.TaskManager; + +public class Download extends SubCommand { + public Download() { + super(Command.DOWNLOAD, "Download your plot", "dl", CommandCategory.ACTIONS, true); + } + + @Override + public boolean execute(final PlotPlayer plr, String... args) { + if (!Settings.METRICS) { + MainUtil.sendMessage(plr, "&cPlease enable metrics in order to use this command.\n&7 - Or host it yourself if you don't like the free service"); + return false; + } + final String world = plr.getLocation().getWorld(); + 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 (MainUtil.runners.containsKey(plot)) { + MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); + return false; + } + MainUtil.runners.put(plot, 1); + MainUtil.sendMessage(plr, C.GENERATING_LINK); + final CompoundTag tag = SchematicHandler.manager.getCompoundTag(plot.world, plot.id); + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + URL url = SchematicHandler.manager.upload(tag); + if (url == null) { + MainUtil.sendMessage(plr, C.GENERATING_LINK_FAILED); + return; + } + MainUtil.sendMessage(plr, url.toString()); + MainUtil.runners.remove(plot); + } + }); + return true; + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java index 51a37fb77..0a2c21549 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java @@ -159,7 +159,7 @@ public class FlagCmd extends SubCommand { if ((args.length == 3) && flag.getAbstractFlag().isList()) { final String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); ((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value); - DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); + DBFunc.setFlags(plot, plot.settings.flags.values()); } else { final boolean result = FlagManager.removePlotFlag(plot, flag.getKey()); if (!result) { @@ -206,7 +206,7 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; } - DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); + DBFunc.setFlags(plot, plot.settings.flags.values()); MainUtil.sendMessage(player, C.FLAG_ADDED); APlotListener.manager.plotEntry(player, plot); return true; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java index 9337babbc..5389e475a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java @@ -20,14 +20,14 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; -import java.util.ArrayList; - /** * @author Citymonstret */ @@ -37,7 +37,7 @@ public class Home extends SubCommand { } private Plot isAlias(final String a) { - for (final Plot p : PlotSquared.getInstance().getPlots()) { + for (final Plot p : PS.get().getPlots()) { if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { return p; } @@ -47,7 +47,7 @@ public class Home extends SubCommand { @Override public boolean execute(final PlotPlayer plr, String... args) { - final ArrayList plots = PlotSquared.getInstance().sortPlotsByWorld(PlotSquared.getInstance().getPlots(plr)); + final ArrayList plots = PS.get().sortPlotsByWorld(PS.get().getPlots(plr)); if (plots.size() == 1) { MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(0)); return true; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java index b0288d3bd..3563bc180 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java @@ -21,14 +21,12 @@ package com.intellectualcrafters.plot.commands; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.UUID; import java.util.regex.Matcher; import org.apache.commons.lang.StringUtils; -import com.intellectualcrafters.plot.PlotSquared; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; @@ -38,7 +36,6 @@ 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.PlotWorld; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; @@ -74,9 +71,7 @@ public class Info extends SubCommand { plot = MainUtil.getPlotFromString(player, null, player == null); break; default: - System.out.print("CHECKING: " + arg); plot = MainUtil.getPlotFromString(player, arg, player == null); - System.out.print(plot); if (args.length == 2) { arg = args[1]; } @@ -124,13 +119,6 @@ public class Info extends SubCommand { MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y)); return true; } - String owner = "none"; - if (plot.owner == null) { - owner = "unowned"; - } - else { - owner = getPlayerList(plot.getOwners()); - } String info = C.PLOT_INFO.s(); if (arg != null) { info = getCaption(arg); @@ -207,7 +195,6 @@ 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%")) { final String newInfo = info; TaskManager.runTaskAsync(new Runnable() { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index 1cf1f3a26..f761f7f93 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -24,11 +24,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import com.intellectualcrafters.plot.PlotSquared; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.StringComparison; /** @@ -111,9 +109,6 @@ public class MainCommand { } public static boolean onCommand(final PlotPlayer player, final String cmd, final String... args) { - if (!Permissions.hasPermission(player, PlotSquared.MAIN_PERMISSION)) { - return no_permission(player, PlotSquared.MAIN_PERMISSION); - } if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) { if (args.length < 2) { final StringBuilder builder = new StringBuilder(); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java index 195856867..e42dea3db 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java @@ -20,17 +20,26 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.*; -import com.intellectualcrafters.plot.util.*; -import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import org.apache.commons.lang.StringUtils; - import java.util.ArrayList; import java.util.HashSet; import java.util.UUID; +import org.apache.commons.lang.StringUtils; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; +import com.intellectualcrafters.plot.util.CmdConfirm; +import com.intellectualcrafters.plot.util.EconHandler; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; + /** * @author Citymonstret */ @@ -131,7 +140,7 @@ public class Merge extends SubCommand { HashSet multiPlots = new HashSet<>(); final UUID u1 = plot.owner; for (final PlotId myid : plots) { - final Plot myplot = PlotSquared.getInstance().getPlots(world).get(myid); + final Plot myplot = PS.get().getPlots(world).get(myid); if (myplot == null || myplot.owner == null) { MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); return false; @@ -150,6 +159,10 @@ public class Merge extends SubCommand { multiUUID.add(u2); } if (multiMerge) { + if (!Permissions.hasPermission(plr, Permissions.MERGE_OTHER)) { + MainUtil.sendMessage(plr, C.NO_PERMISSION, Permissions.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() { @@ -163,7 +176,7 @@ public class Merge extends SubCommand { sendMessage(accepter, C.MERGE_NOT_VALID); return; } - final PlotWorld plotWorld = PlotSquared.getInstance().getPlotWorld(world); + final PlotWorld plotWorld = PS.get().getPlotWorld(world); if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) { double cost = plotWorld.MERGE_PRICE; cost = plots.size() * cost; @@ -192,7 +205,7 @@ public class Merge extends SubCommand { MainUtil.sendMessage(plr, C.MERGE_REQUESTED); return true; } - final PlotWorld plotWorld = PlotSquared.getInstance().getPlotWorld(world); + final PlotWorld plotWorld = PS.get().getPlotWorld(world); if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) { double cost = plotWorld.MERGE_PRICE; cost = plots.size() * cost; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Move.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Move.java index bede75847..d0ce4adc8 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Move.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Move.java @@ -20,9 +20,13 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.*; +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.PlotWorld; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; @@ -48,7 +52,7 @@ public class Move extends SubCommand { if (plot1 == null) { return !sendMessage(plr, C.NOT_IN_PLOT); } - if (!plot1.isAdded(plr.getUUID()) && !plr.hasPermission(Permissions.ADMIN)) { + if (!plot1.isAdded(plr.getUUID()) && !plr.hasPermission(Permissions.ADMIN.s)) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } @@ -61,8 +65,8 @@ public class Move extends SubCommand { } String world2; if (args.length == 2) { - PlotWorld other = PlotSquared.getInstance().getPlotWorld(args[1]); - PlotWorld current = PlotSquared.getInstance().getPlotWorld(loc.getWorld()); + PlotWorld other = PS.get().getPlotWorld(args[1]); + PlotWorld current = PS.get().getPlotWorld(loc.getWorld()); if (other == null || current == null || !other.equals(current)) { MainUtil.sendMessage(plr, C.PLOTWORLD_INCOMPATIBLE); return false; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java index ef012b036..e8150d205 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java @@ -32,6 +32,7 @@ import com.intellectualcrafters.plot.object.PlotItemStack; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.TaskManager; public class MusicSubcommand extends SubCommand { public MusicSubcommand() { @@ -52,8 +53,19 @@ public class MusicSubcommand extends SubCommand { PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { public boolean onClick(int index) { PlotItemStack item = getItem(index); - FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("music"), item.id)); - PlotListener.manager.plotEntry(player, plot); + int id = item.id == 7 ? 0 : item.id; + if (id == 0) { + FlagManager.removePlotFlag(plot, "music"); + } + else { + FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("music"), id)); + } + TaskManager.runTaskLater(new Runnable() { + @Override + public void run() { + PlotListener.manager.plotEntry(player, plot); + } + }, 1); close(); return false; } @@ -66,6 +78,11 @@ public class MusicSubcommand extends SubCommand { inv.setItem(index, item); index++; } + if (player.getMeta("music") != null) { + String name = "&r&6Cancel music"; + String[] lore = {"&r&cClick to cancel!"}; + inv.setItem(index, new PlotItemStack(7, (short) 0, 1, name, lore)); + } inv.openInventory(); return true; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/NamedSubCommand.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/NamedSubCommand.java deleted file mode 100644 index 3b859a83e..000000000 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/NamedSubCommand.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.intellectualcrafters.plot.commands; - -public abstract class NamedSubCommand extends SubCommand { - - public NamedSubCommand(Command command, String description, String usage, CommandCategory category, boolean isPlayer) { - super(command, description, usage, category, isPlayer); - } - public NamedSubCommand(String cmd, String permission, String description, String usage, CommandCategory category, boolean isPlayer, String[] aliases) { - super(cmd, permission, description, usage, category, isPlayer, aliases); - } - public NamedSubCommand(String cmd, String permission, String description, String usage, String alias, CommandCategory category, boolean isPlayer) { - super(cmd, permission, description, usage, alias, category, isPlayer); - } -} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java index affc60720..928b05ac7 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java @@ -20,7 +20,12 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Plot; @@ -29,11 +34,6 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - @SuppressWarnings({ "javadoc" }) public class Purge extends SubCommand { public Purge() { @@ -91,7 +91,7 @@ public class Purge extends SubCommand { return false; } final String worldname = args[1]; - if (!PlotSquared.getInstance().getAllPlotsRaw().containsKey(worldname)) { + if (!PS.get().getAllPlotsRaw().containsKey(worldname)) { MainUtil.sendMessage(plr, "INVALID WORLD"); return false; } @@ -107,7 +107,7 @@ public class Purge extends SubCommand { return finishPurge(DBid == Integer.MAX_VALUE ? 1 : 0); } if (arg.equals("all")) { - final Set ids = PlotSquared.getInstance().getPlots(worldname).keySet(); + final Set ids = PS.get().getPlots(worldname).keySet(); int length = ids.size(); if (length == 0) { return MainUtil.sendMessage(null, "&cNo plots found"); @@ -116,7 +116,7 @@ public class Purge extends SubCommand { return finishPurge(length); } if (arg.equals("unknown")) { - final Collection plots = PlotSquared.getInstance().getPlots(worldname).values(); + final Collection plots = PS.get().getPlots(worldname).values(); final Set ids = new HashSet<>(); for (final Plot plot : plots) { if (plot.owner != null) { @@ -134,7 +134,7 @@ public class Purge extends SubCommand { return finishPurge(length); } if (arg.equals("unowned")) { - final Collection plots = PlotSquared.getInstance().getPlots(worldname).values(); + final Collection plots = PS.get().getPlots(worldname).values(); final Set ids = new HashSet<>(); for (final Plot plot : plots) { if (plot.owner == null) { @@ -150,7 +150,7 @@ public class Purge extends SubCommand { } final UUID uuid = UUIDHandler.getUUID(args[0]); if (uuid != null) { - final Set plots = PlotSquared.getInstance().getPlots(worldname, uuid); + final Set plots = PS.get().getPlots(worldname, uuid); final Set ids = new HashSet<>(); for (final Plot plot : plots) { ids.add(plot.id); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index 990f579fb..b619e44e3 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -20,22 +20,30 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.*; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.TaskManager; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.mutable.MutableInt; - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Map.Entry; import java.util.UUID; +import com.intellectualcrafters.plot.events.PlotRateEvent; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.mutable.MutableInt; + +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.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotInventory; +import com.intellectualcrafters.plot.object.PlotItemStack; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.Rating; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.TaskManager; +import org.bukkit.Bukkit; + public class Rate extends SubCommand { /* * String cmd, String permission, String description, String usage, String @@ -49,23 +57,23 @@ public class Rate extends SubCommand { public boolean execute(final PlotPlayer player, final String... args) { if (args.length == 1) { if (args[0].equalsIgnoreCase("next")) { - ArrayList plots = new ArrayList<>(PlotSquared.getInstance().getPlots()); + ArrayList plots = new ArrayList<>(PS.get().getPlots()); Collections.sort(plots, new Comparator() { @Override public int compare(Plot p1, Plot p2) { - int v1 = 0; - int v2 = 0; + double v1 = 0; + double v2 = 0; if (p1.settings.ratings != null) { - for (Entry entry : p1.settings.ratings.entrySet()) { - v1 -= 11 - entry.getValue(); + for (Entry entry : p1.getRatings().entrySet()) { + v1 -= 11 - entry.getValue().getAverageRating(); } } if (p2.settings.ratings != null) { - for (Entry entry : p2.settings.ratings.entrySet()) { - v2 -= 11 - entry.getValue(); + for (Entry entry : p2.getRatings().entrySet()) { + v2 -= 11 - entry.getValue().getAverageRating(); } } - return v2 - v1; + return v2 > v1 ? 1 : -1; } }); UUID uuid = player.getUUID(); @@ -110,9 +118,17 @@ public class Rate extends SubCommand { index.increment(); if (index.intValue() >= Settings.RATING_CATEGORIES.size()) { close(); - // set rating! - plot.settings.ratings.put(player.getUUID(), rating.intValue()); - DBFunc.setRating(plot, player.getUUID(), rating.intValue()); + // handle ratings + int rV = rating.intValue(); + // CALL THE EVENT + PlotRateEvent rateEvent = new PlotRateEvent(player, rV, plot); + Bukkit.getPluginManager().callEvent(rateEvent); + // DONE CALLING THE EVENT + // get new rating + rV = rateEvent.getRating(); + // set rating + plot.settings.ratings.put(player.getUUID(), rV); + DBFunc.setRating(plot, player.getUUID(), rV); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); return false; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java index 21ffe0e08..ec98558e0 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java @@ -20,7 +20,9 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.List; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.generator.HybridPlotManager; import com.intellectualcrafters.plot.generator.HybridUtils; @@ -29,8 +31,6 @@ import com.intellectualcrafters.plot.object.PlotManager; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.ChunkManager; -import java.util.List; - public class RegenAllRoads extends SubCommand { public RegenAllRoads() { super(Command.REGENALLROADS, "Regenerate all roads in the map using the set road schematic", "rgar", CommandCategory.DEBUG, false); @@ -58,19 +58,19 @@ public class RegenAllRoads extends SubCommand { } } final String name = args[0]; - final PlotManager manager = PlotSquared.getInstance().getPlotManager(name); + final PlotManager manager = PS.get().getPlotManager(name); if ((manager == null) || !(manager instanceof HybridPlotManager)) { sendMessage(player, C.NOT_VALID_PLOT_WORLD); return false; } final List chunks = ChunkManager.manager.getChunkChunks(name); - PlotSquared.log("&cIf no schematic is set, the following will not do anything"); - PlotSquared.log("&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); - PlotSquared.log("&6Potential chunks to update: &7" + (chunks.size() * 1024)); - PlotSquared.log("&6Estimated time: &7" + (chunks.size()) + " seconds"); + PS.log("&cIf no schematic is set, the following will not do anything"); + PS.log("&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); + PS.log("&6Potential chunks to update: &7" + (chunks.size() * 1024)); + PS.log("&6Estimated time: &7" + (chunks.size()) + " seconds"); final boolean result = HybridUtils.manager.scheduleRoadUpdate(name, height); if (!result) { - PlotSquared.log("&cCannot schedule mass schematic update! (Is one already in progress?)"); + PS.log("&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } return true; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java index a573cda1c..a425d2ce1 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotWorld; @@ -36,12 +36,12 @@ public class Reload extends SubCommand { try { // The following won't affect world generation, as that has to be // loaded during startup unfortunately. - PlotSquared.getInstance().config.load(PlotSquared.getInstance().configFile); - PlotSquared.getInstance().setupConfig(); - C.setupTranslations(); - for (final String pw : PlotSquared.getInstance().getPlotWorlds()) { - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(pw); - plotworld.loadDefaultConfiguration(PlotSquared.getInstance().config.getConfigurationSection("worlds." + pw)); + PS.get().config.load(PS.get().configFile); + PS.get().setupConfig(); + C.load(PS.get().translationFile); + for (final String pw : PS.get().getPlotWorlds()) { + final PlotWorld plotworld = PS.get().getPlotWorld(pw); + plotworld.loadDefaultConfiguration(PS.get().config.getConfigurationSection("worlds." + pw)); } MainUtil.sendMessage(plr, C.RELOADED_CONFIGS); } catch (final Exception e) { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Remove.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Remove.java index 5d27bb929..bbf8809fc 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Remove.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Remove.java @@ -20,11 +20,11 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.Iterator; +import java.util.ArrayList; +import java.util.HashSet; import java.util.UUID; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; @@ -58,74 +58,56 @@ public class Remove extends SubCommand { } int count = 0; if (args[0].equals("unknown")) { - Iterator i = plot.members.iterator(); - while (i.hasNext()) { - UUID uuid = i.next(); + ArrayList toRemove = new ArrayList<>(); + HashSet all = new HashSet<>(); + all.addAll(plot.members); + all.addAll(plot.trusted); + all.addAll(plot.denied); + for (UUID uuid : all) { if (UUIDHandler.getName(uuid) == null) { - DBFunc.removeMember(plot.world, plot, uuid); - i.remove(); + toRemove.add(uuid); count++; } } - i = plot.trusted.iterator(); - while (i.hasNext()) { - UUID uuid = i.next(); - if (UUIDHandler.getName(uuid) == null) { - DBFunc.removeTrusted(plot.world, plot, uuid); - i.remove(); - count++; - } - } - i = plot.denied.iterator(); - while (i.hasNext()) { - UUID uuid = i.next(); - if (UUIDHandler.getName(uuid) == null) { - DBFunc.removeDenied(plot.world, plot, uuid); - i.remove(); - count++; - } + for (UUID uuid : toRemove) { + plot.removeDenied(uuid); + plot.removeTrusted(uuid); + plot.removeMember(uuid); } } else if (args[0].equals("*")){ - Iterator i = plot.members.iterator(); - while (i.hasNext()) { - UUID uuid = i.next(); - DBFunc.removeMember(plot.world, plot, uuid); - i.remove(); + ArrayList toRemove = new ArrayList<>(); + HashSet all = new HashSet<>(); + all.addAll(plot.members); + all.addAll(plot.trusted); + all.addAll(plot.denied); + for (UUID uuid : all) { + toRemove.add(uuid); count++; } - i = plot.trusted.iterator(); - while (i.hasNext()) { - UUID uuid = i.next(); - DBFunc.removeTrusted(plot.world, plot, uuid); - i.remove(); - count++; - } - i = plot.denied.iterator(); - while (i.hasNext()) { - UUID uuid = i.next(); - DBFunc.removeDenied(plot.world, plot, uuid); - i.remove(); - count++; + for (UUID uuid : toRemove) { + plot.removeDenied(uuid); + plot.removeTrusted(uuid); + plot.removeMember(uuid); } } else { UUID uuid = UUIDHandler.getUUID(args[0]); if (uuid != null) { if (plot.trusted.contains(uuid)) { - DBFunc.removeTrusted(plot.world, plot, uuid); - plot.trusted.remove(uuid); - count++; + if (plot.removeTrusted(uuid)) { + count++; + } } else if (plot.members.contains(uuid)) { - DBFunc.removeMember(plot.world, plot, uuid); - plot.members.remove(uuid); - count++; + if (plot.removeMember(uuid)) { + count++; + } } else if (plot.denied.contains(uuid)) { - DBFunc.removeDenied(plot.world, plot, uuid); - plot.denied.remove(uuid); - count++; + if (plot.removeDenied(uuid)) { + count++; + } } } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java index 8587ca70c..0a01443bf 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java @@ -20,22 +20,26 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.*; +import com.intellectualcrafters.plot.util.BlockManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler.DataCollection; import com.intellectualcrafters.plot.util.SchematicHandler.Dimension; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; +import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.bukkit.BukkitUtil; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; - public class SchematicCmd extends SubCommand { private int counter = 0; private boolean running = false; @@ -58,7 +62,7 @@ public class SchematicCmd extends SubCommand { switch (arg) { case "paste": { if (plr == null) { - PlotSquared.log(C.IS_CONSOLE.s()); + PS.log(C.IS_CONSOLE.s()); return false; } if (!Permissions.hasPermission(plr, "plots.schematic.paste")) { @@ -134,7 +138,7 @@ public class SchematicCmd extends SubCommand { SchematicHandler.manager.pasteStates(schematic, plot, 0, 0); sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); SchematicCmd.this.running = false; - PlotSquared.getInstance().TASK.cancelTask(SchematicCmd.this.task); + PS.get().TASK.cancelTask(SchematicCmd.this.task); return; } final int end = Math.min(start + 5000, blen); @@ -155,7 +159,7 @@ public class SchematicCmd extends SubCommand { } case "test": { if (plr == null) { - PlotSquared.log(C.IS_CONSOLE.s()); + PS.log(C.IS_CONSOLE.s()); return false; } if (!Permissions.hasPermission(plr, "plots.schematic.test")) { @@ -198,7 +202,7 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(null, "&cNeed world arg. Use &7/plots sch exportall "); return false; } - final HashMap plotmap = PlotSquared.getInstance().getPlots(args[1]); + final HashMap plotmap = PS.get().getPlots(args[1]); if ((plotmap == null) || (plotmap.size() == 0)) { MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall "); return false; @@ -215,8 +219,8 @@ public class SchematicCmd extends SubCommand { return false; } else { - PlotSquared.log("&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); - PlotSquared.log("&3PlotSquared&8->&3Schemaitc&8: &7Found &c" + plotmap.size() + "&7 plots..."); + PS.log("&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); + PS.log("&3PlotSquared&8->&3Schemaitc&8: &7Found &c" + plotmap.size() + "&7 plots..."); } break; } @@ -250,11 +254,11 @@ public class SchematicCmd extends SubCommand { world = args[1]; final String[] split = args[2].split(";"); final PlotId i = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); - if ((PlotSquared.getInstance().getPlots(world) == null) || (PlotSquared.getInstance().getPlots(world).get(i) == null)) { + if ((PS.get().getPlots(world) == null) || (PS.get().getPlots(world).get(i) == null)) { MainUtil.sendMessage(null, "&cInvalid world or id. Use &7/plots sch save "); return false; } - p2 = PlotSquared.getInstance().getPlots(world).get(i); + p2 = PS.get().getPlots(world).get(i); } catch (final Exception e) { MainUtil.sendMessage(null, "&cInvalid world or id. Use &7/plots sch save "); return false; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java index 052448af9..ce8348092 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java @@ -20,22 +20,34 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.Material; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Configuration; -import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.flag.AbstractFlag; import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.listeners.APlotListener; -import com.intellectualcrafters.plot.object.*; -import com.intellectualcrafters.plot.util.*; +import com.intellectualcrafters.plot.object.BlockLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotBlock; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; +import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.util.BlockManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.SetBlockQueue; +import com.intellectualcrafters.plot.util.StringComparison; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import org.apache.commons.lang.StringUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; /** * @author Citymonstret @@ -66,10 +78,10 @@ public class Set extends SubCommand { } } if (args.length < 1) { - PlotManager manager = PlotSquared.getInstance().getPlotManager(loc.getWorld()); + PlotManager manager = PS.get().getPlotManager(loc.getWorld()); ArrayList newValues = new ArrayList(); newValues.addAll(Arrays.asList(values)); - newValues.addAll(Arrays.asList(manager.getPlotComponents(PlotSquared.getInstance().getPlotWorld(loc.getWorld()), plot.id))); + 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; } @@ -141,8 +153,7 @@ public class Set extends SubCommand { } if (args.length > 1) { if (args[1].equalsIgnoreCase("none")) { - plot.settings.setPosition(null); - DBFunc.setPosition(loc.getWorld(), plot, ""); + plot.setHome(null); return true; } return MainUtil.sendMessage(plr, C.HOME_ARGUMENT); @@ -153,8 +164,7 @@ public class Set extends SubCommand { base.setY(0); final Location relative = plr.getLocation().subtract(base.getX(), base.getY(), base.getZ()); final BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ(), relative.getYaw(), relative.getPitch()); - plot.settings.setPosition(blockloc); - DBFunc.setPosition(loc.getWorld(), plot, blockloc.toString()); + plot.setHome(blockloc); return MainUtil.sendMessage(plr, C.POSITION_SET); } if (args[0].equalsIgnoreCase("alias")) { @@ -171,7 +181,7 @@ public class Set extends SubCommand { MainUtil.sendMessage(plr, C.ALIAS_TOO_LONG); return false; } - for (final Plot p : PlotSquared.getInstance().getPlots(plr.getLocation().getWorld()).values()) { + for (final Plot p : PS.get().getPlots(plr.getLocation().getWorld()).values()) { if (p.settings.getAlias().equalsIgnoreCase(alias)) { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); return false; @@ -181,7 +191,7 @@ public class Set extends SubCommand { return false; } } - DBFunc.setAlias(loc.getWorld(), plot, alias); + plot.setAlias(alias); MainUtil.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); return true; } @@ -211,14 +221,14 @@ public class Set extends SubCommand { MainUtil.sendMessage(plr, getBiomeList(BlockManager.manager.getBiomeList())); return true; } - MainUtil.setBiome(plr.getLocation().getWorld(), plot, args[1].toUpperCase()); + plot.setBiome(args[1].toUpperCase()); MainUtil.sendMessage(plr, C.BIOME_SET_TO.s() + args[1].toLowerCase()); return true; } // Get components final String world = plr.getLocation().getWorld(); - final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); - final PlotManager manager = PlotSquared.getInstance().getPlotManager(world); + final PlotWorld plotworld = PS.get().getPlotWorld(world); + final PlotManager manager = PS.get().getPlotManager(world); final String[] components = manager.getPlotComponents(plotworld, plot.id); for (final String component : components) { if (component.equalsIgnoreCase(args[0])) { @@ -231,10 +241,6 @@ public class Set extends SubCommand { MainUtil.sendMessage(plr, C.NEED_BLOCK); return true; } -// if (!Configuration.BLOCKLIST.validateValue(args[1])) { -// MainUtil.sendMessage(plr, C.NOT_VALID_BLOCK, args[1]); -// return false; -// } String[] split = args[1].split(","); blocks = Configuration.BLOCKLIST.parseString(args[1]); for (int i = 0; i < blocks.length; i++) { @@ -308,7 +314,7 @@ public class Set extends SubCommand { } ArrayList newValues = new ArrayList(); newValues.addAll(Arrays.asList(values)); - newValues.addAll(Arrays.asList(manager.getPlotComponents(PlotSquared.getInstance().getPlotWorld(loc.getWorld()), plot.id))); + 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; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java index 59afdc198..ecf9a97f7 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java @@ -20,7 +20,10 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import java.util.ArrayList; +import java.util.UUID; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; @@ -32,9 +35,6 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import java.util.ArrayList; -import java.util.UUID; - public class SetOwner extends SubCommand { public SetOwner() { super("setowner", "plots.set.owner", "Set the plot owner", "setowner ", "so", CommandCategory.ACTIONS, true); @@ -93,14 +93,14 @@ public class SetOwner extends SubCommand { final String world = loc.getWorld(); for (final PlotId id : plots) { - final Plot current = PlotSquared.getInstance().getPlots(world).get(id); + final Plot current = PS.get().getPlots(world).get(id); final UUID uuid = getUUID(args[0]); if (uuid == null) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); return false; } current.owner = uuid; - PlotSquared.getInstance().updatePlot(current); + PS.get().updatePlot(current); DBFunc.setOwner(current, current.owner); } MainUtil.setSign(args[0], plot); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java index 0f691fbd5..67fde8b9b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java @@ -20,7 +20,9 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import org.apache.commons.lang.StringUtils; + +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; @@ -29,7 +31,6 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; -import org.apache.commons.lang.StringUtils; /** * @author Citymonstret @@ -55,7 +56,7 @@ public class TP extends SubCommand { world = args[1]; } } - if (!PlotSquared.getInstance().isPlotWorld(world)) { + if (!PS.get().isPlotWorld(world)) { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; } @@ -85,14 +86,14 @@ public class TP extends SubCommand { } final PlotPlayer player = UUIDHandler.getPlayer(a); if (player != null) { - final java.util.Set plotMainPlots = PlotSquared.getInstance().getPlots(world, player); + 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]; } return null; } - for (final Plot p : PlotSquared.getInstance().getPlots(world).values()) { + for (final Plot p : PS.get().getPlots(world).values()) { if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { return p; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Target.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Target.java index 34422d4d3..8b5839461 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Target.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Target.java @@ -20,7 +20,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; +import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.PlotId; @@ -35,7 +35,7 @@ public class Target extends SubCommand { @Override public boolean execute(final PlotPlayer plr, final String... args) { final Location ploc = plr.getLocation(); - if (!PlotSquared.getInstance().isPlotWorld(ploc.getWorld())) { + if (!PS.get().isPlotWorld(ploc.getWorld())) { MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); return false; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Template.java index ad283ec2e..bc5941506 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Template.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Template.java @@ -20,17 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlotSquared; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.ConfigurationNode; -import com.intellectualcrafters.plot.object.*; -import com.intellectualcrafters.plot.util.BlockManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.TaskManager; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -40,6 +29,21 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; +import com.intellectualcrafters.configuration.ConfigurationSection; +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.ConfigurationNode; +import com.intellectualcrafters.plot.object.FileBytes; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotWorld; +import com.intellectualcrafters.plot.object.SetupObject; +import com.intellectualcrafters.plot.util.BlockManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.SetupUtils; +import com.intellectualcrafters.plot.util.TaskManager; + public class Template extends SubCommand { public Template() { super("template", "plots.admin", "Create or use a world template", "template", "", CommandCategory.DEBUG, false); @@ -48,12 +52,12 @@ public class Template extends SubCommand { public static boolean extractAllFiles(String world, String template) { byte[] buffer = new byte[2048]; try { - File folder = new File(PlotSquared.getInstance().IMP.getDirectory() + File.separator + "templates"); + File folder = new File(PS.get().IMP.getDirectory() + File.separator + "templates"); if (!folder.exists()) { return false; } File input = new File(folder + File.separator + template + ".template"); - File output = PlotSquared.getInstance().IMP.getDirectory(); + File output = PS.get().IMP.getDirectory(); if (!output.exists()) { output.mkdirs(); } @@ -81,7 +85,7 @@ public class Template extends SubCommand { } public static byte[] getBytes(PlotWorld plotworld) { - ConfigurationSection section = PlotSquared.getInstance().config.getConfigurationSection("worlds." + plotworld.worldname); + ConfigurationSection section = PS.get().config.getConfigurationSection("worlds." + plotworld.worldname); YamlConfiguration config = new YamlConfiguration(); String generator = SetupUtils.manager.getGenerator(plotworld); if (generator != null) { @@ -94,7 +98,7 @@ public class Template extends SubCommand { } public static void zipAll(final String world, Set files) throws IOException { - File output = new File(PlotSquared.getInstance().IMP.getDirectory() + File.separator + "templates"); + File output = new File(PS.get().IMP.getDirectory() + File.separator + "templates"); output.mkdirs(); FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template"); ZipOutputStream zos = new ZipOutputStream(fos); @@ -131,7 +135,7 @@ public class Template extends SubCommand { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template import