Merge remote-tracking branch 'origin/master'

This commit is contained in:
sauilitired 2015-07-14 01:55:26 +02:00
commit ba622eba1f
180 changed files with 7475 additions and 2906 deletions

3
.gitignore vendored
View File

@ -100,4 +100,5 @@ hs_err_pid*
/target
/plotsquared/target
*.MF
PlotSquared/schematic.zip
PlotSquared/schematic.zip
*.bat

View File

@ -8,7 +8,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<artifactId>PlotSquared</artifactId>
<version>2.11.27</version>
<version>2.12.5</version>
<name>PlotSquared</name>
<packaging>jar</packaging>
<build>
@ -48,10 +48,6 @@
</plugins>
</build>
<repositories>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public/</url>
</repository>
<repository>
<id>empcraft-repo</id>
<url>http://empcraft.com/maven2</url>
@ -82,7 +78,7 @@
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8.3-R0.1-SNAPSHOT</version>
<version>1.8-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
@ -107,5 +103,10 @@
<version>1.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</project>

View File

@ -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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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<String, Object> defaults);
/**
* Sets the default values of the given paths as provided.
* <p>
* 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.
* <p>
* 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}.
* <p>
* 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.
* <p>
* 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}.
* <p>
* All setters through this method are chainable.
*
* @return Options for this configuration
*/
public ConfigurationOptions options();
}

View File

@ -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
* <p>
* 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
* <p>
* 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.
* <p>
* 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.
* <p>
* 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;
}
}

View File

@ -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.
* <p>
* 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.
* <p>
* 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<String> getKeys(boolean deep);
/**
* Gets a Map containing all keys and their values for this section.
* <p>
* 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.
* <p>
* 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<String, Object> getValues(boolean deep);
/**
* Checks if this {@link ConfigurationSection} contains the given path.
* <p>
* 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.
* <p>
* 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}
* <p>
* For any {@link Configuration} themselves, this will return an empty
* string.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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}
* <p>
* For any {@link Configuration} themselves, this will return its own
* object.
* <p>
* 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}.
* <p>
* For any {@link Configuration} themselves, this will return null.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* If value is null, the entry will be removed. Any existing entry will be
* replaced, regardless of what the new value is.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* If the path exists but is not a String, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a String and return appropriately.
*
* @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.
* <p>
* If the int does not exist but a default value has been specified, this
* will return the default value. If the int does not exist and no default
* value was specified, this will return 0.
*
* @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.
* <p>
* If the int does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
* @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.
* <p>
* If the path exists but is not a int, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a int and return appropriately.
*
* @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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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<String> getStringList(String path);
/**
* Gets the requested List of Integer by path.
* <p>
* 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.
* <p>
* 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<Integer> getIntegerList(String path);
/**
* Gets the requested List of Boolean by path.
* <p>
* 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.
* <p>
* 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<Boolean> getBooleanList(String path);
/**
* Gets the requested List of Double by path.
* <p>
* 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.
* <p>
* 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<Double> getDoubleList(String path);
/**
* Gets the requested List of Float by path.
* <p>
* 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.
* <p>
* 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<Float> getFloatList(String path);
/**
* Gets the requested List of Long by path.
* <p>
* 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.
* <p>
* 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<Long> getLongList(String path);
/**
* Gets the requested List of Byte by path.
* <p>
* 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.
* <p>
* 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<Byte> getByteList(String path);
/**
* Gets the requested List of Character by path.
* <p>
* 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.
* <p>
* 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<Character> getCharacterList(String path);
/**
* Gets the requested List of Short by path.
* <p>
* 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.
* <p>
* 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<Short> getShortList(String path);
/**
* Gets the requested List of Maps by path.
* <p>
* 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.
* <p>
* 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<Map<?, ?>> getMapList(String path);
/**
* Gets the requested ConfigurationSection by path.
* <p>
* 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.
* <p>
* 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()}.
* <p>
* 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.
* <p>
* 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.
* <p>
* If value is null, the value will be removed from the default
* Configuration source.
* <p>
* 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);
}

View File

@ -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);
}
}

View File

@ -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<String, Object> defaults) {
if (defaults == null) throw new NullPointerException("Defaults may not be null");
for (Map.Entry<String, Object> 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;
}
}

View File

@ -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;
}
}

View File

@ -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<String, Object> map = new LinkedHashMap<String, Object>();
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.
* <p>
* 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<String> getKeys(boolean deep) {
Set<String> result = new LinkedHashSet<String>();
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<String, Object> getValues(boolean deep) {
Map<String, Object> result = new LinkedHashMap<String, Object>();
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<String> getStringList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<String>(0);
}
List<String> result = new ArrayList<String>();
for (Object object : list) {
if ((object instanceof String) || (isPrimitiveWrapper(object))) {
result.add(String.valueOf(object));
}
}
return result;
}
public List<Integer> getIntegerList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Integer>(0);
}
List<Integer> result = new ArrayList<Integer>();
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<Boolean> getBooleanList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Boolean>(0);
}
List<Boolean> result = new ArrayList<Boolean>();
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<Double> getDoubleList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Double>(0);
}
List<Double> result = new ArrayList<Double>();
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<Float> getFloatList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Float>(0);
}
List<Float> result = new ArrayList<Float>();
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<Long> getLongList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Long>(0);
}
List<Long> result = new ArrayList<Long>();
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<Byte> getByteList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Byte>(0);
}
List<Byte> result = new ArrayList<Byte>();
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<Character> getCharacterList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Character>(0);
}
List<Character> result = new ArrayList<Character>();
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<Short> getShortList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Short>(0);
}
List<Short> result = new ArrayList<Short>();
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<Map<?, ?>> getMapList(String path) {
List<?> list = getList(path);
List<Map<?, ?>> result = new ArrayList<Map<?, ?>>();
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<String> output, ConfigurationSection section, boolean deep) {
if (section instanceof MemorySection) {
MemorySection sec = (MemorySection) section;
for (Map.Entry<String, Object> 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<String> keys = section.getKeys(deep);
for (String key : keys) {
output.add(createPath(section, key, this));
}
}
}
protected void mapChildrenValues(Map<String, Object> output, ConfigurationSection section, boolean deep) {
if (section instanceof MemorySection) {
MemorySection sec = (MemorySection) section;
for (Map.Entry<String, Object> 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<String, Object> values = section.getValues(deep);
for (Map.Entry<String, Object> 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}.
* <p>
* 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.
* <p>
* 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();
}
}

View File

@ -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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* If the file cannot be loaded for any reason, an exception will be
* thrown.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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;
}
}

View File

@ -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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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;
}
}

View File

@ -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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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;
}
}

View File

@ -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.
* <p>
* 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.
* <p>
* 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;
}
}

View File

@ -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<String, Object> typed = new LinkedHashMap<String, Object>(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);
}
}
}

View File

@ -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<String, Object> values = new LinkedHashMap<String, Object>();
values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass()));
values.putAll(serializable.serialize());
return super.representData(values);
}
}
}

View File

@ -0,0 +1,35 @@
package com.intellectualcrafters.configuration.serialization;
import java.util.Map;
/**
* Represents an object that may be serialized.
* <p>
* These objects MUST implement one of the following, in addition to the
* methods as defined by this interface:
* <ul>
* <li>A static method "deserialize" that accepts a single {@link Map}&lt;
* {@link String}, {@link Object}> and returns the class.</li>
* <li>A static method "valueOf" that accepts a single {@link Map}&lt;{@link
* String}, {@link Object}> and returns the class.</li>
* <li>A constructor that accepts a single {@link Map}&lt;{@link String},
* {@link Object}>.</li>
* </ul>
* 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.
* <p>
* 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<String, Object> serialize();
}

View File

@ -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<? extends ConfigurationSerializable> clazz;
private static Map<String, Class<? extends ConfigurationSerializable>> aliases = new HashMap<String, Class<? extends ConfigurationSerializable>>();
protected ConfigurationSerialization(Class<? extends ConfigurationSerializable> 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<? extends ConfigurationSerializable> getConstructor() {
try {
return clazz.getConstructor(Map.class);
} catch (NoSuchMethodException ex) {
return null;
} catch (SecurityException ex) {
return null;
}
}
protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, ?> 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<? extends ConfigurationSerializable> ctor, Map<String, ?> 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<String, ?> 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<? extends ConfigurationSerializable> 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.
* <p>
* The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.
* <p>
* If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.
*
* @param args Arguments for deserialization
* @param clazz Class to deserialize into
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(Map<String, ?> args, Class<? extends ConfigurationSerializable> clazz) {
return new ConfigurationSerialization(clazz).deserialize(args);
}
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
* <p>
* The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.
* <p>
* 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<String, ?> args) {
Class<? extends ConfigurationSerializable> 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<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate == null) {
registerClass(clazz, getAlias(clazz));
registerClass(clazz, clazz.getName());
}
}
/**
* Registers the given alias to the specified {@link
* ConfigurationSerializable} class
*
* @param clazz Class to register
* @param alias Alias to register as
* @see SerializableAs
*/
public static void registerClass(Class<? extends ConfigurationSerializable> clazz, String alias) {
aliases.put(alias, clazz);
}
/**
* Unregisters the specified alias to a {@link ConfigurationSerializable}
*
* @param alias Alias to unregister
*/
public static void unregisterClass(String alias) {
aliases.remove(alias);
}
/**
* Unregisters any aliases for the specified {@link
* ConfigurationSerializable} class
*
* @param clazz Class to unregister
*/
public static void unregisterClass(Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) {
;
}
}
/**
* Attempts to get a registered {@link ConfigurationSerializable} class by
* its alias
*
* @param alias Alias of the serializable
* @return Registered class, or null if not found
*/
public static Class<? extends ConfigurationSerializable> getClassByAlias(String alias) {
return aliases.get(alias);
}
/**
* Gets the correct alias for the given {@link ConfigurationSerializable}
* class
*
* @param clazz Class to get alias for
* @return Alias to use for the class
*/
public static String getAlias(Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate != null) {
if ((delegate.value() == null) || (delegate.value() == clazz)) {
delegate = null;
} else {
return getAlias(delegate.value());
}
}
if (delegate == null) {
SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
if ((alias != null) && (alias.value() != null)) {
return alias.value();
}
}
return clazz.getName();
}
}

View File

@ -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<? extends ConfigurationSerializable> value();
}

View File

@ -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.
* <p>
* This value will be stored in the configuration so that the configuration
* deserialization can determine what type it is.
* <p>
* 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.
* <p>
* 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();
}

View File

@ -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();
}
}

View File

@ -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<World> 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<String, Plugin> ln;
List<Plugin> 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<String, ?> 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<String> 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<String> unloadRecursively(String doNotLoad, Plugin plugin, Stack<String> 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<String> depend = p.getDescription().getDepend();
if (depend != null) {
for (String s : depend) {
if (s.equals(plugin.getName())) {
unloadRecursively(doNotLoad, p, pluginFiles);
}
}
}
List<String> softDepend = p.getDescription().getSoftDepend();
if (softDepend != null) {
for (String s : softDepend) {
if (s.equals(plugin.getName())) {
unloadRecursively(doNotLoad, p, pluginFiles);
}
}
}
}
if (unloadPlugin(plugin)) {
List<String> depend = plugin.getDescription().getDepend();
if (depend != null) {
for (String s : depend) {
Plugin p = pm.getPlugin(s);
if (p != null) {
unloadRecursively(doNotLoad, p, pluginFiles);
}
}
}
List<String> 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();

View File

@ -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);
}

View File

@ -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<String, PlotWorld> plotworlds = new HashMap<>();
private final HashMap<String, PlotManager> 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<String, HashMap<PlotId, Plot>> 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<PlotId, Plot> 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 = "<a href=\"resources/" + resource + "/download?version=";
String version = "<td class=\"version\">";
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<String, Object> 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<String, String> 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<String, Object> 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<String, Object> 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<String, Object> node : o.entrySet()) {
style.set(node.getKey(), node.getValue());
}
}

View File

@ -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<Plot> 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<Plot> 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<Plot> 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<Plot> plots = PlotSquared.getInstance().getPlots(world.getName()).values();
Collection<Plot> 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<String> worlds = PlotSquared.getInstance().getPlotWorlds();
Set<String> 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<Plot> 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));
}
/**

View File

@ -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 <player>", 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;
}

View File

@ -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;

View File

@ -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;

View File

@ -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);
}

View File

@ -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) {

View File

@ -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<Plot> plots = PlotSquared.getInstance().getPlots(plr);
Set<Plot> plots = PS.get().getPlots(plr);
if (plots.size() == 0) {
MainUtil.sendMessage(plr, C.NO_PLOTS);
return false;

View File

@ -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<Plot> 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;

View File

@ -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"),

View File

@ -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<Plot> plots = PlotSquared.getInstance().getPlots(worldname).values();
final Collection<Plot> 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<Plot> plots = PlotSquared.getInstance().getPlots(worldname).values();
final Collection<Plot> 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) {

View File

@ -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;
}

View File

@ -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);

View File

@ -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<Plot> plots = PlotSquared.getInstance().getPlots();
final java.util.Set<Plot> 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);
}

View File

@ -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"));

View File

@ -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<Plot> 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 {

View File

@ -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))) {

View File

@ -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 <flag>");
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag <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 <world>");
PS.log("&cInvalid syntax: /plot debugexec start-rgar <world>");
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<ChunkLoc> 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);

View File

@ -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<String, Flag> flags = plot.settings.flags;
Iterator<Entry<String, Flag>> 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!");

View File

@ -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..");

View File

@ -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);

View File

@ -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<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotSquared.getInstance().getPlots());
plots.addAll(PS.get().getPlots());
MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override

View File

@ -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<Plot> plots = new ArrayList<>(PlotSquared.getInstance().getPlots());
ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
database.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {

View File

@ -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"))) {

View File

@ -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 <player>", 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;
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;

View File

@ -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<Plot> plots = PlotSquared.getInstance().sortPlotsByWorld(PlotSquared.getInstance().getPlots(plr));
final ArrayList<Plot> plots = PS.get().sortPlotsByWorld(PS.get().getPlots(plr));
if (plots.size() == 1) {
MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(0));
return true;

View File

@ -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() {

View File

@ -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();

View File

@ -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<PlotId> 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;

View File

@ -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;

View File

@ -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;
}

View File

@ -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);
}
}

View File

@ -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<PlotId> ids = PlotSquared.getInstance().getPlots(worldname).keySet();
final Set<PlotId> 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<Plot> plots = PlotSquared.getInstance().getPlots(worldname).values();
final Collection<Plot> plots = PS.get().getPlots(worldname).values();
final Set<PlotId> 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<Plot> plots = PlotSquared.getInstance().getPlots(worldname).values();
final Collection<Plot> plots = PS.get().getPlots(worldname).values();
final Set<PlotId> 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<Plot> plots = PlotSquared.getInstance().getPlots(worldname, uuid);
final Set<Plot> plots = PS.get().getPlots(worldname, uuid);
final Set<PlotId> ids = new HashSet<>();
for (final Plot plot : plots) {
ids.add(plot.id);

View File

@ -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<Plot> plots = new ArrayList<>(PlotSquared.getInstance().getPlots());
ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
Collections.sort(plots, new Comparator<Plot>() {
@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<UUID, Integer> entry : p1.settings.ratings.entrySet()) {
v1 -= 11 - entry.getValue();
for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
v1 -= 11 - entry.getValue().getAverageRating();
}
}
if (p2.settings.ratings != null) {
for (Entry<UUID, Integer> entry : p2.settings.ratings.entrySet()) {
v2 -= 11 - entry.getValue();
for (Entry<UUID, Rating> 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;

View File

@ -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<ChunkLoc> 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;

View File

@ -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) {

View File

@ -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<UUID> i = plot.members.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
ArrayList<UUID> toRemove = new ArrayList<>();
HashSet<UUID> 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<UUID> i = plot.members.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
DBFunc.removeMember(plot.world, plot, uuid);
i.remove();
ArrayList<UUID> toRemove = new ArrayList<>();
HashSet<UUID> 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++;
}
}
}
}

View File

@ -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 <world>");
return false;
}
final HashMap<PlotId, Plot> plotmap = PlotSquared.getInstance().getPlots(args[1]);
final HashMap<PlotId, Plot> plotmap = PS.get().getPlots(args[1]);
if ((plotmap == null) || (plotmap.size() == 0)) {
MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall <world>");
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 <world> <id>");
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 <world> <id>");
return false;

View File

@ -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<String> newValues = new ArrayList<String>();
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<String> newValues = new ArrayList<String>();
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;
}

View File

@ -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 <player>", "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);

View File

@ -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<Plot> plotMainPlots = PlotSquared.getInstance().getPlots(world, player);
final java.util.Set<Plot> 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;
}

View File

@ -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;
}

View File

@ -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<FileBytes> 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 <world> <template>");
return false;
}
if (PlotSquared.getInstance().isPlotWorld(world)) {
if (PS.get().isPlotWorld(world)) {
MainUtil.sendMessage(plr, C.SETUP_WORLD_TAKEN, world);
return false;
}
@ -140,12 +144,12 @@ public class Template extends SubCommand {
MainUtil.sendMessage(plr, "&cInvalid template file: " + args[2] +".template");
return false;
}
File worldFile = new File(PlotSquared.getInstance().IMP.getDirectory() + File.separator + "templates" + File.separator + "tmp-data.yml");
File worldFile = new File(PS.get().IMP.getDirectory() + File.separator + "templates" + File.separator + "tmp-data.yml");
YamlConfiguration worldConfig = YamlConfiguration.loadConfiguration(worldFile);
PlotSquared.getInstance().config.set("worlds." + world, worldConfig.get(""));
PS.get().config.set("worlds." + world, worldConfig.get(""));
try {
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile);
PlotSquared.getInstance().config.load(PlotSquared.getInstance().configFile);
PS.get().config.save(PS.get().configFile);
PS.get().config.load(PS.get().configFile);
} catch (Exception e) {
e.printStackTrace();
}
@ -180,12 +184,12 @@ public class Template extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export <world>");
return false;
}
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world);
final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (!BlockManager.manager.isWorld(world) || (plotworld == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false;
}
final PlotManager manager = PlotSquared.getInstance().getPlotManager(world);
final PlotManager manager = PS.get().getPlotManager(world);
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {

View File

@ -20,14 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
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.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
@ -36,6 +28,18 @@ import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
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.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
public class Trim extends SubCommand {
public static boolean TASK = false;
public static ArrayList<Plot> expired = null;
@ -66,7 +70,7 @@ public class Trim extends SubCommand {
final ChunkLoc loc = new ChunkLoc(x, z);
empty.add(loc);
} catch (final Exception e) {
PlotSquared.log("INVALID MCA: " + name);
PS.log("INVALID MCA: " + name);
}
} else {
final Path path = Paths.get(file.getPath());
@ -83,7 +87,7 @@ public class Trim extends SubCommand {
final ChunkLoc loc = new ChunkLoc(x, z);
empty.add(loc);
} catch (final Exception e) {
PlotSquared.log("INVALID MCA: " + name);
PS.log("INVALID MCA: " + name);
}
}
} catch (final Exception e) {
@ -106,7 +110,7 @@ public class Trim extends SubCommand {
System.currentTimeMillis();
sendMessage("Collecting region data...");
final ArrayList<Plot> plots = new ArrayList<>();
plots.addAll(PlotSquared.getInstance().getPlots(world).values());
plots.addAll(PS.get().getPlots(world).values());
final HashSet<ChunkLoc> chunks = new HashSet<>(ChunkManager.manager.getChunkChunks(world));
sendMessage(" - MCA #: " + chunks.size());
sendMessage(" - CHUNKS: " + (chunks.size() * 1024) + " (max)");
@ -120,19 +124,19 @@ public class Trim extends SubCommand {
empty.addAll(chunks);
Trim.TASK = false;
TaskManager.runTaskAsync(whenDone);
PlotSquared.getInstance().TASK.cancelTask(Trim.TASK_ID);
PS.get().TASK.cancelTask(Trim.TASK_ID);
return;
}
final Plot plot = plots.get(0);
plots.remove(0);
final Location pos1 = MainUtil.getPlotBottomLoc(world, plot.id);
final Location pos2 = MainUtil.getPlotTopLoc(world, plot.id);
final Location pos3 = new Location(world, pos1.getX(), 64, pos2.getZ());
final Location pos4 = new Location(world, pos2.getX(), 64, pos1.getZ());
chunks.remove(ChunkManager.getChunkChunk(pos1));
chunks.remove(ChunkManager.getChunkChunk(pos2));
chunks.remove(ChunkManager.getChunkChunk(pos3));
chunks.remove(ChunkManager.getChunkChunk(pos4));
for (int x = pos1.getX(); x <= pos2.getX(); x += 512 ) {
for (int z = pos1.getZ(); z <= pos2.getZ(); z += 512 ) {
ChunkLoc chunk = ChunkManager.getChunkChunk(new Location(world, x, 0, z));
chunks.remove(chunk);
}
}
}
}
}, 20);
@ -145,7 +149,7 @@ public class Trim extends SubCommand {
}
public static void sendMessage(final String message) {
PlotSquared.log("&3PlotSquared -> World trim&8: &7" + message);
PS.log("&3PlotSquared -> World trim&8: &7" + message);
}
public PlotId getId(final String id) {
@ -187,7 +191,7 @@ public class Trim extends SubCommand {
return false;
}
final String world = args[1];
if (!BlockManager.manager.isWorld(world) || (PlotSquared.getInstance().getPlotWorld(world) == null)) {
if (!BlockManager.manager.isWorld(world) || (PS.get().getPlotWorld(world) == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_WORLD);
return false;
}

View File

@ -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 Trust extends SubCommand {
public Trust() {
super(Command.TRUST, "Allow a player to build in a plot", "trust <player>", CommandCategory.ACTIONS, true);
@ -67,34 +67,29 @@ public class Trust extends SubCommand {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false;
}
if (!plot.trusted.contains(uuid)) {
if (plot.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.ALREADY_OWNER);
return false;
}
if (plot.members.contains(uuid)) {
plot.members.remove(uuid);
DBFunc.removeMember(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.addTrusted(uuid);
DBFunc.setTrusted(loc.getWorld(), plot, uuid);
EventUtil.manager.callTrusted(plr, plot, uuid, true);
} else {
if (plot.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.ALREADY_OWNER);
return false;
}
if (plot.trusted.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.removeMember(uuid)) {
plot.addTrusted(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.addTrusted(uuid);
}
EventUtil.manager.callTrusted(plr, plot, uuid, true);
MainUtil.sendMessage(plr, C.TRUSTED_ADDED);
return true;
}

View File

@ -20,9 +20,8 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
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.database.DBFunc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -50,7 +49,7 @@ public class Unclaim 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 ((EconHandler.manager != null) && pWorld.USE_ECONOMY) {
final double c = pWorld.SELL_PRICE;
if (c > 0d) {
@ -58,12 +57,9 @@ public class Unclaim extends SubCommand {
sendMessage(plr, C.ADDED_BALANCE, c + "");
}
}
final boolean result = PlotSquared.getInstance().removePlot(loc.getWorld(), plot.id, true);
final boolean result = PS.get().removePlot(loc.getWorld(), plot.id, true);
if (result) {
final String worldname = plr.getLocation().getWorld();
PlotSquared.getInstance().getPlotManager(worldname).unclaimPlot(pWorld, plot);
DBFunc.delete(worldname, plot);
// TODO set wall block
plot.unclaim();
} else {
MainUtil.sendMessage(plr, "Plot removal has been denied.");
}

View File

@ -20,11 +20,10 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.Iterator;
import java.util.ArrayList;
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,33 +57,28 @@ public class Undeny extends SubCommand {
}
int count = 0;
if (args[0].equals("unknown")) {
Iterator<UUID> i = plot.denied.iterator();
i = plot.denied.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
ArrayList<UUID> toRemove = new ArrayList<>();
for (UUID uuid : plot.denied) {
if (UUIDHandler.getName(uuid) == null) {
DBFunc.removeDenied(plot.world, plot, uuid);
i.remove();
count++;
toRemove.add(uuid);
}
}
for (UUID uuid : toRemove) {
plot.removeDenied(uuid);
count++;
}
}
else if (args[0].equals("*")){
Iterator<UUID> i = plot.denied.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
DBFunc.removeDenied(plot.world, plot, uuid);
i.remove();
for (UUID uuid : new ArrayList<>(plot.denied)) {
plot.removeDenied(uuid);
count++;
}
}
else {
UUID uuid = UUIDHandler.getUUID(args[0]);
if (uuid != null) {
if (plot.denied.contains(uuid)) {
DBFunc.removeDenied(plot.world, plot, uuid);
plot.denied.remove(uuid);
count++;
if (plot.removeDenied(uuid)) {
count++;
}
}
}

View File

@ -20,11 +20,10 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.Iterator;
import java.util.ArrayList;
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,33 +57,28 @@ public class Untrust extends SubCommand {
}
int count = 0;
if (args[0].equals("unknown")) {
Iterator<UUID> i = plot.trusted.iterator();
i = plot.trusted.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
ArrayList<UUID> toRemove = new ArrayList<>();
for (UUID uuid : plot.trusted) {
if (UUIDHandler.getName(uuid) == null) {
DBFunc.removeTrusted(plot.world, plot, uuid);
i.remove();
count++;
toRemove.add(uuid);
}
}
for (UUID uuid : toRemove) {
plot.removeTrusted(uuid);
count++;
}
}
else if (args[0].equals("*")){
Iterator<UUID> i = plot.trusted.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
DBFunc.removeTrusted(plot.world, plot, uuid);
i.remove();
for (UUID uuid : new ArrayList<>(plot.trusted)) {
plot.removeTrusted(uuid);
count++;
}
}
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++;
}
}
}

View File

@ -0,0 +1,83 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// 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.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
import org.bukkit.Bukkit;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
public class Update extends SubCommand {
public static String downloads, version;
public Update() {
super("update", "plots.admin", "Update PlotSquared", "update", "updateplugin", CommandCategory.DEBUG, false);
}
@Override
public boolean execute(final PlotPlayer plr, final String... args) {
if (plr != null) {
MainUtil.sendMessage(plr, C.NOT_CONSOLE);
return false;
}
URL url;
if (args.length == 0) {
url = PS.get().update;
}
else if (args.length == 1) {
try {
url = new URL(args[0]);
} catch (MalformedURLException e) {
MainUtil.sendMessage(plr, "&cInvalid url: " + args[0]);
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot update [url]");
return false;
}
}
else {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot update");
return false;
}
if (url == null) {
MainUtil.sendMessage(plr, "&cNo update found!");
MainUtil.sendMessage(plr, "&cTo manually specify an update URL: /plot update <url>");
return false;
}
PS.get().update(url);
return true;
}
}

View File

@ -20,7 +20,11 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PlotSquared;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -28,10 +32,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.List;
import java.util.UUID;
public class Visit extends SubCommand {
public Visit() {
super("visit", "plots.visit", "Visit someones plot", "visit {player} [#]", "v", CommandCategory.TELEPORT, true);
@ -39,7 +39,7 @@ public class Visit extends SubCommand {
public List<Plot> getPlots(final UUID uuid) {
final List<Plot> plots = new ArrayList<>();
for (final Plot p : PlotSquared.getInstance().getPlots()) {
for (final Plot p : PS.get().getPlots()) {
if (p.hasOwner() && p.isOwner(uuid)) {
plots.add(p);
}
@ -56,10 +56,10 @@ public class Visit extends SubCommand {
UUID user = UUIDHandler.getUUID(args[0]);
if (user != null ) {
// do plots by username
plots.addAll(PlotSquared.getInstance().getPlots(user));
} else if (PlotSquared.getInstance().isPlotWorld(args[0])) {
plots.addAll(PS.get().getPlots(user));
} else if (PS.get().isPlotWorld(args[0])) {
// do plots by world
plots.addAll(PlotSquared.getInstance().getPlots(args[0]).values());
plots.addAll(PS.get().getPlots(args[0]).values());
}
else {
Plot plot = MainUtil.getPlotFromString(plr, args[0], true);

View File

@ -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.listeners.worldedit.WEManager;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -34,7 +34,7 @@ public class WE_Anywhere extends SubCommand {
@Override
public boolean execute(final PlotPlayer plr, final String... args) {
if (PlotSquared.getInstance().worldEdit == null) {
if (PS.get().worldEdit == null) {
MainUtil.sendMessage(plr, "&cWorldEdit is not enabled on this server");
return false;
}

View File

@ -20,7 +20,18 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PlotSquared;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
@ -28,18 +39,13 @@ import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.BukkitPlayer;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import com.intellectualcrafters.plot.util.bukkit.chat.FancyMessage;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author Citymonstret
@ -142,7 +148,7 @@ public class list extends SubCommand {
world = plr.getLocation().getWorld();
}
else {
Set<String> worlds = PlotSquared.getInstance().getPlotWorlds();
Set<String> worlds = PS.get().getPlotWorlds();
if (worlds.size() == 0) {
world = "world";
}
@ -161,7 +167,7 @@ public class list extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.mine");
return false;
}
plots = new ArrayList<>(PlotSquared.getInstance().getPlots(plr));
plots = new ArrayList<>(PS.get().getPlots(plr));
break;
}
case "shared": {
@ -173,7 +179,7 @@ public class list extends SubCommand {
return false;
}
plots = new ArrayList<Plot>();
for (Plot plot : PlotSquared.getInstance().getPlots()) {
for (Plot plot : PS.get().getPlots()) {
if (plot.trusted.contains(plr.getUUID()) || plot.members.contains(plr.getUUID())) {
plots.add(plot);
}
@ -189,7 +195,7 @@ public class list extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world." + world);
return false;
}
plots = new ArrayList<>(PlotSquared.getInstance().getPlots(world).values());
plots = new ArrayList<>(PS.get().getPlots(world).values());
break;
}
case "all": {
@ -197,7 +203,7 @@ public class list extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.all");
return false;
}
plots = new ArrayList<>(PlotSquared.getInstance().getPlots());
plots = new ArrayList<>(PS.get().getPlots());
break;
}
case "top": {
@ -205,22 +211,24 @@ public class list extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.top");
return false;
}
plots = new ArrayList<>(PlotSquared.getInstance().getPlots());
plots = new ArrayList<>(PS.get().getPlots());
Collections.sort(plots, new Comparator<Plot>() {
@Override
public int compare(Plot p1, Plot p2) {
double v1 = 0;
double v2 = 0;
if (p1.settings.ratings != null && p1.settings.ratings.size() > 0) {
for (Entry<UUID, Integer> entry : p1.settings.ratings.entrySet()) {
v1 += entry.getValue() * entry.getValue();
for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
double av = entry.getValue().getAverageRating();
v1 += av * av;
}
v1 /= p1.settings.ratings.size();
v2 += p2.settings.ratings.size();
}
if (p2.settings.ratings != null && p2.settings.ratings.size() > 0) {
for (Entry<UUID, Integer> entry : p2.settings.ratings.entrySet()) {
v2 += entry.getValue() * entry.getValue();
for (Entry<UUID, Rating> entry : p2.getRatings().entrySet()) {
double av = entry.getValue().getAverageRating();
v2 += av * av;
}
v2 /= p2.settings.ratings.size();
v2 += p2.settings.ratings.size();
@ -243,7 +251,7 @@ public class list extends SubCommand {
break;
}
plots = new ArrayList<>();
for (Plot plot : PlotSquared.getInstance().getPlots()) {
for (Plot plot : PS.get().getPlots()) {
final Flag price = FlagManager.getPlotFlag(plot, "price");
if (price != null) {
plots.add(plot);
@ -257,7 +265,7 @@ public class list extends SubCommand {
return false;
}
plots = new ArrayList<>();
for (Plot plot : PlotSquared.getInstance().getPlots()) {
for (Plot plot : PS.get().getPlots()) {
if (plot.owner == null) {
plots.add(plot);
}
@ -270,7 +278,7 @@ public class list extends SubCommand {
return false;
}
plots = new ArrayList<>();
for (Plot plot : PlotSquared.getInstance().getPlots()) {
for (Plot plot : PS.get().getPlots()) {
if (plot.owner == null) {
continue;
}
@ -281,7 +289,7 @@ public class list extends SubCommand {
break;
}
default: {
if (PlotSquared.getInstance().isPlotWorld(args[0])) {
if (PS.get().isPlotWorld(args[0])) {
if (!Permissions.hasPermission(plr, "plots.list.world")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world");
return false;
@ -290,7 +298,7 @@ public class list extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world." + args[0]);
return false;
}
plots = new ArrayList<>(PlotSquared.getInstance().getPlots(args[0]).values());
plots = new ArrayList<>(PS.get().getPlots(args[0]).values());
break;
}
UUID uuid = UUIDHandler.getUUID(args[0]);
@ -299,7 +307,7 @@ public class list extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.player");
return false;
}
plots = new ArrayList<>(PlotSquared.getInstance().getPlots(uuid));
plots = new ArrayList<>(PS.get().getPlots(uuid));
break;
}
}
@ -321,10 +329,10 @@ public class list extends SubCommand {
public void displayPlots(PlotPlayer player, List<Plot> plots, int pageSize, int page, String world, String[] args, boolean sort) {
if (sort) {
if (world != null) {
plots = PlotSquared.getInstance().sortPlots(plots, world);
plots = PS.get().sortPlots(plots, world);
}
else {
plots = PlotSquared.getInstance().sortPlots(plots);
plots = PS.get().sortPlots(plots);
}
}
if (page < 0) {

View File

@ -20,48 +20,23 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PlotSquared;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
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 plugin extends SubCommand {
public static String downloads, version;
public plugin() {
super("plugin", "plots.use", "Show plugin information", "plugin", "version", CommandCategory.INFO, false);
}
public static void setup() {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
try {
downloads = convertToNumericString(getInfo("https://intellectualsites.com/spigot_api.php?method=downloads&url=http://www.spigotmc.org/resources/plotsquared.1177/"), false);
} catch (final Exception e) {
downloads = "unknown";
}
}
});
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
public void run() {
try {
version = convertToNumericString(getInfo("https://intellectualsites.com/spigot_api.php?method=version&resource=1177"), true);
} catch (final Exception e) {
// Let's just ignore this, most likely error 500...
version = "unknown";
}
}
}, 200);
}
private static String convertToNumericString(final String str, final boolean dividers) {
final StringBuilder builder = new StringBuilder();
for (final char c : str.toCharArray()) {
@ -93,11 +68,10 @@ public class plugin extends SubCommand {
public void run() {
final ArrayList<String> strings = new ArrayList<String>() {
{
add(String.format("&c>> &6PlotSquared (Version: %s)", PlotSquared.getInstance().IMP.getVersion()));
add(String.format("&c>> &6Made by Citymonstret and Empire92"));
add(String.format("&c>> &6Download at &lhttp://www.spigotmc.org/resources/1177"));
add(String.format("&c>> &cNewest Version (Spigot): %s", version));
add(String.format("&c>> &cTotal Downloads (Spigot): %s", downloads));
add(String.format("&c>> &6PlotSquared (Version: %s)", PS.get().IMP.getVersion()));
add(String.format("&c>> &6Authors: Citymonstret and Empire92"));
add(String.format("&c>> &6Wiki: \n&chttps://github.com/IntellectualCrafters/PlotSquared/wiki"));
add(String.format("&c>> &6Newest Version:\n&c" + (PS.get().update == null ? PS.get().IMP.getVersion() : PS.get().update)));
}
};
for (final String s : strings) {

View File

@ -20,14 +20,18 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.config;
import java.io.File;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.ChatColor;
import com.intellectualsites.translation.TranslationFile;
import com.intellectualsites.translation.TranslationLanguage;
import com.intellectualsites.translation.TranslationManager;
import com.intellectualsites.translation.TranslationObject;
import com.intellectualsites.translation.YamlTranslationFile;
import com.intellectualsites.translation.bukkit.BukkitTranslation;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.util.StringMan;
/**
* Captions class.
@ -40,13 +44,18 @@ public enum C {
* Confirm
*/
FAILED_CONFIRM("$2You have no pending actions to confirm!", "Confirm"),
REQUIRES_CONFIRM("$2Are you sure you wish to execute: $1%s$2?\n$2This cannot be undone! If you are sure: $1/plot confirm", "Confirm"),
REQUIRES_CONFIRM("$2Are you sure you wish to execute: $1%s$2?&-$2This cannot be undone! If you are sure: $1/plot confirm", "Confirm"),
/*
* Move
*/
MOVE_SUCCESS("$4Successfully moved plot.", "Move"),
COPY_SUCCESS("$4Successfully copied plot.", "Move"),
REQUIRES_UNOWNED("$2The location specified is already occupied.", "Move"),
/*
* Web
*/
GENERATING_LINK("$1Processing plot...", "Web"),
GENERATING_LINK_FAILED("$2Failed to generate download link!", "Web"),
/*
* Compass
*/
@ -56,7 +65,7 @@ public enum C {
*/
CLUSTER_AVAILABLE_ARGS("$1The following sub commands are available: $4list$2, $4create$2, $4delete$2, $4resize$2, $4invite$2, $4kick$2, $4leave$2, $4members$2, $4info$2, $4tp$2, $4sethome", "Cluster"),
CLUSTER_LIST_HEADING("$2There are $1%s$2 clusters in this world", "Cluster"),
CLUSTER_LIST_ELEMENT("$2 - $1%s\n", "Cluster"),
CLUSTER_LIST_ELEMENT("$2 - $1%s&-", "Cluster"),
CLUSTER_INTERSECTION("$2The proposed area overlaps with $1%s$2 existing cluster/s", "Cluster"),
CLUSTER_ADDED("$4Successfully created the cluster.", "Cluster"),
CLUSTER_DELETED("$4Successfully deleted the cluster.", "Cluster"),
@ -73,7 +82,7 @@ public enum C {
CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"),
CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"),
CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"),
CLUSTER_INFO("$1Current cluster: $2%id%\n$1Name: $2%name%\n$1Owner: $2%owner%\n$1Size: $2%size%\n$1Rights: $2%rights%", "Cluster"),
CLUSTER_INFO("$1Current cluster: $2%id%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", "Cluster"),
CLUSTER_CURRENT_PLOTID("$1Current plot: $2%s", "Cluster"),
/*
* Border
@ -114,7 +123,7 @@ public enum C {
NOT_VALID_INBOX_INDEX("$2No comment at index %s", "Comment"),
INBOX_ITEM("$2 - $4%s", "Comment"),
COMMENT_SYNTAX("$2Use /plots comment [X;Z] <%s> <comment>", "Comment"),
INVALID_INBOX("$2That is not a valid inbox.\n$1Accepted values: %s", "Comment"),
INVALID_INBOX("$2That is not a valid inbox.&-$1Accepted values: %s", "Comment"),
NO_PERM_INBOX("$2You do not have permission for that inbox", "Comment"),
NO_PERM_INBOX_MODIFY("$2You do not have permission to modify that inbox", "Comment"),
NO_PLOT_INBOX("$2You must stand in or supply a plot argument", "Comment"),
@ -177,8 +186,8 @@ public enum C {
SETUP_VALID_ARG("$2Value $1%s $2set to %s", "Setup"),
SETUP_FINISHED("$3If you are using MULTIVERSE or MULTIWORLD the world should have just been created. Otherwise you will need to add the world manually through the bukkit.yml", "Setup"),
SETUP_WORLD_TAKEN("$2%s is already a registered plotworld", "Setup"),
SETUP_MISSING_WORLD("$2You need to specify a world name ($1/plot setup &l<world>$1 <generator>$2)\n$1Additional commands:\n$2 - $1/plot setup <value>\n$2 - $1/plot setup back\n$2 - $1/plot setup cancel", "Setup"),
SETUP_MISSING_GENERATOR("$2You need to specify a generator ($1/plot setup <world> &l<generator>&r$2)\n$1Additional commands:\n$2 - $1/plot setup <value>\n$2 - $1/plot setup back\n$2 - $1/plot setup cancel", "Setup"),
SETUP_MISSING_WORLD("$2You need to specify a world name ($1/plot setup &l<world>$1 <generator>$2)&-$1Additional commands:&-$2 - $1/plot setup <value>&-$2 - $1/plot setup back&-$2 - $1/plot setup cancel", "Setup"),
SETUP_MISSING_GENERATOR("$2You need to specify a generator ($1/plot setup <world> &l<generator>&r$2)&-$1Additional commands:&-$2 - $1/plot setup <value>&-$2 - $1/plot setup back&-$2 - $1/plot setup cancel", "Setup"),
SETUP_INVALID_GENERATOR("$2Invalid generator. Possible options: %s", "Setup"),
/*
* Schematic Stuff
@ -314,9 +323,9 @@ public enum C {
/*
* Debug
*/
DEUBG_HEADER("$1Debug Information\\n", "Debug"),
DEUBG_HEADER("$1Debug Information&-", "Debug"),
DEBUG_SECTION("$2>> $1&l%val%", "Debug"),
DEBUG_LINE("$2>> $1%var%$2:$1 %val%\\n", "Debug"),
DEBUG_LINE("$2>> $1%var%$2:$1 %val%&-", "Debug"),
/*
* Invalid
*/
@ -350,7 +359,7 @@ public enum C {
PLOT_UNOWNED("$2The current plot must have an owner to perform this action", "Info"),
PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"),
PLOT_INFO_HEADER("$3====== $1INFO $3======", false, "Info"),
PLOT_INFO("$1ID: $2%id%$1\n" + "$1Alias: $2%alias%$1\n" + "$1Owner: $2%owner%$1\n" + "$1Biome: $2%biome%$1\n" + "$1Can Build: $2%build%$1\n" + "$1Rating: $2%rating%\n" + "$1Trusted: $2%trusted%$1\n" + "$1Members: $2%members%$1\n" + "$1Denied: $2%denied%$1\n" + "$1Flags: $2%flags%", "Info"),
PLOT_INFO("$1ID: $2%id%$1&-" + "$1Alias: $2%alias%$1&-" + "$1Owner: $2%owner%$1&-" + "$1Biome: $2%biome%$1&-" + "$1Can Build: $2%build%$1&-" + "$1Rating: $2%rating%&-" + "$1Trusted: $2%trusted%$1&-" + "$1Members: $2%members%$1&-" + "$1Denied: $2%denied%$1&-" + "$1Flags: $2%flags%", "Info"),
PLOT_INFO_TRUSTED("$1Trusted:$2 %trusted%", "Info"),
PLOT_INFO_MEMBERS("$1Members:$2 %members%", "Info"),
PLOT_INFO_DENIED("$1Denied:$2 %denied%", "Info"),
@ -468,7 +477,7 @@ public enum C {
HELP_CATEGORY("$1Category: $2%category%$2,$1 Page: $2%current%$3/$2%max%$2,$1 Displaying: $2%dis%$3/$2%total%", "Help"),
HELP_INFO("$3====== $1Choose a Category $3======", false, "Help"),
HELP_INFO_ITEM("$1/plots help %category% $3- $2%category_desc%", "Help"),
HELP_ITEM("$1%usage% [%alias%]\n $3- $2%desc%\n", "Help"),
HELP_ITEM("$1%usage% [%alias%]&- $3- $2%desc%&-", "Help"),
/*
* Direction
*/
@ -478,32 +487,13 @@ public enum C {
*/
CUSTOM_STRING("-", "-");
/**
* Special Language
*
* @see com.intellectualsites.translation.TranslationLanguage
* Translated
*/
protected final static TranslationLanguage lang = new TranslationLanguage("PlotSquared", "this", "use");
public static String COLOR_1 = "&6", COLOR_2 = "&7", COLOR_3 = "&8", COLOR_4 = "&3";
/**
* The TranslationManager
*
* @see com.intellectualsites.translation.TranslationManager
*/
private static TranslationManager manager;
/**
* The default file
*
* @see com.intellectualsites.translation.TranslationFile
*/
private static TranslationFile defaultFile;
private String s;
/**
* Default
*/
private String d;
/**
* Translated
*/
private String s;
/**
* What locale category should this translation fall under
*/
@ -545,41 +535,97 @@ public enum C {
C(final String d, String cat) {
this(d, true, cat.toLowerCase());
}
public static void setupTranslations() {
manager = new TranslationManager();
defaultFile = new YamlTranslationFile(BukkitTranslation.getParent(), lang, "PlotSquared", manager, true).read();
// register everything in this class
for (final C c : values()) {
manager.addTranslationObject(new TranslationObject(c.toString(), c.d, "", ""));
public static String format(C c, Object... args) {
String m = c.s;
for (int i = args.length - 1 ; i >= 0; i--) {
if (args[i] == null) {
continue;
}
m = m.replaceAll("%s" + i, args[i].toString());
}
if (args.length > 0) {
m = m.replaceAll("%s", args[0].toString());
}
return m;
}
public static void saveTranslations() {
public static void load(File file) {
try {
manager.saveAll(defaultFile).saveFile(defaultFile);
} catch (final Exception e) {
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
Set<String> keys = yml.getKeys(true);
EnumSet<C> all = EnumSet.allOf(C.class);
HashSet<String> allNames = new HashSet<>();
HashSet<String> allCats = new HashSet<>();
HashSet<String> toRemove = new HashSet<>();
for (C c: all) {
allNames.add(c.name());
allCats.add(c.cat.toLowerCase());
}
HashSet<C> captions = new HashSet<>();
boolean changed = false;
for (String key : keys) {
if (!yml.isString(key)) {
if (!allCats.contains(key)) {
toRemove.add(key);
}
continue;
}
String[] split = key.split("\\.");
String node = split[split.length - 1].toUpperCase();
C caption = allNames.contains(node) ? valueOf(node) : null;
if (caption != null) {
String value = yml.getString(key);
if (!split[0].equalsIgnoreCase(caption.cat)) {
changed = true;
yml.set(key, null);
yml.set(caption.cat + "." + caption.name().toLowerCase(), value);
}
captions.add(caption);
caption.s = value;
}
else {
toRemove.add(key);
}
}
for (String remove : toRemove) {
changed = true;
yml.set(remove, null);
}
ConfigurationSection config = PS.get().style.getConfigurationSection("color");
Set<String> styles = config.getKeys(false);
HashMap<String, String> replacements = new HashMap<>();
for (String style : styles) {
replacements.put("$" + style, "\u00a7" + config.getString(style));
}
for (char letter : "1234567890abcdefklmnor".toCharArray()) {
replacements.put("&" + letter, "\u00a7" + letter);
}
replacements.put("\\\\n", "\n");
replacements.put("\\n", "\n");
replacements.put("&-", "\n");
for (C caption : all) {
if (!captions.contains(caption)) {
changed = true;
yml.set(caption.cat + "." + caption.name().toLowerCase(), caption.d);
}
caption.s = StringMan.replaceFromMap(caption.s, replacements);
}
if (changed) {
yml.save(file);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get the default string
*
* @return default
*/
public String d() {
return this.d;
}
/**
* Get translated if exists
*
* @return translated if exists else default
*/
public String s() {
final String s = manager.getTranslated(toString(), lang).getTranslated().replaceAll("&-", "\n").replaceAll("\\n", "\n");
return s.replace("$1", COLOR_1.toString()).replace("$2", COLOR_2.toString()).replace("$3", COLOR_3.toString()).replace("$4", COLOR_4.toString());
return this.s;
}
public boolean usePrefix() {
@ -598,8 +644,4 @@ public enum C {
public String getCat() {
return cat;
}
public void setCat(String cat) {
this.cat = cat;
}
}

View File

@ -21,7 +21,6 @@
package com.intellectualcrafters.plot.config;
import java.util.ArrayList;
import java.util.List;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.BlockManager;
@ -34,6 +33,7 @@ import com.intellectualcrafters.plot.util.StringComparison;
*/
@SuppressWarnings("unused")
public class Configuration {
public static final SettingValue<String> STRING = new SettingValue<String>("STRING") {
@Override
public boolean validateValue(final String string) {

View File

@ -38,6 +38,13 @@ public class Settings {
public static boolean PERMISSION_CACHING = false;
public static boolean CACHE_RATINGS = true;
public static boolean UUID_FROM_DISK = false;
/**
* Web
*/
public static String WEB_URL = "http://empcraft.com/plots/";
public static String WEB_IP = "your.ip.here";
/**
* Ratings
*/

View File

@ -84,7 +84,7 @@ public interface AbstractDB {
*
* @param plot Plot that should be deleted
*/
public void delete(final String world, final Plot plot);
public void delete(final Plot plot);
public void delete(final PlotCluster cluster);
@ -133,7 +133,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param merged boolean[]
*/
public void setMerged(final String world, final Plot plot, final boolean[] merged);
public void setMerged(final Plot plot, final boolean[] merged);
/**
* Swap the settings, helpers etc. of two plots
@ -149,7 +149,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param flags flags to set (flag[])
*/
public void setFlags(final String world, final Plot plot, final Collection<Flag> flags);
public void setFlags(final Plot plot, final Collection<Flag> flags);
/**
* Set cluster flags
@ -170,7 +170,7 @@ public interface AbstractDB {
* @param plot Plot for which the alias should be set
* @param alias Plot Alias
*/
public void setAlias(final String world, final Plot plot, final String alias);
public void setAlias(final Plot plot, final String alias);
/**
* Purgle a plot
@ -193,7 +193,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param position Plot Home Position
*/
public void setPosition(final String world, final Plot plot, final String position);
public void setPosition(final Plot plot, final String position);
/**
*
@ -220,7 +220,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param uuid Player that should be removed
*/
public void removeTrusted(final String world, final Plot plot, final UUID uuid);
public void removeTrusted(final Plot plot, final UUID uuid);
/**
* @param cluster PlotCluster Object
@ -232,7 +232,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param uuid Player that should be removed
*/
public void removeMember(final String world, final Plot plot, final UUID uuid);
public void removeMember(final Plot plot, final UUID uuid);
/**
*
@ -245,7 +245,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param uuid Player that should be removed
*/
public void setTrusted(final String world, final Plot plot, final UUID uuid);
public void setTrusted(final Plot plot, final UUID uuid);
/**
* @param cluster PlotCluster Object
@ -257,7 +257,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param uuid Player that should be added
*/
public void setMember(final String world, final Plot plot, final UUID uuid);
public void setMember(final Plot plot, final UUID uuid);
/**
*
@ -265,19 +265,19 @@ public interface AbstractDB {
* @param cluster
* @param uuid
*/
public void setInvited(final String world, final PlotCluster cluster, final UUID uuid);
public void setInvited(final PlotCluster cluster, final UUID uuid);
/**
* @param plot Plot Object
* @param uuid Player uuid
*/
public void removeDenied(final String world, final Plot plot, final UUID uuid);
public void removeDenied(final Plot plot, final UUID uuid);
/**
* @param plot Plot Object
* @param uuid Player uuid that should be added
*/
public void setDenied(final String world, final Plot plot, final UUID uuid);
public void setDenied(final Plot plot, final UUID uuid);
/**
* Get Plots ratings
@ -303,7 +303,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param comment Comment to remove
*/
public void removeComment(final String world, final Plot plot, final PlotComment comment);
public void removeComment(final Plot plot, final PlotComment comment);
/**
* Clear an inbox
@ -319,7 +319,7 @@ public interface AbstractDB {
* @param plot Plot Object
* @param comment Comment to add
*/
public void setComment(final String world, final Plot plot, final PlotComment comment);
public void setComment(final Plot plot, final PlotComment comment);
/**
* Get Plot Comments
@ -330,7 +330,7 @@ public interface AbstractDB {
*
* @return Plot Comments within the specified tier
*/
public void getComments(final String world, final Plot plot, final String inbox, RunnableVal whenDone);
public void getComments(final Plot plot, final String inbox, RunnableVal whenDone);
public void createPlotAndSettings(Plot plot);

View File

@ -56,6 +56,9 @@ public class DBFunc {
public static AbstractDB dbManager;
public static void movePlot(final Plot originalPlot, final Plot newPlot) {
if (originalPlot.temp || newPlot.temp) {
return;
}
dbManager.movePlot(originalPlot, newPlot);
}
/**
@ -87,6 +90,9 @@ public class DBFunc {
* @param uuid New Owner
*/
public static void setOwner(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.setOwner(plot, uuid);
}
@ -105,6 +111,9 @@ public class DBFunc {
* @param plot Plot to create
*/
public static void createPlot(final Plot plot) {
if (plot.temp) {
return;
}
dbManager.createPlot(plot);
}
@ -114,6 +123,9 @@ public class DBFunc {
* @param plot Plot to create
*/
public static void createPlotAndSettings(final Plot plot) {
if (plot.temp) {
return;
}
dbManager.createPlotAndSettings(plot);
}
@ -131,8 +143,11 @@ public class DBFunc {
*
* @param plot Plot to delete
*/
public static void delete(final String world, final Plot plot) {
dbManager.delete(world, plot);
public static void delete(final Plot plot) {
if (plot.temp) {
return;
}
dbManager.delete(plot);
}
public static void delete(final PlotCluster toDelete) {
@ -146,6 +161,9 @@ public class DBFunc {
* @param plot Plot Object
*/
public static void createPlotSettings(final int id, final Plot plot) {
if (plot.temp) {
return;
}
dbManager.createPlotSettings(id, plot);
}
@ -158,7 +176,7 @@ public class DBFunc {
* @return ID
*/
/*
* public static int getId(String world, PlotId id2) { Statement stmt =
* public static int getId(String plotId id2) { Statement stmt =
* null; try { stmt = connection.createStatement(); ResultSet r =
* stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x
* + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world +
@ -178,12 +196,18 @@ public class DBFunc {
return dbManager.getPlots();
}
public static void setMerged(final String world, final Plot plot, final boolean[] merged) {
dbManager.setMerged(world, plot, merged);
public static void setMerged(final Plot plot, final boolean[] merged) {
if (plot.temp) {
return;
}
dbManager.setMerged(plot, merged);
}
public static void setFlags(final String world, final Plot plot, final Collection<Flag> flags) {
dbManager.setFlags(world, plot, flags);
public static void setFlags(final Plot plot, final Collection<Flag> flags) {
if (plot.temp) {
return;
}
dbManager.setFlags(plot, flags);
}
public static void setFlags(final PlotCluster cluster, final Collection<Flag> flags) {
@ -194,8 +218,11 @@ public class DBFunc {
* @param plot
* @param alias
*/
public static void setAlias(final String world, final Plot plot, final String alias) {
dbManager.setAlias(world, plot, alias);
public static void setAlias(final Plot plot, final String alias) {
if (plot.temp) {
return;
}
dbManager.setAlias(plot, alias);
}
public static void purgeIds(final String world, final Set<Integer> uniqueIds) {
@ -210,8 +237,11 @@ public class DBFunc {
* @param plot
* @param position
*/
public static void setPosition(final String world, final Plot plot, final String position) {
dbManager.setPosition(world, plot, position);
public static void setPosition(final Plot plot, final String position) {
if (plot.temp) {
return;
}
dbManager.setPosition(plot, position);
}
/**
@ -227,11 +257,17 @@ public class DBFunc {
* @param plot
* @param comment
*/
public static void removeComment(final String world, final Plot plot, final PlotComment comment) {
dbManager.removeComment(world, plot, comment);
public static void removeComment(final Plot plot, final PlotComment comment) {
if (plot != null && plot.temp) {
return;
}
dbManager.removeComment(plot, comment);
}
public static void clearInbox(final Plot plot, final String inbox) {
if (plot != null && plot.temp) {
return;
}
dbManager.clearInbox(plot, inbox);
}
@ -239,23 +275,32 @@ public class DBFunc {
* @param plot
* @param comment
*/
public static void setComment(final String world, final Plot plot, final PlotComment comment) {
dbManager.setComment(world, plot, comment);
public static void setComment(final Plot plot, final PlotComment comment) {
if (plot != null && plot.temp) {
return;
}
dbManager.setComment(plot, comment);
}
/**
* @param plot
*/
public static void getComments(final String world, final Plot plot, final String inbox, RunnableVal whenDone) {
dbManager.getComments(world, plot, inbox, whenDone);
public static void getComments(final Plot plot, final String inbox, RunnableVal whenDone) {
if (plot != null && plot.temp) {
return;
}
dbManager.getComments(plot, inbox, whenDone);
}
/**
* @param plot
* @param uuid
*/
public static void removeTrusted(final String world, final Plot plot, final UUID uuid) {
dbManager.removeTrusted(world, plot, uuid);
public static void removeTrusted(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.removeTrusted(plot, uuid);
}
/**
@ -286,8 +331,11 @@ public class DBFunc {
* @param plot
* @param uuid
*/
public static void removeMember(final String world, final Plot plot, final UUID uuid) {
dbManager.removeMember(world, plot, uuid);
public static void removeMember(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.removeMember(plot, uuid);
}
/**
@ -304,8 +352,11 @@ public class DBFunc {
* @param plot
* @param uuid
*/
public static void setTrusted(final String world, final Plot plot, final UUID uuid) {
dbManager.setTrusted(world, plot, uuid);
public static void setTrusted(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.setTrusted(plot, uuid);
}
public static void setHelper(final PlotCluster cluster, final UUID uuid) {
@ -317,12 +368,15 @@ public class DBFunc {
* @param plot
* @param uuid
*/
public static void setMember(final String world, final Plot plot, final UUID uuid) {
dbManager.setMember(world, plot, uuid);
public static void setMember(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.setMember(plot, uuid);
}
public static void setInvited(final String world, final PlotCluster cluster, final UUID uuid) {
dbManager.setInvited(world, cluster, uuid);
dbManager.setInvited(cluster, uuid);
}
/**
@ -330,8 +384,11 @@ public class DBFunc {
* @param plot
* @param uuid
*/
public static void removeDenied(final String world, final Plot plot, final UUID uuid) {
dbManager.removeDenied(world, plot, uuid);
public static void removeDenied(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.removeDenied(plot, uuid);
}
/**
@ -339,15 +396,24 @@ public class DBFunc {
* @param plot
* @param uuid
*/
public static void setDenied(final String world, final Plot plot, final UUID uuid) {
dbManager.setDenied(world, plot, uuid);
public static void setDenied(final Plot plot, final UUID uuid) {
if (plot.temp) {
return;
}
dbManager.setDenied(plot, uuid);
}
public static HashMap<UUID, Integer> getRatings(final Plot plot) {
if (plot.temp) {
return new HashMap<>();
}
return dbManager.getRatings(plot);
}
public static void setRating(Plot plot, UUID rater, int value) {
if (plot.temp) {
return;
}
dbManager.setRating(plot, rater, value);
}

View File

@ -24,8 +24,6 @@ import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.intellectualcrafters.plot.PlotSquared;
/**
* Abstract Database class, serves as a base for any connection method (MySQL, SQLite, etc.)
*
@ -33,19 +31,6 @@ import com.intellectualcrafters.plot.PlotSquared;
* @author tips48
*/
public abstract class Database {
/**
* Plugin instance, use for plugin.getDataFolder()
*/
protected final PlotSquared plotsquared;
/**
* Creates a new Database
*
* @param plotsquared Plugin instance
*/
protected Database(final PlotSquared plotsquared) {
this.plotsquared = plotsquared;
}
public abstract Connection forceConnection() throws SQLException, ClassNotFoundException ;

View File

@ -26,8 +26,6 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.intellectualcrafters.plot.PlotSquared;
/**
* Connects to and uses a MySQL database
*
@ -51,8 +49,7 @@ public class MySQL extends Database {
* @param username Username
* @param password Password
*/
public MySQL(final PlotSquared plotsquared, final String hostname, final String port, final String database, final String username, final String password) {
super(plotsquared);
public MySQL(final String hostname, final String port, final String database, final String username, final String password) {
this.hostname = hostname;
this.port = port;
this.database = database;

View File

@ -20,11 +20,15 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.database;
import com.intellectualcrafters.plot.PlotSquared;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.intellectualcrafters.plot.PS;
/**
* Connects to and uses a SQLite database
@ -41,8 +45,7 @@ public class SQLite extends Database {
*
* @param dbLocation Location of the Database (Must end in .db)
*/
public SQLite(final PlotSquared plotsquared, final String dbLocation) {
super(plotsquared);
public SQLite(final String dbLocation) {
this.dbLocation = dbLocation;
}
@ -51,15 +54,15 @@ public class SQLite extends Database {
if (checkConnection()) {
return this.connection;
}
if (!PlotSquared.getInstance().IMP.getDirectory().exists()) {
PlotSquared.getInstance().IMP.getDirectory().mkdirs();
if (!PS.get().IMP.getDirectory().exists()) {
PS.get().IMP.getDirectory().mkdirs();
}
final File file = new File(this.dbLocation);
if (!(file.exists())) {
try {
file.createNewFile();
} catch (final IOException e) {
PlotSquared.log("&cUnable to create database!");
PS.log("&cUnable to create database!");
}
}
Class.forName("org.sqlite.JDBC");

View File

@ -4,8 +4,11 @@ import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
@ -13,4 +16,76 @@ public abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException;
public abstract boolean accepts(String version);
public String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
}
return world;
}
public Location getPlotTopLocAbs(int path, int plot, final PlotId plotid) {
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 256, z);
}
public Location getPlotBottomLocAbs(int path, int plot, final PlotId plotid) {
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 1, z);
}
public void setMerged(HashMap<String, HashMap<PlotId, boolean[]>> merges, String world, PlotId id, int direction) {
HashMap<PlotId, boolean[]> plots = merges.get(world);
PlotId id2;
switch (direction) {
case 0: {
id2 = new PlotId(id.x, id.y);
break;
}
case 1: {
id2 = new PlotId(id.x, id.y);
break;
}
case 2: {
id2 = new PlotId(id.x, id.y);
break;
}
case 3: {
id2 = new PlotId(id.x, id.y);
break;
}
default: {
return;
}
}
boolean[] merge1;
boolean[] merge2;
if (plots.containsKey(id)) {
merge1 = plots.get(id);
}
else {
merge1 = new boolean[]{false, false, false, false};
}
if (plots.containsKey(id2)) {
merge2 = plots.get(id2);
}
else {
merge2 = new boolean[]{false, false, false, false};
}
merge1[direction] = true;
merge2[(direction + 2) % 4] = true;
plots.put(id, merge1);
plots.put(id2, merge1);
}
}

View File

@ -1,6 +1,21 @@
package com.intellectualcrafters.plot.database.plotme;
import com.intellectualcrafters.plot.PlotSquared;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Location;
@ -9,30 +24,11 @@ import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin;
public static String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
}
return world;
}
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
@ -44,57 +40,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
return DriverManager.getConnection(con, user, password);
// return new MySQL(plotsquared, hostname, port, database, username, password)
} else {
return new SQLite(PlotSquared.getInstance(), dataFolder + File.separator + "plots.db").openConnection();
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
}
catch (SQLException | ClassNotFoundException e) {}
return null;
}
public void setMerged(HashMap<String, HashMap<PlotId, boolean[]>> merges, String world, PlotId id, int direction) {
HashMap<PlotId, boolean[]> plots = merges.get(world);
PlotId id2;
switch (direction) {
case 0: {
id2 = new PlotId(id.x, id.y);
break;
}
case 1: {
id2 = new PlotId(id.x, id.y);
break;
}
case 2: {
id2 = new PlotId(id.x, id.y);
break;
}
case 3: {
id2 = new PlotId(id.x, id.y);
break;
}
default: {
return;
}
}
boolean[] merge1;
boolean[] merge2;
if (plots.containsKey(id)) {
merge1 = plots.get(id);
}
else {
merge1 = new boolean[]{false, false, false, false};
}
if (plots.containsKey(id2)) {
merge2 = plots.get(id2);
}
else {
merge2 = new boolean[]{false, false, false, false};
}
merge1[direction] = true;
merge2[(direction + 2) % 4] = true;
plots.put(id, merge1);
plots.put(id2, merge1);
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
ResultSet r;
@ -106,21 +58,18 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Plots`");
r = stmt.executeQuery();
boolean checkUUID = DBFunc.hasColumn(r, "ownerid");
boolean merge = !plugin.equals("plotme");
boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) {
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world)) {
int plot = PlotSquared.getInstance().config.getInt("worlds." + world + ".plot.size");
int path = PlotSquared.getInstance().config.getInt("worlds." + world + ".road.width");
if (plot == 0 && path == 0) {
}
plotWidth.put(world, plot);
roadWidth.put(world, path);
plots.put(world, new HashMap<PlotId, Plot>());
if (merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId,boolean[]>());
}
}
@ -175,7 +124,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
else {
UUIDHandler.add(new StringWrapper(name), owner);
}
final Plot plot = new Plot(id, owner, new ArrayList<UUID>(), new ArrayList<UUID>(), world);
final Plot plot = new Plot(world, id, owner);
plots.get(world).put(id, plot);
}
@ -245,21 +194,12 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
catch (Exception e) {}
return plots;
}
public Location getPlotTopLocAbs(int path, int plot, final PlotId plotid) {
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 256, z);
@Override
public boolean accepts(String version) {
if (version == null) {
return true;
}
return PS.get().canUpdate(version, "0.17.0");
}
public Location getPlotBottomLocAbs(int path, int plot, final PlotId plotid) {
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 1, z);
}
}

View File

@ -20,19 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.database.plotme;
import com.intellectualcrafters.plot.PlotSquared;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.TaskManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
@ -47,6 +34,20 @@ import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.TaskManager;
/**
* Created 2014-08-17 for PlotSquared
*
@ -75,7 +76,7 @@ public class LikePlotMeConverter {
}
private void sendMessage(final String message) {
PlotSquared.log("&3PlotMe&8->&3PlotSquared&8: &7" + message);
PS.log("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
public String getPlotMePath() {
@ -118,11 +119,18 @@ public class LikePlotMeConverter {
try {
String dataFolder = getPlotMePath();
FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) {
return false;
}
String version = plotConfig.getString("Version");
if (version == null) version = plotConfig.getString("version");
if (!connector.accepts(version)) {
return false;
}
PS.log("&3Using connector: " + connector.getClass().getCanonicalName());
Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
if (connection == null) {
@ -142,33 +150,35 @@ public class LikePlotMeConverter {
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world);
try {
String actualWorldName = getWorld(world);
final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.width", pathwidth);
final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.size", plotsize);
final String wallblock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".wall.block", wallblock);
final String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.floor", Arrays.asList(floor));
final String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.filling", Arrays.asList(filling));
final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.block", road);
Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
if (height == null) {
height = 64;
if (!Settings.CONVERT_PLOTME) {
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world);
try {
String actualWorldName = getWorld(world);
final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PS.get().config.set("worlds." + actualWorldName + ".road.width", pathwidth);
final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotsize);
final String wallblock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallblock);
final String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.floor", Arrays.asList(floor));
final String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.filling", Arrays.asList(filling));
final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().config.set("worlds." + actualWorldName + ".road.block", road);
Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
if (height == null) {
height = 64;
}
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.save(PS.get().configFile);
} catch (final Exception e) {
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
}
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.height", height);
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile);
} catch (final Exception e) {
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
}
}
@ -194,32 +204,32 @@ public class LikePlotMeConverter {
if (pathwidth == null) {
pathwidth = 7;
}
PlotSquared.getInstance().config.set("worlds." + world + ".road.width", pathwidth);
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if (plotsize == null) {
plotsize = 32;
}
PlotSquared.getInstance().config.set("worlds." + world + ".plot.size", plotsize);
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); //
if (wallblock == null) {
wallblock = "44";
}
PlotSquared.getInstance().config.set("worlds." + world + ".wall.block", wallblock);
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); //
if (floor == null) {
floor = "2";
}
PlotSquared.getInstance().config.set("worlds." + world + ".plot.floor", Arrays.asList(floor));
PS.get().config.set("worlds." + world + ".plot.floor", Arrays.asList(floor));
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); //
if (filling == null) {
filling = "3";
}
PlotSquared.getInstance().config.set("worlds." + world + ".plot.filling", Arrays.asList(filling));
PS.get().config.set("worlds." + world + ".plot.filling", Arrays.asList(filling));
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock");
if (road == null) {
road = "5";
}
PlotSquared.getInstance().config.set("worlds." + world + ".road.block", road);
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if ((height == null) || (height == 0)) {
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
@ -227,10 +237,10 @@ public class LikePlotMeConverter {
height = 64;
}
}
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.height", height);
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.height", height);
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".wall.height", height);
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile);
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile);
}
} catch (final Exception e) {
}
@ -238,14 +248,14 @@ public class LikePlotMeConverter {
for (final String world : plots.keySet()) {
int duplicate = 0;
for (final Plot plot : plots.get(world).values()) {
if (!PlotSquared.getInstance().getPlots(world).containsKey(plot.id)) {
if (!PS.get().getPlots(world).containsKey(plot.id)) {
createdPlots.add(plot);
} else {
duplicate++;
}
}
if (duplicate > 0) {
PlotSquared.log("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
PS.log("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
}
}
sendMessage("Creating plot DB");
@ -254,16 +264,16 @@ public class LikePlotMeConverter {
@Override
public void run() {
sendMessage("&aDatabase conversion is now complete!");
PlotSquared.log("&c - Stop the server");
PlotSquared.log("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PlotSquared.log("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PlotSquared.log("&c - Start the server");
PlotSquared.getInstance().setAllPlotsRaw(DBFunc.getPlots());
PS.log("&c - Stop the server");
PS.log("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.log("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.log("&c - Start the server");
PS.get().setAllPlotsRaw(DBFunc.getPlots());
}
});
sendMessage("Saving configuration...");
try {
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile);
PS.get().config.save(PS.get().configFile);
} catch (final IOException e) {
sendMessage(" - &cFailed to save configuration.");
}
@ -285,7 +295,7 @@ public class LikePlotMeConverter {
}
final String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PlotSquared.getInstance().removePlotWorld(actualWorldName);
PS.get().removePlotWorld(actualWorldName);
if (MV) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
@ -321,7 +331,8 @@ public class LikePlotMeConverter {
}
});
} catch (final Exception e) {
PlotSquared.log("&/end/");
e.printStackTrace();
PS.log("&/end/");
}
return true;
}

View File

@ -0,0 +1,215 @@
package com.intellectualcrafters.plot.database.plotme;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.UUID;
import java.util.Map.Entry;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
try {
if (plotConfig.getBoolean("usemySQL")) {
String user = plotConfig.getString("mySQLuname");
String password = plotConfig.getString("mySQLpass");
String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
} else {
File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) {
return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection();
}
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
}
catch (SQLException | ClassNotFoundException e) {}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
ResultSet r;
PreparedStatement stmt;
HashMap<String, Integer> plotWidth = new HashMap<>();
HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<Integer, Plot> plots = new HashMap<>();
HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_plots`");
r = stmt.executeQuery();
boolean checkUUID = DBFunc.hasColumn(r, "ownerID");
boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) {
int key = r.getInt("plot_id");
PlotId id = new PlotId(r.getInt("plotX"), r.getInt("plotZ"));
String name = r.getString("owner");
String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world)) {
if (merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId,boolean[]>());
}
}
if (merge) {
int tx = r.getInt("topX");
int tz = r.getInt("topZ");
int bx = r.getInt("bottomX") - 1;
int bz = r.getInt("bottomZ") - 1;
int path = roadWidth.get(world);
int plot = plotWidth.get(world);
Location top = getPlotTopLocAbs(path, plot, id);
Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX()) {
setMerged(merges, world, id, 1);
}
if (tz > top.getZ()) {
setMerged(merges, world, id, 2);
}
if (bx < bot.getX()) {
setMerged(merges, world, id, 3);
}
if (bz > bot.getZ()) {
setMerged(merges, world, id, 0);
}
}
UUID owner = UUIDHandler.getUUID(name);
if (owner == null) {
if (name.equals("*")) {
owner = DBFunc.everyone;
}
else {
if (checkUUID){
try {
byte[] bytes = r.getBytes("ownerid");
if (bytes != null) {
owner = UUID.nameUUIDFromBytes(bytes);
if (owner != null) {
UUIDHandler.add(new StringWrapper(name), owner);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
if (owner == null) {
MainUtil.sendConsoleMessage("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
continue;
}
}
}
else {
UUIDHandler.add(new StringWrapper(name), owner);
}
Plot plot = new Plot(world, id, owner);
plots.put(key, plot);
}
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.world);
if (mergeMap != null) {
if (mergeMap.containsKey(plot.id)) {
plot.settings.setMerged(mergeMap.get(plot.id));
}
}
}
r.close();
stmt.close();
try {
MainUtil.sendConsoleMessage(" - " + plugin + "_denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "_denied`");
r = stmt.executeQuery();
while (r.next()) {
int key = r.getInt("plot_id");
Plot plot = plots.get(key);
if (plot == null) {
MainUtil.sendConsoleMessage("&6Denied (" + key + ") references deleted plot; ignoring entry.");
continue;
}
String name = r.getString("player");
UUID denied = UUIDHandler.getUUID(name);
if (denied == null) {
if (name.equals("*")) {
denied = DBFunc.everyone;
} else {
MainUtil.sendConsoleMessage("&6Denied (" + key + ") references incorrect name (`" + name + "`)");
continue;
}
}
plot.denied.add(denied);
}
MainUtil.sendConsoleMessage(" - " + plugin + "_allowed");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "_allowed`");
r = stmt.executeQuery();
while (r.next()) {
int key = r.getInt("plot_id");
Plot plot = plots.get(key);
if (plot == null) {
MainUtil.sendConsoleMessage("&6Allowed (" + key + ") references deleted plot; ignoring entry.");
continue;
}
String name = r.getString("player");
UUID allowed = UUIDHandler.getUUID(name);
if (allowed == null) {
if (name.equals("*")) {
allowed = DBFunc.everyone;
} else {
MainUtil.sendConsoleMessage("&6Allowed (" + key + ") references incorrect name (`" + name + "`)");
continue;
}
}
plot.trusted.add(allowed);
}
r.close();
stmt.close();
}
catch (Exception e) {}
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
HashMap<PlotId, Plot> map = processed.get(plot.world);
if (map == null) {
map = new HashMap<>();
processed.put(plot.world, map);
}
map.put(plot.id, plot);
}
return processed ;
}
@Override
public boolean accepts(String version) {
if (version == null) {
return false;
}
return !PS.get().canUpdate(version, "0.17");
}
}

View File

@ -25,7 +25,6 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotCluster;
/**

View File

@ -31,6 +31,7 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Empire92
*/
public class PlayerLeavePlotEvent extends PlayerEvent {
private static HandlerList handlers = new HandlerList();
private final Plot plot;

View File

@ -32,9 +32,9 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Citymonstret
* @author Empire92
*/
public class PlayerPlotDeniedEvent extends Event {
public class PlayerPlotDeniedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Player initiator;
private final boolean added;
private final UUID player;
@ -48,8 +48,8 @@ public class PlayerPlotDeniedEvent extends Event {
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.plot = plot;
this.added = added;
this.player = player;
}
@ -76,15 +76,6 @@ public class PlayerPlotDeniedEvent extends Event {
return this.player;
}
/**
* The plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* The player initiating the action
*

View File

@ -32,9 +32,9 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Empire92
* @author Citymonstret
*/
public class PlayerPlotHelperEvent extends Event {
public class PlayerPlotHelperEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Player initiator;
private final boolean added;
private final UUID player;
@ -48,8 +48,8 @@ public class PlayerPlotHelperEvent extends Event {
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.plot = plot;
this.added = added;
this.player = player;
}
@ -76,15 +76,6 @@ public class PlayerPlotHelperEvent extends Event {
return this.player;
}
/**
* The plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* The player initiating the action
*

View File

@ -32,9 +32,9 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Citymonstret
* @author Empire92
*/
public class PlayerPlotTrustedEvent extends Event {
public class PlayerPlotTrustedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Player initiator;
private final boolean added;
private final UUID player;
@ -48,8 +48,8 @@ public class PlayerPlotTrustedEvent extends Event {
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.plot = plot;
this.added = added;
this.player = player;
}
@ -76,15 +76,6 @@ public class PlayerPlotTrustedEvent extends Event {
return this.player;
}
/**
* The plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* The player initiating the action
*

View File

@ -0,0 +1,20 @@
package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.object.Plot;
import com.sk89q.worldedit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public abstract class PlotEvent extends Event {
private final Plot plot;
public PlotEvent(final Plot plot) {
this.plot = plot;
}
public final Plot getPlot() {
return this.plot;
}
}

View File

@ -33,9 +33,9 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Citymonstret
* @author Empire92
*/
public class PlotFlagAddEvent extends Event implements Cancellable {
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Flag flag;
private boolean cancelled;
@ -46,7 +46,7 @@ public class PlotFlagAddEvent extends Event implements Cancellable {
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(final Flag flag, final Plot plot) {
this.plot = plot;
super(plot);
this.flag = flag;
}
@ -54,15 +54,6 @@ public class PlotFlagAddEvent extends Event implements Cancellable {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* Get the flag involved
*
@ -78,12 +69,12 @@ public class PlotFlagAddEvent extends Event implements Cancellable {
}
@Override
public boolean isCancelled() {
public final boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -33,9 +33,9 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Citymonstret
* @author Empire92
*/
public class PlotFlagRemoveEvent extends Event implements Cancellable {
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Flag flag;
private boolean cancelled;
@ -46,7 +46,7 @@ public class PlotFlagRemoveEvent extends Event implements Cancellable {
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(final Flag flag, final Plot plot) {
this.plot = plot;
super(plot);
this.flag = flag;
}
@ -54,14 +54,6 @@ public class PlotFlagRemoveEvent extends Event implements Cancellable {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* Get the flag involved
@ -78,12 +70,12 @@ public class PlotFlagRemoveEvent extends Event implements Cancellable {
}
@Override
public boolean isCancelled() {
public final boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -0,0 +1,46 @@
package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import org.bukkit.event.HandlerList;
/**
* Created 2015-07-13 for PlotSquaredGit
*
* @author Citymonstret
*/
public class PlotRateEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final PlotPlayer rater;
private int rating;
public PlotRateEvent(final PlotPlayer rater, final int rating, final Plot plot) {
super(plot);
this.rater = rater;
this.rating = rating;
}
public static HandlerList getHandlerList() {
return handlers;
}
public PlotPlayer getRater() {
return this.rater;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getRating() {
return this.rating;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

Some files were not shown because too many files have changed in this diff Show More