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

1
.gitignore vendored
View File

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

View File

@ -8,7 +8,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<artifactId>PlotSquared</artifactId> <artifactId>PlotSquared</artifactId>
<version>2.11.27</version> <version>2.12.5</version>
<name>PlotSquared</name> <name>PlotSquared</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<build> <build>
@ -48,10 +48,6 @@
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public/</url>
</repository>
<repository> <repository>
<id>empcraft-repo</id> <id>empcraft-repo</id>
<url>http://empcraft.com/maven2</url> <url>http://empcraft.com/maven2</url>
@ -82,7 +78,7 @@
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
<version>1.8.3-R0.1-SNAPSHOT</version> <version>1.8-R0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q</groupId> <groupId>com.sk89q</groupId>
@ -107,5 +103,10 @@
<version>1.5</version> <version>1.5</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies> </dependencies>
</project> </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 { public void close() throws IOException {
this.os.close(); this.os.close();
} }
/**
* Flush output
* @throws IOException
*/
public void flush() throws IOException {
this.os.flush();
}
} }

View File

@ -1,44 +1,157 @@
package com.intellectualcrafters.plot; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.plotme.ClassicPlotMeConnector; import com.intellectualcrafters.plot.database.plotme.ClassicPlotMeConnector;
import com.intellectualcrafters.plot.database.plotme.LikePlotMeConverter; 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.flag.FlagManager;
import com.intellectualcrafters.plot.generator.BukkitHybridUtils; import com.intellectualcrafters.plot.generator.BukkitHybridUtils;
import com.intellectualcrafters.plot.generator.HybridGen; import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.HybridUtils; 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.WEListener;
import com.intellectualcrafters.plot.listeners.worldedit.WESubscriber; import com.intellectualcrafters.plot.listeners.worldedit.WESubscriber;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.titles.AbstractTitle; import com.intellectualcrafters.plot.titles.AbstractTitle;
import com.intellectualcrafters.plot.titles.DefaultTitle; import com.intellectualcrafters.plot.titles.DefaultTitle;
import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.bukkit.*; 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.DefaultUUIDWrapper;
import com.intellectualcrafters.plot.uuid.LowerOfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.LowerOfflineUUIDWrapper;
import com.intellectualcrafters.plot.uuid.OfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.OfflineUUIDWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; 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 class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@ -57,8 +170,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (version.length == 3) { if (version.length == 3) {
version[2] = Integer.parseInt(split[2]); version[2] = Integer.parseInt(split[2]);
} }
} } catch (Exception e) {
catch (Exception e) {
return false; return false;
} }
} }
@ -68,7 +180,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public void onEnable() { public void onEnable() {
THIS = this; THIS = this;
PlotSquared.instance = new PlotSquared(this); PS.instance = new PS(this);
if (Settings.METRICS) { if (Settings.METRICS) {
try { try {
final Metrics metrics = new Metrics(this); final Metrics metrics = new Metrics(this);
@ -80,6 +192,18 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} else { } else {
log("&dUsing metrics will allow us to improve the plugin, please consider it :)"); 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(); List<World> worlds = Bukkit.getWorlds();
if (worlds.size() > 0) { if (worlds.size() > 0) {
UUIDHandler.cacheAll(worlds.get(0).getName()); UUIDHandler.cacheAll(worlds.get(0).getName());
@ -94,10 +218,15 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} }
} }
@Override @Override
public void onDisable() { public void onDisable() {
PlotSquared.getInstance().disable(); PS.get().disable();
try {
unloadRecursively(this);
}
catch (Exception e) {
e.printStackTrace();
};
THIS = null; THIS = null;
} }
@ -107,15 +236,18 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
return; return;
} }
message = message.replaceAll("\u00B2", "2"); message = message.replaceAll("\u00B2", "2");
if ((THIS == null) || (Bukkit.getServer().getConsoleSender() == null)) { if (THIS != null && Bukkit.getServer().getConsoleSender() != null) {
System.out.println(ChatColor.stripColor(ConsoleColors.fromString(message))); try {
} else {
message = ChatColor.translateAlternateColorCodes('&', message); message = ChatColor.translateAlternateColorCodes('&', message);
if (!Settings.CONSOLE_COLOR) { if (!Settings.CONSOLE_COLOR) {
message = ChatColor.stripColor(message); message = ChatColor.stripColor(message);
} }
Bukkit.getServer().getConsoleSender().sendMessage(message); Bukkit.getServer().getConsoleSender().sendMessage(message);
return;
} }
catch (Throwable e) {};
}
System.out.println(ConsoleColors.fromString(message));
} }
@Override @Override
@ -140,6 +272,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public void registerCommands() { public void registerCommands() {
new MainCommand(); 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 Template());
MainCommand.subCommands.add(new Setup()); MainCommand.subCommands.add(new Setup());
MainCommand.subCommands.add(new DebugUUID()); MainCommand.subCommands.add(new DebugUUID());
@ -162,14 +297,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (Settings.ENABLE_CLUSTERS) { if (Settings.ENABLE_CLUSTERS) {
MainCommand.subCommands.add(new Cluster()); MainCommand.subCommands.add(new Cluster());
} }
MainCommand.subCommands.add(new Trust()); MainCommand.subCommands.add(new Trust());
MainCommand.subCommands.add(new Add()); MainCommand.subCommands.add(new Add());
MainCommand.subCommands.add(new Deny()); MainCommand.subCommands.add(new Deny());
MainCommand.subCommands.add(new Untrust()); MainCommand.subCommands.add(new Untrust());
MainCommand.subCommands.add(new Remove()); MainCommand.subCommands.add(new Remove());
MainCommand.subCommands.add(new Undeny()); MainCommand.subCommands.add(new Undeny());
MainCommand.subCommands.add(new Info()); MainCommand.subCommands.add(new Info());
MainCommand.subCommands.add(new list()); MainCommand.subCommands.add(new list());
MainCommand.subCommands.add(new Help()); MainCommand.subCommands.add(new Help());
@ -235,7 +368,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
this.error = 0l; this.error = 0l;
} }
World world; World world;
for (final String w : PlotSquared.getInstance().getPlotWorlds()) { for (final String w : PS.get().getPlotWorlds()) {
world = Bukkit.getWorld(w); world = Bukkit.getWorld(w);
try { try {
if (world.getLoadedChunks().length < 1) { if (world.getLoadedChunks().length < 1) {
@ -260,10 +393,167 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
}, 20); }, 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 @Override
final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
WorldEvents.lastWorld = world; WorldEvents.lastWorld = world;
if (!PlotSquared.getInstance().setupPlotWorld(world, id)) { if (!PS.get().setupPlotWorld(world, id)) {
return null; return null;
} }
HybridGen result = new HybridGen(world); HybridGen result = new HybridGen(world);
@ -308,8 +598,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public void registerWorldEditEvents() { public void registerWorldEditEvents() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
PlotSquared.getInstance().worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); PS.get().worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
final String version = PlotSquared.getInstance().worldEdit.getDescription().getVersion(); final String version = PS.get().worldEdit.getDescription().getVersion();
if ((version != null) && version.startsWith("5.")) { if ((version != null) && version.startsWith("5.")) {
log("&cThis version of WorldEdit does not support PlotSquared."); log("&cThis version of WorldEdit does not support PlotSquared.");
log("&cPlease use WorldEdit 6+ for masking support"); log("&cPlease use WorldEdit 6+ for masking support");
@ -366,9 +656,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
TaskManager.runTaskLaterAsync(new Runnable() { TaskManager.runTaskLaterAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!(new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector()))) { if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) return;
new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector()); if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) return;
} if (new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector())) return;
} }
}, 20); }, 20);
return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null; return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null;
@ -400,8 +690,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (Settings.OFFLINE_MODE) { if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE) { if (Settings.UUID_LOWERCASE) {
UUIDHandler.uuidWrapper = new LowerOfflineUUIDWrapper(); UUIDHandler.uuidWrapper = new LowerOfflineUUIDWrapper();
} } else {
else {
UUIDHandler.uuidWrapper = new OfflineUUIDWrapper(); UUIDHandler.uuidWrapper = new OfflineUUIDWrapper();
} }
Settings.OFFLINE_MODE = true; Settings.OFFLINE_MODE = true;
@ -411,8 +700,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} else { } else {
if (Settings.UUID_LOWERCASE) { if (Settings.UUID_LOWERCASE) {
UUIDHandler.uuidWrapper = new LowerOfflineUUIDWrapper(); UUIDHandler.uuidWrapper = new LowerOfflineUUIDWrapper();
} } else {
else {
UUIDHandler.uuidWrapper = new OfflineUUIDWrapper(); UUIDHandler.uuidWrapper = new OfflineUUIDWrapper();
} }
Settings.OFFLINE_MODE = true; Settings.OFFLINE_MODE = true;
@ -425,8 +713,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
AbstractTitle.TITLE_CLASS = new DefaultTitle(); AbstractTitle.TITLE_CLASS = new DefaultTitle();
if (UUIDHandler.uuidWrapper instanceof DefaultUUIDWrapper) { if (UUIDHandler.uuidWrapper instanceof DefaultUUIDWrapper) {
Settings.TWIN_MODE_UUID = true; 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; Settings.TWIN_MODE_UUID = true;
} }
} }

View File

@ -24,6 +24,8 @@ public interface IPlotMain {
public File getDirectory(); public File getDirectory();
public File getFile();
public void disable(); public void disable();
public String getVersion(); public String getVersion();
@ -79,4 +81,6 @@ public interface IPlotMain {
public PlayerManager initPlayerManager(); public PlayerManager initPlayerManager();
public boolean checkVersion(int major, int minor, int minor2); public boolean checkVersion(int major, int minor, int minor2);
public void loadPlugin(String plugin);
} }

View File

@ -1,35 +1,85 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import com.intellectualcrafters.plot.config.C; import java.io.BufferedReader;
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.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; 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.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.SQLException; 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.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; 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, * An implementation of the core,
* with a static getter for easy access * with a static getter for easy access
@ -37,13 +87,10 @@ import java.util.zip.ZipInputStream;
* @author Sauilitired | Citymonstret * @author Sauilitired | Citymonstret
* @author boy0001 | Empire92 * @author boy0001 | Empire92
*/ */
public class PlotSquared { public class PS {
// public static final:
public static final String MAIN_PERMISSION = "plots.use";
// protected static: // protected static:
protected static PlotSquared instance; protected static PS instance;
// private final: // private final:
private final HashMap<String, PlotWorld> plotworlds = new HashMap<>(); private final HashMap<String, PlotWorld> plotworlds = new HashMap<>();
@ -52,17 +99,20 @@ public class PlotSquared {
// public: // public:
public WorldEditPlugin worldEdit = null; public WorldEditPlugin worldEdit = null;
public File configFile; public File configFile;
public File translationFile;
public YamlConfiguration style;
public YamlConfiguration config; public YamlConfiguration config;
public YamlConfiguration storage; public YamlConfiguration storage;
public IPlotMain IMP = null; public IPlotMain IMP = null;
public TaskManager TASK; public TaskManager TASK;
public URL update;
// private: // private:
private File styleFile; private File styleFile;
private YamlConfiguration style;
private File storageFile; private File storageFile;
private File FILE = null; // This file private File FILE = null; // This file
private String VERSION = null; private String VERSION = null;
private String LAST_VERSION;
private boolean LOADING_WORLD = false; private boolean LOADING_WORLD = false;
private LinkedHashMap<String, HashMap<PlotId, Plot>> plots; private LinkedHashMap<String, HashMap<PlotId, Plot>> plots;
private Database database; private Database database;
@ -72,18 +122,17 @@ public class PlotSquared {
* Initialize PlotSquared with the desired Implementation class * Initialize PlotSquared with the desired Implementation class
* @param imp_class * @param imp_class
*/ */
protected PlotSquared(final IPlotMain imp_class) { protected PS(final IPlotMain imp_class) {
instance = this;
SetupUtils.generators = new HashMap<>(); SetupUtils.generators = new HashMap<>();
IMP = imp_class; IMP = imp_class;
try { try {
FILE = new File(PlotSquared.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); FILE = new File(PS.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
} catch (Exception e) { } catch (Exception e) {
log("Could not determine file path"); log("Could not determine file path");
} }
VERSION = IMP.getVersion(); VERSION = IMP.getVersion();
EconHandler.manager = IMP.getEconomyHandler(); EconHandler.manager = IMP.getEconomyHandler();
C.setupTranslations();
C.saveTranslations();
if (getJavaVersion() < 1.7) { if (getJavaVersion() < 1.7) {
log(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 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 // Didn't know of any other link :D
@ -99,6 +148,8 @@ public class PlotSquared {
log(C.ENABLED.s()); log(C.ENABLED.s());
} }
setupConfigs(); setupConfigs();
this.translationFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "PlotSquared.use_THIS.yml");
C.load(translationFile);
setupDefaultFlags(); setupDefaultFlags();
setupDatabase(); setupDatabase();
CommentManager.registerDefaultInboxes(); CommentManager.registerDefaultInboxes();
@ -139,6 +190,23 @@ public class PlotSquared {
// Player manager // Player manager
PlayerManager.manager = IMP.initPlayerManager(); 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 // PlotMe
if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME) { if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME) {
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(new Runnable() {
@ -173,10 +241,26 @@ public class PlotSquared {
* *
* @return the instance created by IPlotMain * @return the instance created by IPlotMain
*/ */
public static PlotSquared getInstance() { public static PS get() {
return instance; 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 * Log a message to the IPlotMain logger
* *
@ -184,7 +268,7 @@ public class PlotSquared {
* @see IPlotMain#log(String) * @see IPlotMain#log(String)
*/ */
public static void log(final String message) { 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 * Sort a collection of plots by world, then by hashcode
* @param plots * @param plots
* @param priorityWorld
* @see #sortPlots(Collection, String) to sort with a specific priority world * @see #sortPlots(Collection, String) to sort with a specific priority world
* @see #sortPlots(Collection) to sort plots just by hashcode * @see #sortPlots(Collection) to sort plots just by hashcode
* @return ArrayList of plot * @return ArrayList of plot
@ -532,7 +615,11 @@ public class PlotSquared {
if (callEvent) { if (callEvent) {
EventUtil.manager.callDelete(world, id); 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)) { if (MainUtil.lastPlot.containsKey(world)) {
final PlotId last = MainUtil.lastPlot.get(world); final PlotId last = MainUtil.lastPlot.get(world);
final int last_max = Math.max(last.x, last.y); 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'!"); 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; 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); addPlotWorld(world, plotWorld, plotManager);
if (plotWorld.TYPE == 2) { if (plotWorld.TYPE == 2) {
if (ClusterManager.getClusters(world).size() > 0) { if (ClusterManager.getClusters(world).size() > 0) {
for (final PlotCluster cluster : ClusterManager.getClusters(world)) { 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); new AugmentedPopulator(world, gen_class, cluster, plotWorld.TERRAIN == 2, plotWorld.TERRAIN != 2);
} }
} }
@ -753,6 +849,123 @@ public class PlotSquared {
return true; 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;
}
/** /**
* Get the database connection * Get the database connection
@ -824,7 +1037,7 @@ public class PlotSquared {
public void setupDatabase() { public void setupDatabase() {
if (Settings.DB.USE_MYSQL) { if (Settings.DB.USE_MYSQL) {
try { 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(); connection = database.openConnection();
{ {
if (DBFunc.dbManager == null) { if (DBFunc.dbManager == null) {
@ -852,7 +1065,7 @@ public class PlotSquared {
log(C.PREFIX.s() + "MongoDB is not yet implemented"); log(C.PREFIX.s() + "MongoDB is not yet implemented");
} else if (Settings.DB.USE_SQLITE) { } else if (Settings.DB.USE_SQLITE) {
try { 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(); connection = this.database.openConnection();
{ {
DBFunc.dbManager = new SQLManager(connection, Settings.DB.PREFIX); 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("disable-physics", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("fly", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("fly", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("explosion", 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-interact", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("hostile-attack", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("hostile-attack", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("animal-interact", 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-interact", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("tamed-attack", 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-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-place", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("hanging-break", 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-use", new FlagValue.BooleanValue()));
FlagManager.addFlag(new AbstractFlag("vehicle-place", 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("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("place", new FlagValue.PlotBlockListValue()));
FlagManager.addFlag(new AbstractFlag("break", new FlagValue.PlotBlockListValue())); FlagManager.addFlag(new AbstractFlag("break", new FlagValue.PlotBlockListValue()));
FlagManager.addFlag(new AbstractFlag("use", new FlagValue.PlotBlockListValue())); FlagManager.addFlag(new AbstractFlag("use", new FlagValue.PlotBlockListValue()));
@ -980,6 +1198,7 @@ public class PlotSquared {
* Setup the default configuration (settings.yml) * Setup the default configuration (settings.yml)
*/ */
public void setupConfig() { public void setupConfig() {
LAST_VERSION = config.getString("version");
config.set("version", VERSION); config.set("version", VERSION);
final Map<String, Object> options = new HashMap<>(); final Map<String, Object> options = new HashMap<>();
@ -1023,6 +1242,10 @@ public class PlotSquared {
// Schematics // Schematics
options.put("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); 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 // Caching
options.put("cache.permissions", Settings.PERMISSION_CACHING); options.put("cache.permissions", Settings.PERMISSION_CACHING);
options.put("cache.ratings", Settings.CACHE_RATINGS); options.put("cache.ratings", Settings.CACHE_RATINGS);
@ -1073,7 +1296,7 @@ public class PlotSquared {
Settings.CONFIRM_UNLINK = config.getBoolean("confirmation.unlink"); Settings.CONFIRM_UNLINK = config.getBoolean("confirmation.unlink");
// Protection // 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.TNT_LISTENER = config.getBoolean("protection.tnt-listener.enabled");
Settings.PISTON_FALLING_BLOCK_CHECK = config.getBoolean("protection.piston.falling-blocks"); Settings.PISTON_FALLING_BLOCK_CHECK = config.getBoolean("protection.piston.falling-blocks");
@ -1107,6 +1330,10 @@ public class PlotSquared {
// Schematics // Schematics
Settings.SCHEMATIC_SAVE_PATH = config.getString("schematics.save_path"); 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 // Caching
Settings.PERMISSION_CACHING = config.getBoolean("cache.permissions"); Settings.PERMISSION_CACHING = config.getBoolean("cache.permissions");
Settings.CACHE_RATINGS = config.getBoolean("cache.ratings"); 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."); log(C.PREFIX.s() + "&6Debug Mode Enabled (Default). Edit the config to turn this off.");
} }
Settings.CONSOLE_COLOR = config.getBoolean("console.color"); 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.FANCY_CHAT = false;
} }
Settings.METRICS = config.getBoolean("metrics"); Settings.METRICS = config.getBoolean("metrics");
@ -1173,6 +1400,9 @@ public class PlotSquared {
try { try {
styleFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "style.yml"); styleFile = new File(IMP.getDirectory() + File.separator + "translations" + File.separator + "style.yml");
if (!styleFile.exists()) { if (!styleFile.exists()) {
if (!styleFile.getParentFile().exists()) {
styleFile.getParentFile().mkdirs();
}
if (!styleFile.createNewFile()) { if (!styleFile.createNewFile()) {
log("Could not create the style file, please create \"translations/style.yml\" manually"); log("Could not create the style file, please create \"translations/style.yml\" manually");
} }
@ -1180,6 +1410,7 @@ public class PlotSquared {
style = YamlConfiguration.loadConfiguration(styleFile); style = YamlConfiguration.loadConfiguration(styleFile);
setupStyle(); setupStyle();
} catch (final Exception err) { } catch (final Exception err) {
err.printStackTrace();
Logger.add(LogLevel.DANGER, "Failed to save style.yml"); Logger.add(LogLevel.DANGER, "Failed to save style.yml");
log("failed to save style.yml"); log("failed to save style.yml");
} }
@ -1259,10 +1490,6 @@ public class PlotSquared {
* Show startup debug information * Show startup debug information
*/ */
public void showDebug() { 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) { if (Settings.DEBUG) {
final Map<String, String> settings = new HashMap<>(); final Map<String, String> settings = new HashMap<>();
settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS);
@ -1287,12 +1514,12 @@ public class PlotSquared {
private void setupStyle() { private void setupStyle() {
style.set("version", VERSION); style.set("version", VERSION);
final Map<String, Object> o = new HashMap<>(); final Map<String, Object> o = new HashMap<>();
o.put("color.1", C.COLOR_1.substring(1)); o.put("color.1", "6");
o.put("color.2", C.COLOR_2.substring(1)); o.put("color.2", "7");
o.put("color.3", C.COLOR_3.substring(1)); o.put("color.3", "8");
o.put("color.4", C.COLOR_4.substring(1)); o.put("color.4", "3");
if (!style.contains("color")) {
for (final Entry<String, Object> node : o.entrySet()) { for (final Entry<String, Object> node : o.entrySet()) {
if (!style.contains(node.getKey())) {
style.set(node.getKey(), node.getValue()); style.set(node.getKey(), node.getValue());
} }
} }

View File

@ -21,27 +21,37 @@
package com.intellectualcrafters.plot.api; 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.MainCommand;
import com.intellectualcrafters.plot.commands.SubCommand; import com.intellectualcrafters.plot.commands.SubCommand;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.flag.AbstractFlag; import com.intellectualcrafters.plot.flag.AbstractFlag;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.util.*; 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.BukkitSetBlockManager;
import com.intellectualcrafters.plot.util.bukkit.BukkitUtil; import com.intellectualcrafters.plot.util.bukkit.BukkitUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; 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 * PlotSquared API
@ -68,7 +78,7 @@ import java.util.Set;
* *
* @throws com.intellectualcrafters.plot.util.PlotSquaredException if the program fails to fetch the PlotSquared * @throws com.intellectualcrafters.plot.util.PlotSquaredException if the program fails to fetch the PlotSquared
* instance * instance
* @see com.intellectualcrafters.plot.PlotSquared * @see com.intellectualcrafters.plot.PS
*/ */
@Deprecated @Deprecated
public PlotAPI(final JavaPlugin plugin) { public PlotAPI(final JavaPlugin plugin) {
@ -82,10 +92,10 @@ import java.util.Set;
* *
* @return all plots * @return all plots
* *
* @see com.intellectualcrafters.plot.PlotSquared#getPlots() * @see com.intellectualcrafters.plot.PS#getPlots()
*/ */
public Set<Plot> getAllPlots() { 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 * @return all plots that a player owns
*/ */
public Set<Plot> getPlayerPlots(final Player player) { 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 plotWorld Plot World Object
* @param manager World Manager * @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) * com.intellectualcrafters.plot.object.PlotManager)
*/ */
public void addPlotWorld(final String world, final PlotWorld plotWorld, final PlotManager manager) { 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 * @return main configuration
* *
* @see com.intellectualcrafters.plot.PlotSquared#config * @see com.intellectualcrafters.plot.PS#config
*/ */
public YamlConfiguration getConfig() { public YamlConfiguration getConfig() {
return PlotSquared.getInstance().config; return PS.get().config;
} }
/** /**
* @return storage configuration * @return storage configuration
* *
* @see com.intellectualcrafters.plot.PlotSquared#storage * @see com.intellectualcrafters.plot.PS#storage
*/ */
public YamlConfiguration getStorage() { public YamlConfiguration getStorage() {
return PlotSquared.getInstance().storage; return PS.get().storage;
} }
/** /**
@ -137,10 +147,10 @@ import java.util.Set;
* *
* @return PlotSquared PlotSquared Main Class * @return PlotSquared PlotSquared Main Class
* *
* @see com.intellectualcrafters.plot.PlotSquared * @see com.intellectualcrafters.plot.PS
*/ */
public PlotSquared getMain() { public PS getMain() {
return PlotSquared.getInstance(); return PS.get();
} }
/** /**
@ -240,8 +250,8 @@ import java.util.Set;
* @see com.intellectualcrafters.plot.util.Permissions * @see com.intellectualcrafters.plot.util.Permissions
*/ */
@Deprecated @Deprecated
public Permissions getPermissions() { public Permissions[] getPermissions() {
return new Permissions(); return Permissions.values();
} }
/** /**
@ -275,10 +285,10 @@ import java.util.Set;
* @return PlotManager * @return PlotManager
* *
* @see com.intellectualcrafters.plot.object.PlotManager * @see com.intellectualcrafters.plot.object.PlotManager
* @see PlotSquared#getPlotManager(String) * @see PS#getPlotManager(String)
*/ */
public PlotManager getPlotManager(final World world) { 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 * @return PlotManager
* *
* @see PlotSquared#getPlotManager(String) * @see PS#getPlotManager(String)
* @see com.intellectualcrafters.plot.object.PlotManager * @see com.intellectualcrafters.plot.object.PlotManager
*/ */
public PlotManager getPlotManager(final String world) { 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 * @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 * @see com.intellectualcrafters.plot.object.PlotWorld
*/ */
public PlotWorld getWorldSettings(final World world) { 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 * @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 * @see com.intellectualcrafters.plot.object.PlotWorld
*/ */
public PlotWorld getWorldSettings(final String world) { 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) { public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) {
final ArrayList<Plot> pPlots = new ArrayList<>(); 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 (just_owner) {
if ((plot.owner != null) && (plot.owner.equals(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr))))) { if ((plot.owner != null) && (plot.owner.equals(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr))))) {
pPlots.add(plot); pPlots.add(plot);
@ -485,11 +495,11 @@ import java.util.Set;
* *
* @return Plot[] - array of plot objects in world * @return Plot[] - array of plot objects in world
* *
* @see PlotSquared#getPlots(String) * @see PS#getPlots(String)
* @see com.intellectualcrafters.plot.object.Plot * @see com.intellectualcrafters.plot.object.Plot
*/ */
public Plot[] getPlots(final World world) { 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()]); return plots.toArray(new Plot[plots.size()]);
} }
@ -498,10 +508,10 @@ import java.util.Set;
* *
* @return World[] - array of plot worlds * @return World[] - array of plot worlds
* *
* @see com.intellectualcrafters.plot.PlotSquared#getPlotWorlds() * @see com.intellectualcrafters.plot.PS#getPlotWorlds()
*/ */
public String[] getPlotWorlds() { public String[] getPlotWorlds() {
Set<String> worlds = PlotSquared.getInstance().getPlotWorlds(); Set<String> worlds = PS.get().getPlotWorlds();
return worlds.toArray(new String[worlds.size()]); return worlds.toArray(new String[worlds.size()]);
} }
@ -512,10 +522,10 @@ import java.util.Set;
* *
* @return boolean (if plot world or not) * @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) { 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 * @return PlotSquared Class
* *
* @see com.intellectualcrafters.plot.PlotSquared * @see com.intellectualcrafters.plot.PS
*/ */
public PlotSquared getPlotSquared() { public PS getPlotSquared() {
return PlotSquared.getInstance(); return PS.get();
} }
/** /**
@ -639,12 +649,12 @@ import java.util.Set;
* *
* @return a set containing the players plots * @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) * org.bukkit.entity.Player)
* @see com.intellectualcrafters.plot.object.Plot * @see com.intellectualcrafters.plot.object.Plot
*/ */
public Set<Plot> getPlayerPlots(final World world, final Player player) { 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; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location; 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.Permissions;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import java.util.UUID;
public class Add extends SubCommand { public class Add extends SubCommand {
public Add() { public Add() {
super(Command.ADD, "Allow a user to build while you are online", "add <player>", CommandCategory.ACTIONS, true); 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]); MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false; return false;
} }
if (!plot.members.contains(uuid)) {
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.ALREADY_OWNER); MainUtil.sendMessage(plr, C.ALREADY_OWNER);
return false; return false;
} }
if (plot.trusted.contains(uuid)) {
plot.trusted.remove(uuid); if (plot.members.contains(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 {
MainUtil.sendMessage(plr, C.ALREADY_ADDED); MainUtil.sendMessage(plr, C.ALREADY_ADDED);
return false; return false;
} }
if (plot.members.size() + plot.trusted.size() >= PlotSquared.getInstance().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) { 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); MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS);
return false; 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); MainUtil.sendMessage(plr, C.MEMBER_ADDED);
return true; return true;
} }

View File

@ -20,10 +20,15 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; 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.ClusterManager;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
@ -70,11 +75,11 @@ public class Auto extends SubCommand {
int size_x = 1; int size_x = 1;
int size_z = 1; int size_z = 1;
String schematic = ""; String schematic = "";
if (PlotSquared.getInstance().getPlotWorlds().size() == 1) { if (PS.get().getPlotWorlds().size() == 1) {
world = PlotSquared.getInstance().getPlotWorlds().iterator().next(); world = PS.get().getPlotWorlds().iterator().next();
} else { } else {
world = plr.getLocation().getWorld(); world = plr.getLocation().getWorld();
if (!PlotSquared.getInstance().isPlotWorld(world)) { if (!PS.get().isPlotWorld(world)) {
MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
} }
@ -122,7 +127,7 @@ public class Auto extends SubCommand {
} }
return false; return false;
} }
final PlotWorld pWorld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld pWorld = PS.get().getPlotWorld(world);
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) { if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) {
double cost = pWorld.PLOT_PRICE; double cost = pWorld.PLOT_PRICE;
cost = (size_x * size_z) * cost; cost = (size_x * size_z) * cost;
@ -148,7 +153,7 @@ public class Auto extends SubCommand {
// } // }
} }
final String worldname = world; final String worldname = world;
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(worldname); final PlotWorld plotworld = PS.get().getPlotWorld(worldname);
if (plotworld.TYPE == 2) { if (plotworld.TYPE == 2) {
final Location loc = plr.getLocation(); final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(new Location(worldname, loc.getX(), loc.getY(), loc.getZ())); 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); MainUtil.lastPlot.put(worldname, start);
if (lastPlot) { 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; continue;
} else { } else {
lastPlot = false; lastPlot = false;

View File

@ -20,13 +20,18 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager; 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.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
@ -46,7 +51,7 @@ public class Buy extends SubCommand {
} }
final Location loc = plr.getLocation(); final Location loc = plr.getLocation();
final String world = loc.getWorld(); final String world = loc.getWorld();
if (!PlotSquared.getInstance().isPlotWorld(world)) { if (!PS.get().isPlotWorld(world)) {
return sendMessage(plr, C.NOT_IN_PLOT_WORLD); return sendMessage(plr, C.NOT_IN_PLOT_WORLD);
} }
Plot plot; Plot plot;
@ -83,7 +88,7 @@ public class Buy extends SubCommand {
final PlotId id = plot.id; final PlotId id = plot.id;
final PlotId id2 = MainUtil.getTopPlot(plot).id; final PlotId id2 = MainUtil.getTopPlot(plot).id;
final int size = MainUtil.getPlotSelectionIds(id, id2).size(); 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) { if (plotworld.USE_ECONOMY) {
price += plotworld.PLOT_PRICE * size; price += plotworld.PLOT_PRICE * size;
initPrice += plotworld.SELL_PRICE * size; initPrice += plotworld.SELL_PRICE * size;

View File

@ -1,6 +1,6 @@
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld; import com.intellectualcrafters.plot.object.PlotWorld;
@ -13,7 +13,7 @@ public class Chat extends SubCommand {
@Override @Override
public boolean execute(PlotPlayer plr, String... args) { public boolean execute(PlotPlayer plr, String... args) {
final String world = plr.getLocation().getWorld(); final String world = plr.getLocation().getWorld();
if (!PlotSquared.getInstance().isPlotWorld(world)) { if (!PS.get().isPlotWorld(world)) {
return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); return !sendMessage(plr, C.NOT_IN_PLOT_WORLD);
} }
boolean enable = !(plr.getMeta("chat") != null && (Boolean) plr.getMeta("chat")); boolean enable = !(plr.getMeta("chat") != null && (Boolean) plr.getMeta("chat"));
@ -24,7 +24,7 @@ public class Chat extends SubCommand {
enable = false; enable = false;
} }
} }
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (!enable && plotworld.PLOT_CHAT) { if (!enable && plotworld.PLOT_CHAT) {
return !sendMessage(plr, C.PLOT_CHAT_FORCED); return !sendMessage(plr, C.PLOT_CHAT_FORCED);
} }

View File

@ -20,14 +20,18 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld; 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; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
/** /**
@ -56,8 +60,8 @@ public class Claim extends SubCommand {
MainUtil.teleportPlayer(player, loc, plot); MainUtil.teleportPlayer(player, loc, plot);
} }
final String world = plot.world; final String world = plot.world;
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotworld = PS.get().getPlotWorld(world);
final Plot plot2 = PlotSquared.getInstance().getPlots(world).get(plot.id); final Plot plot2 = PS.get().getPlots(world).get(plot.id);
if (plotworld.SCHEMATIC_ON_CLAIM) { if (plotworld.SCHEMATIC_ON_CLAIM) {
Schematic sch; Schematic sch;
if (schematic.equals("")) { if (schematic.equals("")) {
@ -70,7 +74,7 @@ public class Claim extends SubCommand {
} }
SchematicHandler.manager.paste(sch, plot2, 0, 0); SchematicHandler.manager.paste(sch, plot2, 0, 0);
} }
PlotSquared.getInstance().getPlotManager(world).claimPlot(plotworld, plot); PS.get().getPlotManager(world).claimPlot(plotworld, plot);
} }
return result; return result;
} }
@ -93,7 +97,7 @@ public class Claim extends SubCommand {
if (!MainUtil.canClaim(plr, plot)) { if (!MainUtil.canClaim(plr, plot)) {
return sendMessage(plr, C.PLOT_IS_CLAIMED); 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) { if ((EconHandler.manager != null) && world.USE_ECONOMY) {
final double cost = world.PLOT_PRICE; final double cost = world.PLOT_PRICE;
if (cost > 0d) { if (cost > 0d) {

View File

@ -20,7 +20,9 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location; 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.TaskManager;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import java.util.Set;
public class Clear extends SubCommand { public class Clear extends SubCommand {
public Clear() { public Clear() {
super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, false); super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, false);
@ -45,25 +45,25 @@ public class Clear extends SubCommand {
if (plr == null) { if (plr == null) {
// Is console // Is console
if (args.length < 2) { 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 { } else {
final PlotId id = PlotId.fromString(args[0]); final PlotId id = PlotId.fromString(args[0]);
final String world = args[1]; final String world = args[1];
if (id == null) { if (id == null) {
PlotSquared.log("Invalid Plot ID: " + args[0]); PS.log("Invalid Plot ID: " + args[0]);
} else { } else {
if (!PlotSquared.getInstance().isPlotWorld(world)) { if (!PS.get().isPlotWorld(world)) {
PlotSquared.log("Invalid plot world: " + world); PS.log("Invalid plot world: " + world);
} else { } else {
final Plot plot = MainUtil.getPlot(world, id); final Plot plot = MainUtil.getPlot(world, id);
if (plot == null) { 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 { } else {
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
@Override @Override
public void run() { public void run() {
MainUtil.clear(world, plot, plot.owner == null, null); MainUtil.clear(plot, plot.owner == null, null);
PlotSquared.log("Plot " + plot.getId().toString() + " cleared."); PS.log("Plot " + plot.getId().toString() + " cleared.");
} }
}; };
if (Settings.CONFIRM_CLEAR && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { 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]); PlotId id = PlotId.fromString(args[0]);
if (id == null) { if (id == null) {
if (args[1].equalsIgnoreCase("mine")) { if (args[1].equalsIgnoreCase("mine")) {
Set<Plot> plots = PlotSquared.getInstance().getPlots(plr); Set<Plot> plots = PS.get().getPlots(plr);
if (plots.size() == 0) { if (plots.size() == 0) {
MainUtil.sendMessage(plr, C.NO_PLOTS); MainUtil.sendMessage(plr, C.NO_PLOTS);
return false; return false;

View File

@ -20,21 +20,29 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.generator.AugmentedPopulator; import com.intellectualcrafters.plot.generator.AugmentedPopulator;
import com.intellectualcrafters.plot.generator.HybridGen; 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.ClusterManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; 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 class Cluster extends SubCommand {
public Cluster() { public Cluster() {
super(Command.CLUSTER, "Manage a plot cluster", "cluster", CommandCategory.ACTIONS, true); 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); ClusterManager.clusters.get(world).add(cluster);
// Add any existing plots to the current 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); final PlotCluster current = ClusterManager.getCluster(plot);
if (cluster.equals(current) && !cluster.isAdded(plot.owner)) { if (cluster.equals(current) && !cluster.isAdded(plot.owner)) {
cluster.invited.add(plot.owner); cluster.invited.add(plot.owner);
DBFunc.setInvited(world, cluster, plot.owner); DBFunc.setInvited(world, cluster, plot.owner);
} }
} }
PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); PlotWorld plotworld = PS.get().getPlotWorld(world);
if (plotworld == null) { if (plotworld == null) {
PlotSquared.getInstance().config.createSection("worlds." + world); PS.get().config.createSection("worlds." + world);
PlotSquared.getInstance().loadWorld(world, null); PS.get().loadWorld(world, null);
} }
else { 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; PlotGenerator generator;
if (gen_string == null) { if (gen_string == null) {
generator = new HybridGen(world); generator = new HybridGen(world);
} else { } 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); new AugmentedPopulator(world, generator, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2);
} }
@ -177,17 +185,17 @@ public class Cluster extends SubCommand {
return false; return false;
} }
} }
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(plr.getLocation().getWorld()); final PlotWorld plotworld = PS.get().getPlotWorld(plr.getLocation().getWorld());
if (plotworld.TYPE == 2) { if (plotworld.TYPE == 2) {
final ArrayList<Plot> toRemove = new ArrayList<>(); 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); final PlotCluster other = ClusterManager.getCluster(plot);
if (cluster.equals(other)) { if (cluster.equals(other)) {
toRemove.add(plot); toRemove.add(plot);
} }
} }
for (final Plot plot : toRemove) { for (final Plot plot : toRemove) {
DBFunc.delete(plot.world, plot); plot.unclaim();
} }
} }
DBFunc.delete(cluster); DBFunc.delete(cluster);
@ -361,11 +369,11 @@ public class Cluster extends SubCommand {
if (player != null) { if (player != null) {
MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); 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); final PlotCluster current = ClusterManager.getCluster(plot);
if ((current != null) && current.equals(cluster)) { if ((current != null) && current.equals(cluster)) {
final String world = plr.getLocation().getWorld(); final String world = plr.getLocation().getWorld();
DBFunc.delete(world, plot); plot.unclaim();
} }
} }
MainUtil.sendMessage(plr, C.CLUSTER_KICKED_USER); MainUtil.sendMessage(plr, C.CLUSTER_KICKED_USER);
@ -411,11 +419,11 @@ public class Cluster extends SubCommand {
cluster.invited.remove(uuid); cluster.invited.remove(uuid);
DBFunc.removeInvited(cluster, uuid); DBFunc.removeInvited(cluster, uuid);
MainUtil.sendMessage(plr, C.CLUSTER_REMOVED, cluster.getName()); 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); final PlotCluster current = ClusterManager.getCluster(plot);
if ((current != null) && current.equals(cluster)) { if ((current != null) && current.equals(cluster)) {
final String world = plr.getLocation().getWorld(); final String world = plr.getLocation().getWorld();
DBFunc.delete(world, plot); plot.unclaim();
} }
} }
return true; return true;

View File

@ -38,13 +38,11 @@ public enum Command {
ADD("add","a"), ADD("add","a"),
TRUST("trust", "t"), TRUST("trust", "t"),
DENY("deny", "d"), DENY("deny", "d"),
REMOVE("remove", "r"), REMOVE("remove", "r"),
UNTRUST("untrust", "ut"), UNTRUST("untrust", "ut"),
UNDENY("undeny", "ud"), UNDENY("undeny", "ud"),
TOGGLE("toggle", "attribute"), TOGGLE("toggle", "attribute"),
DOWNLOAD("download", "dl"),
MOVE("move"), MOVE("move"),
FLAG("flag", "f"), FLAG("flag", "f"),
TARGET("target"), TARGET("target"),

View File

@ -20,17 +20,21 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; 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 class Condense extends SubCommand {
public static boolean TASK = false; public static boolean TASK = false;
@ -40,7 +44,7 @@ public class Condense extends SubCommand {
} }
public static void sendMessage(final String message) { public static void sendMessage(final String message) {
PlotSquared.log("&3PlotSquared -> Plot condense&8: &7" + message); PS.log("&3PlotSquared -> Plot condense&8: &7" + message);
} }
@Override @Override
@ -54,7 +58,7 @@ public class Condense extends SubCommand {
return false; return false;
} }
final String worldname = args[0]; 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"); MainUtil.sendMessage(plr, "INVALID WORLD");
return false; return false;
} }
@ -77,7 +81,7 @@ public class Condense extends SubCommand {
return false; return false;
} }
final int radius = Integer.parseInt(args[2]); 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 size = plots.size();
final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1);
if (radius < minimum_radius) { if (radius < minimum_radius) {
@ -95,7 +99,7 @@ public class Condense extends SubCommand {
start = Auto.getNextPlot(start, 1); start = Auto.getNextPlot(start, 1);
} }
if (free.size() == 0 || to_move.size() == 0) { if (free.size() == 0 || to_move.size() == 0) {
MainUtil.sendMessage(plr, "NO PLOTS FOUND"); MainUtil.sendMessage(plr, "NO FREE PLOTS FOUND");
return false; return false;
} }
MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), new Runnable() { MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), new Runnable() {
@ -166,7 +170,7 @@ public class Condense extends SubCommand {
return false; return false;
} }
final int radius = Integer.parseInt(args[2]); 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 size = plots.size();
final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1);
if (radius < minimum_radius) { if (radius < minimum_radius) {

View File

@ -50,7 +50,7 @@ public class Copy extends SubCommand {
if (plot1 == null) { if (plot1 == null) {
return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT); 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); MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }

View File

@ -20,7 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.generator.HybridPlotWorld; import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
@ -41,7 +41,7 @@ public class CreateRoadSchematic extends SubCommand {
if (plot == null) { if (plot == null) {
return sendMessage(player, C.NOT_IN_PLOT); 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); return sendMessage(player, C.NOT_IN_PLOT_WORLD);
} }
HybridUtils.manager.setupRoadSchematic(plot); HybridUtils.manager.setupRoadSchematic(plot);

View File

@ -1,6 +1,11 @@
package com.intellectualcrafters.plot.commands; 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.config.Settings;
import com.intellectualcrafters.plot.database.MySQL; import com.intellectualcrafters.plot.database.MySQL;
import com.intellectualcrafters.plot.database.SQLManager; 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.TaskManager;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; 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 * 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) { private static boolean sendMessageU(final UUID uuid, final String msg) {
if (uuid == null) { if (uuid == null) {
PlotSquared.log(msg); PS.log(msg);
} else { } else {
final PlotPlayer p = UUIDHandler.getPlayer(uuid); final PlotPlayer p = UUIDHandler.getPlayer(uuid);
if ((p != null) && p.isOnline()) { 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) { 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() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -92,7 +92,7 @@ public class Database extends SubCommand {
} }
Connection n; Connection n;
try { try {
n = new MySQL(PlotSquared.getInstance(), host, port, database, username, password).openConnection(); n = new MySQL(host, port, database, username, password).openConnection();
// Connection // Connection
if (n.isClosed()) { if (n.isClosed()) {
return sendMessage(plr, "Failed to open connection"); 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) { private boolean sendMessage(final PlotPlayer player, final String msg) {
if (player == null) { if (player == null) {
PlotSquared.log(msg); PS.log(msg);
} else { } else {
MainUtil.sendMessage(player, msg); MainUtil.sendMessage(player, msg);
} }

View File

@ -20,7 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.Lag; import com.intellectualcrafters.plot.util.Lag;
@ -51,7 +51,7 @@ public class Debug extends SubCommand {
} }
{ {
final StringBuilder worlds = new StringBuilder(""); final StringBuilder worlds = new StringBuilder("");
for (final String world : PlotSquared.getInstance().getPlotWorlds()) { for (final String world : PS.get().getPlotWorlds()) {
worlds.append(world).append(" "); worlds.append(world).append(" ");
} }
information.append(header); information.append(header);
@ -61,7 +61,7 @@ public class Debug extends SubCommand {
information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%"));
information.append(getSection(section, "PlotWorld")); information.append(getSection(section, "PlotWorld"));
information.append(getLine(line, "Plot Worlds", worlds)); 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(getSection(section, "Messages"));
information.append(getLine(line, "Total Messages", C.values().length)); information.append(getLine(line, "Total Messages", C.values().length));
information.append(getLine(line, "View all captions", "/plot debug msg")); information.append(getLine(line, "View all captions", "/plot debug msg"));

View File

@ -20,20 +20,27 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.UUID;
import com.google.common.collect.BiMap; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; 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.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import java.util.ArrayList;
import java.util.UUID;
/** /**
* @author Citymonstret * @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}"); 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]; 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!"); return !MainUtil.sendMessage(null, "&cInvalid plot world!");
} }
PlotId min, max; 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: &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)"); 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 PlotManager manager = PS.get().getPlotManager(world);
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotworld = PS.get().getPlotWorld(world);
final ArrayList<Plot> plots = new ArrayList<>(); final ArrayList<Plot> plots = new ArrayList<>();
for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) { for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) {
final Plot plot = MainUtil.getPlot(world, id); 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) { if (contains) {
MainUtil.sendMessage(null, " - &cDB Already contains: " + plot.id); MainUtil.sendMessage(null, " - &cDB Already contains: " + plot.id);
continue; continue;
@ -134,7 +141,7 @@ public class DebugClaimTest extends SubCommand {
} }
}); });
for (final Plot plot : plots) { for (final Plot plot : plots) {
PlotSquared.getInstance().updatePlot(plot); PS.get().updatePlot(plot);
} }
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
} else { } else {

View File

@ -20,7 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.generator.SquarePlotWorld; import com.intellectualcrafters.plot.generator.SquarePlotWorld;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
@ -42,19 +42,19 @@ public class DebugClear extends SubCommand {
if (plr == null) { if (plr == null) {
// Is console // Is console
if (args.length < 2) { 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 { } else {
final PlotId id = PlotId.fromString(args[0]); final PlotId id = PlotId.fromString(args[0]);
final String world = args[1]; final String world = args[1];
if (id == null) { if (id == null) {
PlotSquared.log("Invalid Plot ID: " + args[0]); PS.log("Invalid Plot ID: " + args[0]);
} else { } else {
if (!PlotSquared.getInstance().isPlotWorld(world) || !(PlotSquared.getInstance().getPlotWorld(world) instanceof SquarePlotWorld)) { if (!PS.get().isPlotWorld(world) || !(PS.get().getPlotWorld(world) instanceof SquarePlotWorld)) {
PlotSquared.log("Invalid plot world: " + world); PS.log("Invalid plot world: " + world);
} else { } else {
final Plot plot = MainUtil.getPlot(world, id); final Plot plot = MainUtil.getPlot(world, id);
if (plot == null) { 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 { } else {
final Location pos1 = MainUtil.getPlotBottomLoc(world, plot.id).add(1, 0, 1); final Location pos1 = MainUtil.getPlotBottomLoc(world, plot.id).add(1, 0, 1);
final Location pos2 = MainUtil.getPlotTopLoc(world, plot.id); final Location pos2 = MainUtil.getPlotTopLoc(world, plot.id);
@ -67,8 +67,8 @@ public class DebugClear extends SubCommand {
@Override @Override
public void run() { public void run() {
MainUtil.runners.remove(plot); MainUtil.runners.remove(plot);
PlotSquared.log("Plot " + plot.getId().toString() + " cleared."); PS.log("Plot " + plot.getId().toString() + " cleared.");
PlotSquared.log("&aDone!"); PS.log("&aDone!");
} }
}); });
} }
@ -79,7 +79,7 @@ public class DebugClear extends SubCommand {
} }
final Location loc = plr.getLocation(); final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc); 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); return sendMessage(plr, C.NOT_IN_PLOT);
} }
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) {

View File

@ -20,26 +20,36 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.BukkitHybridUtils; import com.intellectualcrafters.plot.generator.BukkitHybridUtils;
import com.intellectualcrafters.plot.generator.HybridUtils; 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.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.ExpireManager; import com.intellectualcrafters.plot.util.ExpireManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; 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 class DebugExec extends SubCommand {
public DebugExec() { public DebugExec() {
@ -82,11 +92,11 @@ public class DebugExec extends SubCommand {
} }
case "remove-flag": { case "remove-flag": {
if (args.length != 2) { 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; return false;
} }
String flag = args[1]; String flag = args[1];
for (Plot plot : PlotSquared.getInstance().getPlots()) { for (Plot plot : PS.get().getPlots()) {
if (FlagManager.getPlotFlag(plot, flag) != null) { if (FlagManager.getPlotFlag(plot, flag) != null) {
FlagManager.removePlotFlag(plot, flag); FlagManager.removePlotFlag(plot, flag);
} }
@ -95,11 +105,11 @@ public class DebugExec extends SubCommand {
} }
case "start-rgar": { case "start-rgar": {
if (args.length != 2) { if (args.length != 2) {
PlotSquared.log("&cInvalid syntax: /plot debugexec start-rgar <world>"); PS.log("&cInvalid syntax: /plot debugexec start-rgar <world>");
return false; return false;
} }
boolean result; boolean result;
if (!PlotSquared.getInstance().isPlotWorld(args[1])) { if (!PS.get().isPlotWorld(args[1])) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
return false; return false;
} }
@ -110,26 +120,26 @@ public class DebugExec extends SubCommand {
result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0); result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0);
} }
if (!result) { 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 false;
} }
return true; return true;
} }
case "stop-rgar": { case "stop-rgar": {
if (((BukkitHybridUtils)(HybridUtils.manager)).task == 0) { if (((BukkitHybridUtils)(HybridUtils.manager)).task == 0) {
PlotSquared.log("&cTASK NOT RUNNING!"); PS.log("&cTASK NOT RUNNING!");
return false; return false;
} }
((BukkitHybridUtils)(HybridUtils.manager)).task = 0; ((BukkitHybridUtils)(HybridUtils.manager)).task = 0;
Bukkit.getScheduler().cancelTask(((BukkitHybridUtils)(HybridUtils.manager)).task); Bukkit.getScheduler().cancelTask(((BukkitHybridUtils)(HybridUtils.manager)).task);
PlotSquared.log("&cCancelling task..."); PS.log("&cCancelling task...");
while (BukkitHybridUtils.chunks.size() > 0) { while (BukkitHybridUtils.chunks.size() > 0) {
ChunkLoc chunk = BukkitHybridUtils.chunks.get(0); ChunkLoc chunk = BukkitHybridUtils.chunks.get(0);
BukkitHybridUtils.chunks.remove(0); BukkitHybridUtils.chunks.remove(0);
HybridUtils.manager.regenerateRoad(BukkitHybridUtils.world, chunk, 0); HybridUtils.manager.regenerateRoad(BukkitHybridUtils.world, chunk, 0);
ChunkManager.manager.unloadChunk(BukkitHybridUtils.world, chunk); ChunkManager.manager.unloadChunk(BukkitHybridUtils.world, chunk);
} }
PlotSquared.log("&cCancelled!"); PS.log("&cCancelled!");
return true; return true;
} }
case "start-expire": { case "start-expire": {
@ -197,7 +207,7 @@ public class DebugExec extends SubCommand {
return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run"); return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run");
} }
final String world = args[1]; 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]); return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
} }
final ArrayList<ChunkLoc> empty = new ArrayList<>(); final ArrayList<ChunkLoc> empty = new ArrayList<>();
@ -208,7 +218,7 @@ public class DebugExec extends SubCommand {
Trim.sendMessage(" - MCA #: " + empty.size()); Trim.sendMessage(" - MCA #: " + empty.size());
Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)"); Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)");
Trim.sendMessage("Exporting log for manual approval..."); 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; PrintWriter writer;
try { try {
writer = new PrintWriter(file); writer = new PrintWriter(file);

View File

@ -20,7 +20,11 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag; 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.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; 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 class DebugFixFlags extends SubCommand {
public DebugFixFlags() { public DebugFixFlags() {
super(Command.DEBUGFIXFLAGS, "Attempt to fix all flags for a world", "debugclear", CommandCategory.DEBUG, false); 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; return false;
} }
final String world = args[0]; 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]); MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD, args[0]);
return false; return false;
} }
MainUtil.sendMessage(plr, "&8--- &6Starting task &8 ---"); 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; final HashMap<String, Flag> flags = plot.settings.flags;
Iterator<Entry<String, Flag>> i = flags.entrySet().iterator(); Iterator<Entry<String, Flag>> i = flags.entrySet().iterator();
boolean changed = false; boolean changed = false;
@ -66,7 +66,7 @@ public class DebugFixFlags extends SubCommand {
} }
} }
if (changed) { if (changed) {
DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); DBFunc.setFlags(plot, plot.settings.flags.values());
} }
} }
MainUtil.sendMessage(plr, "&aDone!"); MainUtil.sendMessage(plr, "&aDone!");

View File

@ -22,7 +22,7 @@ package com.intellectualcrafters.plot.commands;
import java.lang.reflect.Field; 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.database.DBFunc;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
@ -39,13 +39,13 @@ public class DebugLoadTest extends SubCommand {
public boolean execute(final PlotPlayer plr, final String... args) { public boolean execute(final PlotPlayer plr, final String... args) {
if (plr == null) { if (plr == null) {
try { try {
final Field fPlots = PlotSquared.class.getDeclaredField("plots"); final Field fPlots = PS.class.getDeclaredField("plots");
fPlots.setAccessible(true); fPlots.setAccessible(true);
fPlots.set(null, DBFunc.getPlots()); fPlots.set(null, DBFunc.getPlots());
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log("&3===FAILED&3==="); PS.log("&3===FAILED&3===");
e.printStackTrace(); e.printStackTrace();
PlotSquared.log("&3===END OF STACKTRACE==="); PS.log("&3===END OF STACKTRACE===");
} }
} else { } else {
MainUtil.sendMessage(plr, "&6This command can only be executed by console as it has been deemed unsafe if abused.."); 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; 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.C;
import com.intellectualcrafters.plot.generator.HybridPlotWorld; import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
@ -38,7 +38,7 @@ public class DebugRoadRegen extends SubCommand {
public boolean execute(final PlotPlayer player, final String... args) { public boolean execute(final PlotPlayer player, final String... args) {
final Location loc = player.getLocation(); final Location loc = player.getLocation();
final String world = loc.getWorld(); 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); return sendMessage(player, C.NOT_IN_PLOT_WORLD);
} }
final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);

View File

@ -20,14 +20,14 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.database.DBFunc;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import java.util.ArrayList;
/** /**
* @author Citymonstret * @author Citymonstret
*/ */
@ -40,7 +40,7 @@ public class DebugSaveTest extends SubCommand {
public boolean execute(final PlotPlayer plr, final String... args) { public boolean execute(final PlotPlayer plr, final String... args) {
if (plr == null) { if (plr == null) {
final ArrayList<Plot> plots = new ArrayList<Plot>(); final ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotSquared.getInstance().getPlots()); plots.addAll(PS.get().getPlots());
MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`"); MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots, new Runnable() { DBFunc.createPlotsAndData(plots, new Runnable() {
@Override @Override

View File

@ -20,7 +20,17 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.AbstractDB; 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.LowerOfflineUUIDWrapper;
import com.intellectualcrafters.plot.uuid.OfflineUUIDWrapper; import com.intellectualcrafters.plot.uuid.OfflineUUIDWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; 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 class DebugUUID extends SubCommand {
public DebugUUID() { public DebugUUID() {
@ -139,7 +140,7 @@ public class DebugUUID extends SubCommand {
final UUID uuid = UUID.fromString(s); final UUID uuid = UUID.fromString(s);
uuids.add(uuid); uuids.add(uuid);
} catch (final Exception e) { } 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); uCReverse.put(uuid2, uuid);
} }
} catch (final Throwable e) { } 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) { for (final String name : names) {
@ -215,7 +216,7 @@ public class DebugUUID extends SubCommand {
MainUtil.sendConsoleMessage("&7 - Updating plot objects"); MainUtil.sendConsoleMessage("&7 - Updating plot objects");
for (Plot plot : PlotSquared.getInstance().getPlotsRaw()) { for (Plot plot : PS.get().getPlotsRaw()) {
UUID value = uCMap.get(plot.owner); UUID value = uCMap.get(plot.owner);
if (value != null) { if (value != null) {
plot.owner = value; plot.owner = value;
@ -235,13 +236,13 @@ public class DebugUUID extends SubCommand {
database.createTables(Settings.DB.USE_MYSQL ? "mysql" : "sqlite"); database.createTables(Settings.DB.USE_MYSQL ? "mysql" : "sqlite");
if (!result) { if (!result) {
MainUtil.sendConsoleMessage("&cConversion failed! Attempting recovery"); MainUtil.sendConsoleMessage("&cConversion failed! Attempting recovery");
for (Plot plot : PlotSquared.getInstance().getPlots()) { for (Plot plot : PS.get().getPlots()) {
UUID value = uCReverse.get(plot.owner); UUID value = uCReverse.get(plot.owner);
if (value != null) { if (value != null) {
plot.owner = value; plot.owner = value;
} }
} }
database.createPlotsAndData(new ArrayList<>(PlotSquared.getInstance().getPlots()), new Runnable() { database.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() {
@Override @Override
public void run() { public void run() {
MainUtil.sendMessage(null, "&6Recovery was successful!"); MainUtil.sendMessage(null, "&6Recovery was successful!");
@ -256,19 +257,19 @@ public class DebugUUID extends SubCommand {
} }
if (newWrapper instanceof OfflineUUIDWrapper) { if (newWrapper instanceof OfflineUUIDWrapper) {
PlotSquared.getInstance().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.force-lowercase", false);
PlotSquared.getInstance().config.set("UUID.offline", true); PS.get().config.set("UUID.offline", true);
} }
else if (newWrapper instanceof LowerOfflineUUIDWrapper) { else if (newWrapper instanceof LowerOfflineUUIDWrapper) {
PlotSquared.getInstance().config.set("UUID.force-lowercase", true); PS.get().config.set("UUID.force-lowercase", true);
PlotSquared.getInstance().config.set("UUID.offline", true); PS.get().config.set("UUID.offline", true);
} }
else if (newWrapper instanceof DefaultUUIDWrapper) { else if (newWrapper instanceof DefaultUUIDWrapper) {
PlotSquared.getInstance().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.force-lowercase", false);
PlotSquared.getInstance().config.set("UUID.offline", false); PS.get().config.set("UUID.offline", false);
} }
try { try {
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile); PS.get().config.save(PS.get().configFile);
} }
catch (Exception e) { catch (Exception e) {
MainUtil.sendConsoleMessage("Could not save configuration. It will need to be manuall set!"); 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() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.getInstance().getPlots()); ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
database.createPlotsAndData(plots, new Runnable() { database.createPlotsAndData(plots, new Runnable() {
@Override @Override
public void run() { public void run() {

View File

@ -20,7 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; 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.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld; 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; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
public class Delete extends SubCommand { public class Delete extends SubCommand {
@ -50,7 +54,7 @@ public class Delete extends SubCommand {
return !sendMessage(plr, C.NO_PLOT_PERMS); return !sendMessage(plr, C.NO_PLOT_PERMS);
} }
assert plot != null; assert plot != null;
final PlotWorld pWorld = PlotSquared.getInstance().getPlotWorld(plot.world); final PlotWorld pWorld = PS.get().getPlotWorld(plot.world);
if (MainUtil.runners.containsKey(plot)) { if (MainUtil.runners.containsKey(plot)) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false; return false;
@ -65,7 +69,7 @@ public class Delete extends SubCommand {
sendMessage(plr, C.ADDED_BALANCE, c + ""); 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 long start = System.currentTimeMillis();
final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() { final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() {
@Override @Override
@ -76,7 +80,7 @@ public class Delete extends SubCommand {
if (!result) { if (!result) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); 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"))) { if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) {

View File

@ -20,7 +20,9 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location; 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.Permissions;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import java.util.UUID;
public class Deny extends SubCommand { public class Deny extends SubCommand {
public Deny() { public Deny() {
super(Command.DENY, "Deny a user from a plot", "deny <player>", CommandCategory.ACTIONS, true); 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]); MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false; return false;
} }
if (!plot.denied.contains(uuid)) {
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.ALREADY_OWNER); MainUtil.sendMessage(plr, C.ALREADY_OWNER);
return false; return false;
} }
if (plot.trusted.contains(uuid)) {
plot.trusted.remove(uuid); if (plot.denied.contains(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 {
MainUtil.sendMessage(plr, C.ALREADY_ADDED); MainUtil.sendMessage(plr, C.ALREADY_ADDED);
return false; return false;
} }
plot.removeMember(uuid);
plot.removeTrusted(uuid);
plot.addDenied(uuid);
EventUtil.manager.callDenied(plr, plot, uuid, true);
MainUtil.sendMessage(plr, C.DENIED_ADDED); MainUtil.sendMessage(plr, C.DENIED_ADDED);
if (!uuid.equals(DBFunc.everyone)) { 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; 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()) { if ((args.length == 3) && flag.getAbstractFlag().isList()) {
final String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); final String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ");
((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value); ((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 { } else {
final boolean result = FlagManager.removePlotFlag(plot, flag.getKey()); final boolean result = FlagManager.removePlotFlag(plot, flag.getKey());
if (!result) { if (!result) {
@ -206,7 +206,7 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); MainUtil.sendMessage(player, C.FLAG_NOT_ADDED);
return false; return false;
} }
DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); DBFunc.setFlags(plot, plot.settings.flags.values());
MainUtil.sendMessage(player, C.FLAG_ADDED); MainUtil.sendMessage(player, C.FLAG_ADDED);
APlotListener.manager.plotEntry(player, plot); APlotListener.manager.plotEntry(player, plot);
return true; return true;

View File

@ -20,14 +20,14 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import java.util.ArrayList;
/** /**
* @author Citymonstret * @author Citymonstret
*/ */
@ -37,7 +37,7 @@ public class Home extends SubCommand {
} }
private Plot isAlias(final String a) { 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)) { if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p; return p;
} }
@ -47,7 +47,7 @@ public class Home extends SubCommand {
@Override @Override
public boolean execute(final PlotPlayer plr, String... args) { 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) { if (plots.size() == 1) {
MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(0)); MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(0));
return true; return true;

View File

@ -21,14 +21,12 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import com.intellectualcrafters.plot.PlotSquared;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; 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.Plot;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
@ -74,9 +71,7 @@ public class Info extends SubCommand {
plot = MainUtil.getPlotFromString(player, null, player == null); plot = MainUtil.getPlotFromString(player, null, player == null);
break; break;
default: default:
System.out.print("CHECKING: " + arg);
plot = MainUtil.getPlotFromString(player, arg, player == null); plot = MainUtil.getPlotFromString(player, arg, player == null);
System.out.print(plot);
if (args.length == 2) { if (args.length == 2) {
arg = args[1]; 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)); MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y));
return true; return true;
} }
String owner = "none";
if (plot.owner == null) {
owner = "unowned";
}
else {
owner = getPlayerList(plot.getOwners());
}
String info = C.PLOT_INFO.s(); String info = C.PLOT_INFO.s();
if (arg != null) { if (arg != null) {
info = getCaption(arg); info = getCaption(arg);
@ -207,7 +195,6 @@ public class Info extends SubCommand {
info = info.replaceAll("%flags%", Matcher.quoteReplacement(flags)); info = info.replaceAll("%flags%", Matcher.quoteReplacement(flags));
info = info.replaceAll("%build%", build + ""); info = info.replaceAll("%build%", build + "");
info = info.replaceAll("%desc%", "No description set."); info = info.replaceAll("%desc%", "No description set.");
if (info.contains("%rating%")) { if (info.contains("%rating%")) {
final String newInfo = info; final String newInfo = info;
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {

View File

@ -24,11 +24,9 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import com.intellectualcrafters.plot.PlotSquared;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringComparison; 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) { 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 < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
if (args.length < 2) { if (args.length < 2) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();

View File

@ -20,17 +20,26 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; 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 * @author Citymonstret
*/ */
@ -131,7 +140,7 @@ public class Merge extends SubCommand {
HashSet<PlotId> multiPlots = new HashSet<>(); HashSet<PlotId> multiPlots = new HashSet<>();
final UUID u1 = plot.owner; final UUID u1 = plot.owner;
for (final PlotId myid : plots) { 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) { if (myplot == null || myplot.owner == null) {
MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false; return false;
@ -150,6 +159,10 @@ public class Merge extends SubCommand {
multiUUID.add(u2); multiUUID.add(u2);
} }
if (multiMerge) { 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) { for (final UUID uuid : multiUUID) {
PlotPlayer accepter = UUIDHandler.getPlayer(uuid); PlotPlayer accepter = UUIDHandler.getPlayer(uuid);
CmdConfirm.addPending(accepter, C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", plr.getName()), new Runnable() { 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); sendMessage(accepter, C.MERGE_NOT_VALID);
return; return;
} }
final PlotWorld plotWorld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotWorld = PS.get().getPlotWorld(world);
if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) { if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE; double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost; cost = plots.size() * cost;
@ -192,7 +205,7 @@ public class Merge extends SubCommand {
MainUtil.sendMessage(plr, C.MERGE_REQUESTED); MainUtil.sendMessage(plr, C.MERGE_REQUESTED);
return true; return true;
} }
final PlotWorld plotWorld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotWorld = PS.get().getPlotWorld(world);
if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) { if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE; double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost; cost = plots.size() * cost;

View File

@ -20,9 +20,13 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.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.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
@ -48,7 +52,7 @@ public class Move extends SubCommand {
if (plot1 == null) { if (plot1 == null) {
return !sendMessage(plr, C.NOT_IN_PLOT); 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); MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
@ -61,8 +65,8 @@ public class Move extends SubCommand {
} }
String world2; String world2;
if (args.length == 2) { if (args.length == 2) {
PlotWorld other = PlotSquared.getInstance().getPlotWorld(args[1]); PlotWorld other = PS.get().getPlotWorld(args[1]);
PlotWorld current = PlotSquared.getInstance().getPlotWorld(loc.getWorld()); PlotWorld current = PS.get().getPlotWorld(loc.getWorld());
if (other == null || current == null || !other.equals(current)) { if (other == null || current == null || !other.equals(current)) {
MainUtil.sendMessage(plr, C.PLOTWORLD_INCOMPATIBLE); MainUtil.sendMessage(plr, C.PLOTWORLD_INCOMPATIBLE);
return false; return false;

View File

@ -32,6 +32,7 @@ import com.intellectualcrafters.plot.object.PlotItemStack;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
public class MusicSubcommand extends SubCommand { public class MusicSubcommand extends SubCommand {
public MusicSubcommand() { public MusicSubcommand() {
@ -52,8 +53,19 @@ public class MusicSubcommand extends SubCommand {
PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") {
public boolean onClick(int index) { public boolean onClick(int index) {
PlotItemStack item = getItem(index); PlotItemStack item = getItem(index);
FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("music"), item.id)); 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); PlotListener.manager.plotEntry(player, plot);
}
}, 1);
close(); close();
return false; return false;
} }
@ -66,6 +78,11 @@ public class MusicSubcommand extends SubCommand {
inv.setItem(index, item); inv.setItem(index, item);
index++; 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(); inv.openInventory();
return true; 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; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Plot; 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.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; 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" }) @SuppressWarnings({ "javadoc" })
public class Purge extends SubCommand { public class Purge extends SubCommand {
public Purge() { public Purge() {
@ -91,7 +91,7 @@ public class Purge extends SubCommand {
return false; return false;
} }
final String worldname = args[1]; final String worldname = args[1];
if (!PlotSquared.getInstance().getAllPlotsRaw().containsKey(worldname)) { if (!PS.get().getAllPlotsRaw().containsKey(worldname)) {
MainUtil.sendMessage(plr, "INVALID WORLD"); MainUtil.sendMessage(plr, "INVALID WORLD");
return false; return false;
} }
@ -107,7 +107,7 @@ public class Purge extends SubCommand {
return finishPurge(DBid == Integer.MAX_VALUE ? 1 : 0); return finishPurge(DBid == Integer.MAX_VALUE ? 1 : 0);
} }
if (arg.equals("all")) { 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(); int length = ids.size();
if (length == 0) { if (length == 0) {
return MainUtil.sendMessage(null, "&cNo plots found"); return MainUtil.sendMessage(null, "&cNo plots found");
@ -116,7 +116,7 @@ public class Purge extends SubCommand {
return finishPurge(length); return finishPurge(length);
} }
if (arg.equals("unknown")) { 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<>(); final Set<PlotId> ids = new HashSet<>();
for (final Plot plot : plots) { for (final Plot plot : plots) {
if (plot.owner != null) { if (plot.owner != null) {
@ -134,7 +134,7 @@ public class Purge extends SubCommand {
return finishPurge(length); return finishPurge(length);
} }
if (arg.equals("unowned")) { 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<>(); final Set<PlotId> ids = new HashSet<>();
for (final Plot plot : plots) { for (final Plot plot : plots) {
if (plot.owner == null) { if (plot.owner == null) {
@ -150,7 +150,7 @@ public class Purge extends SubCommand {
} }
final UUID uuid = UUIDHandler.getUUID(args[0]); final UUID uuid = UUIDHandler.getUUID(args[0]);
if (uuid != null) { 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<>(); final Set<PlotId> ids = new HashSet<>();
for (final Plot plot : plots) { for (final Plot plot : plots) {
ids.add(plot.id); ids.add(plot.id);

View File

@ -20,22 +20,30 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID; 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 { public class Rate extends SubCommand {
/* /*
* String cmd, String permission, String description, String usage, String * 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) { public boolean execute(final PlotPlayer player, final String... args) {
if (args.length == 1) { if (args.length == 1) {
if (args[0].equalsIgnoreCase("next")) { 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>() { Collections.sort(plots, new Comparator<Plot>() {
@Override @Override
public int compare(Plot p1, Plot p2) { public int compare(Plot p1, Plot p2) {
int v1 = 0; double v1 = 0;
int v2 = 0; double v2 = 0;
if (p1.settings.ratings != null) { if (p1.settings.ratings != null) {
for (Entry<UUID, Integer> entry : p1.settings.ratings.entrySet()) { for (Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
v1 -= 11 - entry.getValue(); v1 -= 11 - entry.getValue().getAverageRating();
} }
} }
if (p2.settings.ratings != null) { if (p2.settings.ratings != null) {
for (Entry<UUID, Integer> entry : p2.settings.ratings.entrySet()) { for (Entry<UUID, Rating> entry : p2.getRatings().entrySet()) {
v2 -= 11 - entry.getValue(); v2 -= 11 - entry.getValue().getAverageRating();
} }
} }
return v2 - v1; return v2 > v1 ? 1 : -1;
} }
}); });
UUID uuid = player.getUUID(); UUID uuid = player.getUUID();
@ -110,9 +118,17 @@ public class Rate extends SubCommand {
index.increment(); index.increment();
if (index.intValue() >= Settings.RATING_CATEGORIES.size()) { if (index.intValue() >= Settings.RATING_CATEGORIES.size()) {
close(); close();
// set rating! // handle ratings
plot.settings.ratings.put(player.getUUID(), rating.intValue()); int rV = rating.intValue();
DBFunc.setRating(plot, player.getUUID(), 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());
sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
return false; return false;

View File

@ -20,7 +20,9 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.generator.HybridPlotManager; import com.intellectualcrafters.plot.generator.HybridPlotManager;
import com.intellectualcrafters.plot.generator.HybridUtils; 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.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import java.util.List;
public class RegenAllRoads extends SubCommand { public class RegenAllRoads extends SubCommand {
public RegenAllRoads() { public RegenAllRoads() {
super(Command.REGENALLROADS, "Regenerate all roads in the map using the set road schematic", "rgar", CommandCategory.DEBUG, false); 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 String name = args[0];
final PlotManager manager = PlotSquared.getInstance().getPlotManager(name); final PlotManager manager = PS.get().getPlotManager(name);
if ((manager == null) || !(manager instanceof HybridPlotManager)) { if ((manager == null) || !(manager instanceof HybridPlotManager)) {
sendMessage(player, C.NOT_VALID_PLOT_WORLD); sendMessage(player, C.NOT_VALID_PLOT_WORLD);
return false; return false;
} }
final List<ChunkLoc> chunks = ChunkManager.manager.getChunkChunks(name); final List<ChunkLoc> chunks = ChunkManager.manager.getChunkChunks(name);
PlotSquared.log("&cIf no schematic is set, the following will not do anything"); PS.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"); PS.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)); PS.log("&6Potential chunks to update: &7" + (chunks.size() * 1024));
PlotSquared.log("&6Estimated time: &7" + (chunks.size()) + " seconds"); PS.log("&6Estimated time: &7" + (chunks.size()) + " seconds");
final boolean result = HybridUtils.manager.scheduleRoadUpdate(name, height); final boolean result = HybridUtils.manager.scheduleRoadUpdate(name, height);
if (!result) { 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 false;
} }
return true; return true;

View File

@ -20,7 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld; import com.intellectualcrafters.plot.object.PlotWorld;
@ -36,12 +36,12 @@ public class Reload extends SubCommand {
try { try {
// The following won't affect world generation, as that has to be // The following won't affect world generation, as that has to be
// loaded during startup unfortunately. // loaded during startup unfortunately.
PlotSquared.getInstance().config.load(PlotSquared.getInstance().configFile); PS.get().config.load(PS.get().configFile);
PlotSquared.getInstance().setupConfig(); PS.get().setupConfig();
C.setupTranslations(); C.load(PS.get().translationFile);
for (final String pw : PlotSquared.getInstance().getPlotWorlds()) { for (final String pw : PS.get().getPlotWorlds()) {
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(pw); final PlotWorld plotworld = PS.get().getPlotWorld(pw);
plotworld.loadDefaultConfiguration(PlotSquared.getInstance().config.getConfigurationSection("worlds." + pw)); plotworld.loadDefaultConfiguration(PS.get().config.getConfigurationSection("worlds." + pw));
} }
MainUtil.sendMessage(plr, C.RELOADED_CONFIGS); MainUtil.sendMessage(plr, C.RELOADED_CONFIGS);
} catch (final Exception e) { } catch (final Exception e) {

View File

@ -20,11 +20,11 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.Iterator; import java.util.ArrayList;
import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
@ -58,77 +58,59 @@ public class Remove extends SubCommand {
} }
int count = 0; int count = 0;
if (args[0].equals("unknown")) { if (args[0].equals("unknown")) {
Iterator<UUID> i = plot.members.iterator(); ArrayList<UUID> toRemove = new ArrayList<>();
while (i.hasNext()) { HashSet<UUID> all = new HashSet<>();
UUID uuid = i.next(); all.addAll(plot.members);
all.addAll(plot.trusted);
all.addAll(plot.denied);
for (UUID uuid : all) {
if (UUIDHandler.getName(uuid) == null) { if (UUIDHandler.getName(uuid) == null) {
DBFunc.removeMember(plot.world, plot, uuid); toRemove.add(uuid);
i.remove();
count++; count++;
} }
} }
i = plot.trusted.iterator(); for (UUID uuid : toRemove) {
while (i.hasNext()) { plot.removeDenied(uuid);
UUID uuid = i.next(); plot.removeTrusted(uuid);
if (UUIDHandler.getName(uuid) == null) { plot.removeMember(uuid);
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++;
}
} }
} }
else if (args[0].equals("*")){ else if (args[0].equals("*")){
Iterator<UUID> i = plot.members.iterator(); ArrayList<UUID> toRemove = new ArrayList<>();
while (i.hasNext()) { HashSet<UUID> all = new HashSet<>();
UUID uuid = i.next(); all.addAll(plot.members);
DBFunc.removeMember(plot.world, plot, uuid); all.addAll(plot.trusted);
i.remove(); all.addAll(plot.denied);
for (UUID uuid : all) {
toRemove.add(uuid);
count++; count++;
} }
i = plot.trusted.iterator(); for (UUID uuid : toRemove) {
while (i.hasNext()) { plot.removeDenied(uuid);
UUID uuid = i.next(); plot.removeTrusted(uuid);
DBFunc.removeTrusted(plot.world, plot, uuid); plot.removeMember(uuid);
i.remove();
count++;
}
i = plot.denied.iterator();
while (i.hasNext()) {
UUID uuid = i.next();
DBFunc.removeDenied(plot.world, plot, uuid);
i.remove();
count++;
} }
} }
else { else {
UUID uuid = UUIDHandler.getUUID(args[0]); UUID uuid = UUIDHandler.getUUID(args[0]);
if (uuid != null) { if (uuid != null) {
if (plot.trusted.contains(uuid)) { if (plot.trusted.contains(uuid)) {
DBFunc.removeTrusted(plot.world, plot, uuid); if (plot.removeTrusted(uuid)) {
plot.trusted.remove(uuid);
count++; count++;
} }
}
else if (plot.members.contains(uuid)) { else if (plot.members.contains(uuid)) {
DBFunc.removeMember(plot.world, plot, uuid); if (plot.removeMember(uuid)) {
plot.members.remove(uuid);
count++; count++;
} }
}
else if (plot.denied.contains(uuid)) { else if (plot.denied.contains(uuid)) {
DBFunc.removeDenied(plot.world, plot, uuid); if (plot.removeDenied(uuid)) {
plot.denied.remove(uuid);
count++; count++;
} }
} }
} }
}
if (count == 0) { if (count == 0) {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false; return false;

View File

@ -20,22 +20,26 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; 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.DataCollection;
import com.intellectualcrafters.plot.util.SchematicHandler.Dimension; import com.intellectualcrafters.plot.util.SchematicHandler.Dimension;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.bukkit.BukkitUtil; import com.intellectualcrafters.plot.util.bukkit.BukkitUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
public class SchematicCmd extends SubCommand { public class SchematicCmd extends SubCommand {
private int counter = 0; private int counter = 0;
private boolean running = false; private boolean running = false;
@ -58,7 +62,7 @@ public class SchematicCmd extends SubCommand {
switch (arg) { switch (arg) {
case "paste": { case "paste": {
if (plr == null) { if (plr == null) {
PlotSquared.log(C.IS_CONSOLE.s()); PS.log(C.IS_CONSOLE.s());
return false; return false;
} }
if (!Permissions.hasPermission(plr, "plots.schematic.paste")) { if (!Permissions.hasPermission(plr, "plots.schematic.paste")) {
@ -134,7 +138,7 @@ public class SchematicCmd extends SubCommand {
SchematicHandler.manager.pasteStates(schematic, plot, 0, 0); SchematicHandler.manager.pasteStates(schematic, plot, 0, 0);
sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS);
SchematicCmd.this.running = false; SchematicCmd.this.running = false;
PlotSquared.getInstance().TASK.cancelTask(SchematicCmd.this.task); PS.get().TASK.cancelTask(SchematicCmd.this.task);
return; return;
} }
final int end = Math.min(start + 5000, blen); final int end = Math.min(start + 5000, blen);
@ -155,7 +159,7 @@ public class SchematicCmd extends SubCommand {
} }
case "test": { case "test": {
if (plr == null) { if (plr == null) {
PlotSquared.log(C.IS_CONSOLE.s()); PS.log(C.IS_CONSOLE.s());
return false; return false;
} }
if (!Permissions.hasPermission(plr, "plots.schematic.test")) { 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>"); MainUtil.sendMessage(null, "&cNeed world arg. Use &7/plots sch exportall <world>");
return false; 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)) { if ((plotmap == null) || (plotmap.size() == 0)) {
MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall <world>"); MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall <world>");
return false; return false;
@ -215,8 +219,8 @@ public class SchematicCmd extends SubCommand {
return false; return false;
} }
else { else {
PlotSquared.log("&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); PS.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: &7Found &c" + plotmap.size() + "&7 plots...");
} }
break; break;
} }
@ -250,11 +254,11 @@ public class SchematicCmd extends SubCommand {
world = args[1]; world = args[1];
final String[] split = args[2].split(";"); final String[] split = args[2].split(";");
final PlotId i = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); 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>"); MainUtil.sendMessage(null, "&cInvalid world or id. Use &7/plots sch save <world> <id>");
return false; return false;
} }
p2 = PlotSquared.getInstance().getPlots(world).get(i); p2 = PS.get().getPlots(world).get(i);
} catch (final Exception e) { } catch (final Exception e) {
MainUtil.sendMessage(null, "&cInvalid world or id. Use &7/plots sch save <world> <id>"); MainUtil.sendMessage(null, "&cInvalid world or id. Use &7/plots sch save <world> <id>");
return false; return false;

View File

@ -20,22 +20,34 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Configuration; import com.intellectualcrafters.plot.config.Configuration;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.AbstractFlag; import com.intellectualcrafters.plot.flag.AbstractFlag;
import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.listeners.APlotListener; import com.intellectualcrafters.plot.listeners.APlotListener;
import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.object.BlockLoc;
import com.intellectualcrafters.plot.util.*; 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 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 * @author Citymonstret
@ -66,10 +78,10 @@ public class Set extends SubCommand {
} }
} }
if (args.length < 1) { if (args.length < 1) {
PlotManager manager = PlotSquared.getInstance().getPlotManager(loc.getWorld()); PlotManager manager = PS.get().getPlotManager(loc.getWorld());
ArrayList<String> newValues = new ArrayList<String>(); ArrayList<String> newValues = new ArrayList<String>();
newValues.addAll(Arrays.asList(values)); 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)); MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(newValues));
return false; return false;
} }
@ -141,8 +153,7 @@ public class Set extends SubCommand {
} }
if (args.length > 1) { if (args.length > 1) {
if (args[1].equalsIgnoreCase("none")) { if (args[1].equalsIgnoreCase("none")) {
plot.settings.setPosition(null); plot.setHome(null);
DBFunc.setPosition(loc.getWorld(), plot, "");
return true; return true;
} }
return MainUtil.sendMessage(plr, C.HOME_ARGUMENT); return MainUtil.sendMessage(plr, C.HOME_ARGUMENT);
@ -153,8 +164,7 @@ public class Set extends SubCommand {
base.setY(0); base.setY(0);
final Location relative = plr.getLocation().subtract(base.getX(), base.getY(), base.getZ()); 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()); final BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ(), relative.getYaw(), relative.getPitch());
plot.settings.setPosition(blockloc); plot.setHome(blockloc);
DBFunc.setPosition(loc.getWorld(), plot, blockloc.toString());
return MainUtil.sendMessage(plr, C.POSITION_SET); return MainUtil.sendMessage(plr, C.POSITION_SET);
} }
if (args[0].equalsIgnoreCase("alias")) { if (args[0].equalsIgnoreCase("alias")) {
@ -171,7 +181,7 @@ public class Set extends SubCommand {
MainUtil.sendMessage(plr, C.ALIAS_TOO_LONG); MainUtil.sendMessage(plr, C.ALIAS_TOO_LONG);
return false; 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)) { if (p.settings.getAlias().equalsIgnoreCase(alias)) {
MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN); MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
return false; return false;
@ -181,7 +191,7 @@ public class Set extends SubCommand {
return false; return false;
} }
} }
DBFunc.setAlias(loc.getWorld(), plot, alias); plot.setAlias(alias);
MainUtil.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); MainUtil.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
return true; return true;
} }
@ -211,14 +221,14 @@ public class Set extends SubCommand {
MainUtil.sendMessage(plr, getBiomeList(BlockManager.manager.getBiomeList())); MainUtil.sendMessage(plr, getBiomeList(BlockManager.manager.getBiomeList()));
return true; 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()); MainUtil.sendMessage(plr, C.BIOME_SET_TO.s() + args[1].toLowerCase());
return true; return true;
} }
// Get components // Get components
final String world = plr.getLocation().getWorld(); final String world = plr.getLocation().getWorld();
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotworld = PS.get().getPlotWorld(world);
final PlotManager manager = PlotSquared.getInstance().getPlotManager(world); final PlotManager manager = PS.get().getPlotManager(world);
final String[] components = manager.getPlotComponents(plotworld, plot.id); final String[] components = manager.getPlotComponents(plotworld, plot.id);
for (final String component : components) { for (final String component : components) {
if (component.equalsIgnoreCase(args[0])) { if (component.equalsIgnoreCase(args[0])) {
@ -231,10 +241,6 @@ public class Set extends SubCommand {
MainUtil.sendMessage(plr, C.NEED_BLOCK); MainUtil.sendMessage(plr, C.NEED_BLOCK);
return true; return true;
} }
// if (!Configuration.BLOCKLIST.validateValue(args[1])) {
// MainUtil.sendMessage(plr, C.NOT_VALID_BLOCK, args[1]);
// return false;
// }
String[] split = args[1].split(","); String[] split = args[1].split(",");
blocks = Configuration.BLOCKLIST.parseString(args[1]); blocks = Configuration.BLOCKLIST.parseString(args[1]);
for (int i = 0; i < blocks.length; i++) { for (int i = 0; i < blocks.length; i++) {
@ -308,7 +314,7 @@ public class Set extends SubCommand {
} }
ArrayList<String> newValues = new ArrayList<String>(); ArrayList<String> newValues = new ArrayList<String>();
newValues.addAll(Arrays.asList(values)); 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)); MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(newValues));
return false; return false;
} }

View File

@ -20,7 +20,10 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; 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.Permissions;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import java.util.ArrayList;
import java.util.UUID;
public class SetOwner extends SubCommand { public class SetOwner extends SubCommand {
public SetOwner() { public SetOwner() {
super("setowner", "plots.set.owner", "Set the plot owner", "setowner <player>", "so", CommandCategory.ACTIONS, true); 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(); final String world = loc.getWorld();
for (final PlotId id : plots) { 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]); final UUID uuid = getUUID(args[0]);
if (uuid == null) { if (uuid == null) {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false; return false;
} }
current.owner = uuid; current.owner = uuid;
PlotSquared.getInstance().updatePlot(current); PS.get().updatePlot(current);
DBFunc.setOwner(current, current.owner); DBFunc.setOwner(current, current.owner);
} }
MainUtil.setSign(args[0], plot); MainUtil.setSign(args[0], plot);

View File

@ -20,7 +20,9 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; 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.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import org.apache.commons.lang.StringUtils;
/** /**
* @author Citymonstret * @author Citymonstret
@ -55,7 +56,7 @@ public class TP extends SubCommand {
world = args[1]; world = args[1];
} }
} }
if (!PlotSquared.getInstance().isPlotWorld(world)) { if (!PS.get().isPlotWorld(world)) {
MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD); MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
} }
@ -85,14 +86,14 @@ public class TP extends SubCommand {
} }
final PlotPlayer player = UUIDHandler.getPlayer(a); final PlotPlayer player = UUIDHandler.getPlayer(a);
if (player != null) { 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()]); final Plot[] plots = plotMainPlots.toArray(new Plot[plotMainPlots.size()]);
if (plots.length > index) { if (plots.length > index) {
return plots[index]; return plots[index];
} }
return null; 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)) { if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p; return p;
} }

View File

@ -20,7 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
@ -35,7 +35,7 @@ public class Target extends SubCommand {
@Override @Override
public boolean execute(final PlotPlayer plr, final String... args) { public boolean execute(final PlotPlayer plr, final String... args) {
final Location ploc = plr.getLocation(); 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); MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
} }

View File

@ -20,17 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -40,6 +29,21 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; 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 class Template extends SubCommand {
public Template() { public Template() {
super("template", "plots.admin", "Create or use a world template", "template", "", CommandCategory.DEBUG, false); 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) { public static boolean extractAllFiles(String world, String template) {
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
try { 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()) { if (!folder.exists()) {
return false; return false;
} }
File input = new File(folder + File.separator + template + ".template"); File input = new File(folder + File.separator + template + ".template");
File output = PlotSquared.getInstance().IMP.getDirectory(); File output = PS.get().IMP.getDirectory();
if (!output.exists()) { if (!output.exists()) {
output.mkdirs(); output.mkdirs();
} }
@ -81,7 +85,7 @@ public class Template extends SubCommand {
} }
public static byte[] getBytes(PlotWorld plotworld) { 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(); YamlConfiguration config = new YamlConfiguration();
String generator = SetupUtils.manager.getGenerator(plotworld); String generator = SetupUtils.manager.getGenerator(plotworld);
if (generator != null) { if (generator != null) {
@ -94,7 +98,7 @@ public class Template extends SubCommand {
} }
public static void zipAll(final String world, Set<FileBytes> files) throws IOException { 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(); output.mkdirs();
FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template"); FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template");
ZipOutputStream zos = new ZipOutputStream(fos); 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>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template import <world> <template>");
return false; return false;
} }
if (PlotSquared.getInstance().isPlotWorld(world)) { if (PS.get().isPlotWorld(world)) {
MainUtil.sendMessage(plr, C.SETUP_WORLD_TAKEN, world); MainUtil.sendMessage(plr, C.SETUP_WORLD_TAKEN, world);
return false; return false;
} }
@ -140,12 +144,12 @@ public class Template extends SubCommand {
MainUtil.sendMessage(plr, "&cInvalid template file: " + args[2] +".template"); MainUtil.sendMessage(plr, "&cInvalid template file: " + args[2] +".template");
return false; 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); YamlConfiguration worldConfig = YamlConfiguration.loadConfiguration(worldFile);
PlotSquared.getInstance().config.set("worlds." + world, worldConfig.get("")); PS.get().config.set("worlds." + world, worldConfig.get(""));
try { try {
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile); PS.get().config.save(PS.get().configFile);
PlotSquared.getInstance().config.load(PlotSquared.getInstance().configFile); PS.get().config.load(PS.get().configFile);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -180,12 +184,12 @@ public class Template extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export <world>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export <world>");
return false; return false;
} }
final PlotWorld plotworld = PlotSquared.getInstance().getPlotWorld(world); final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (!BlockManager.manager.isWorld(world) || (plotworld == null)) { if (!BlockManager.manager.isWorld(world) || (plotworld == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false; return false;
} }
final PlotManager manager = PlotSquared.getInstance().getPlotManager(world); final PlotManager manager = PS.get().getPlotManager(world);
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {

View File

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

View File

@ -20,7 +20,9 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.config.C;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location; 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.Permissions;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; import com.intellectualcrafters.plot.util.bukkit.UUIDHandler;
import java.util.UUID;
public class Trust extends SubCommand { public class Trust extends SubCommand {
public Trust() { public Trust() {
super(Command.TRUST, "Allow a player to build in a plot", "trust <player>", CommandCategory.ACTIONS, true); 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]); MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false; return false;
} }
if (!plot.trusted.contains(uuid)) {
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.ALREADY_OWNER); MainUtil.sendMessage(plr, C.ALREADY_OWNER);
return false; return false;
} }
if (plot.members.contains(uuid)) {
plot.members.remove(uuid); if (plot.trusted.contains(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 {
MainUtil.sendMessage(plr, C.ALREADY_ADDED); MainUtil.sendMessage(plr, C.ALREADY_ADDED);
return false; return false;
} }
if (plot.members.size() + plot.trusted.size() >= PlotSquared.getInstance().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) { 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); MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS);
return false; 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); MainUtil.sendMessage(plr, C.TRUSTED_ADDED);
return true; return true;
} }

View File

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

View File

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

View File

@ -20,11 +20,10 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.Iterator; import java.util.ArrayList;
import java.util.UUID; import java.util.UUID;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
@ -58,32 +57,27 @@ public class Untrust extends SubCommand {
} }
int count = 0; int count = 0;
if (args[0].equals("unknown")) { if (args[0].equals("unknown")) {
Iterator<UUID> i = plot.trusted.iterator(); ArrayList<UUID> toRemove = new ArrayList<>();
i = plot.trusted.iterator(); for (UUID uuid : plot.trusted) {
while (i.hasNext()) {
UUID uuid = i.next();
if (UUIDHandler.getName(uuid) == null) { if (UUIDHandler.getName(uuid) == null) {
DBFunc.removeTrusted(plot.world, plot, uuid); toRemove.add(uuid);
i.remove(); }
}
for (UUID uuid : toRemove) {
plot.removeTrusted(uuid);
count++; count++;
} }
} }
}
else if (args[0].equals("*")){ else if (args[0].equals("*")){
Iterator<UUID> i = plot.trusted.iterator(); for (UUID uuid : new ArrayList<>(plot.trusted)) {
while (i.hasNext()) { plot.removeTrusted(uuid);
UUID uuid = i.next();
DBFunc.removeTrusted(plot.world, plot, uuid);
i.remove();
count++; count++;
} }
} }
else { else {
UUID uuid = UUIDHandler.getUUID(args[0]); UUID uuid = UUIDHandler.getUUID(args[0]);
if (uuid != null) { if (uuid != null) {
if (plot.trusted.contains(uuid)) { if (plot.removeTrusted(uuid)) {
DBFunc.removeTrusted(plot.world, plot, uuid);
plot.trusted.remove(uuid);
count++; 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; 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.config.C;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; 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.Permissions;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; 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 class Visit extends SubCommand {
public Visit() { public Visit() {
super("visit", "plots.visit", "Visit someones plot", "visit {player} [#]", "v", CommandCategory.TELEPORT, true); 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) { public List<Plot> getPlots(final UUID uuid) {
final List<Plot> plots = new ArrayList<>(); 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)) { if (p.hasOwner() && p.isOwner(uuid)) {
plots.add(p); plots.add(p);
} }
@ -56,10 +56,10 @@ public class Visit extends SubCommand {
UUID user = UUIDHandler.getUUID(args[0]); UUID user = UUIDHandler.getUUID(args[0]);
if (user != null ) { if (user != null ) {
// do plots by username // do plots by username
plots.addAll(PlotSquared.getInstance().getPlots(user)); plots.addAll(PS.get().getPlots(user));
} else if (PlotSquared.getInstance().isPlotWorld(args[0])) { } else if (PS.get().isPlotWorld(args[0])) {
// do plots by world // do plots by world
plots.addAll(PlotSquared.getInstance().getPlots(args[0]).values()); plots.addAll(PS.get().getPlots(args[0]).values());
} }
else { else {
Plot plot = MainUtil.getPlotFromString(plr, args[0], true); Plot plot = MainUtil.getPlotFromString(plr, args[0], true);

View File

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

View File

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

View File

@ -20,48 +20,23 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.ArrayList; 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 class plugin extends SubCommand {
public static String downloads, version;
public plugin() { public plugin() {
super("plugin", "plots.use", "Show plugin information", "plugin", "version", CommandCategory.INFO, false); 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) { private static String convertToNumericString(final String str, final boolean dividers) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
for (final char c : str.toCharArray()) { for (final char c : str.toCharArray()) {
@ -93,11 +68,10 @@ public class plugin extends SubCommand {
public void run() { public void run() {
final ArrayList<String> strings = new ArrayList<String>() { final ArrayList<String> strings = new ArrayList<String>() {
{ {
add(String.format("&c>> &6PlotSquared (Version: %s)", PlotSquared.getInstance().IMP.getVersion())); add(String.format("&c>> &6PlotSquared (Version: %s)", PS.get().IMP.getVersion()));
add(String.format("&c>> &6Made by Citymonstret and Empire92")); add(String.format("&c>> &6Authors: Citymonstret and Empire92"));
add(String.format("&c>> &6Download at &lhttp://www.spigotmc.org/resources/1177")); add(String.format("&c>> &6Wiki: \n&chttps://github.com/IntellectualCrafters/PlotSquared/wiki"));
add(String.format("&c>> &cNewest Version (Spigot): %s", version)); add(String.format("&c>> &6Newest Version:\n&c" + (PS.get().update == null ? PS.get().IMP.getVersion() : PS.get().update)));
add(String.format("&c>> &cTotal Downloads (Spigot): %s", downloads));
} }
}; };
for (final String s : strings) { for (final String s : strings) {

View File

@ -20,14 +20,18 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.config; 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 org.bukkit.ChatColor;
import com.intellectualsites.translation.TranslationFile; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualsites.translation.TranslationLanguage; import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualsites.translation.TranslationManager; import com.intellectualcrafters.plot.PS;
import com.intellectualsites.translation.TranslationObject; import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualsites.translation.YamlTranslationFile;
import com.intellectualsites.translation.bukkit.BukkitTranslation;
/** /**
* Captions class. * Captions class.
@ -40,13 +44,18 @@ public enum C {
* Confirm * Confirm
*/ */
FAILED_CONFIRM("$2You have no pending actions to confirm!", "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
*/ */
MOVE_SUCCESS("$4Successfully moved plot.", "Move"), MOVE_SUCCESS("$4Successfully moved plot.", "Move"),
COPY_SUCCESS("$4Successfully copied plot.", "Move"), COPY_SUCCESS("$4Successfully copied plot.", "Move"),
REQUIRES_UNOWNED("$2The location specified is already occupied.", "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 * 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_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_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_INTERSECTION("$2The proposed area overlaps with $1%s$2 existing cluster/s", "Cluster"),
CLUSTER_ADDED("$4Successfully created the cluster.", "Cluster"), CLUSTER_ADDED("$4Successfully created the cluster.", "Cluster"),
CLUSTER_DELETED("$4Successfully deleted 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_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"),
CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"), CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"),
CLUSTER_TELEPORTING("$4Teleporting...", "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"), CLUSTER_CURRENT_PLOTID("$1Current plot: $2%s", "Cluster"),
/* /*
* Border * Border
@ -114,7 +123,7 @@ public enum C {
NOT_VALID_INBOX_INDEX("$2No comment at index %s", "Comment"), NOT_VALID_INBOX_INDEX("$2No comment at index %s", "Comment"),
INBOX_ITEM("$2 - $4%s", "Comment"), INBOX_ITEM("$2 - $4%s", "Comment"),
COMMENT_SYNTAX("$2Use /plots comment [X;Z] <%s> <comment>", "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("$2You do not have permission for that inbox", "Comment"),
NO_PERM_INBOX_MODIFY("$2You do not have permission to modify 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"), 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_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_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_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_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)\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)&-$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"), SETUP_INVALID_GENERATOR("$2Invalid generator. Possible options: %s", "Setup"),
/* /*
* Schematic Stuff * Schematic Stuff
@ -314,9 +323,9 @@ public enum C {
/* /*
* Debug * Debug
*/ */
DEUBG_HEADER("$1Debug Information\\n", "Debug"), DEUBG_HEADER("$1Debug Information&-", "Debug"),
DEBUG_SECTION("$2>> $1&l%val%", "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 * Invalid
*/ */
@ -350,7 +359,7 @@ public enum C {
PLOT_UNOWNED("$2The current plot must have an owner to perform this action", "Info"), 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_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"),
PLOT_INFO_HEADER("$3====== $1INFO $3======", false, "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_TRUSTED("$1Trusted:$2 %trusted%", "Info"),
PLOT_INFO_MEMBERS("$1Members:$2 %members%", "Info"), PLOT_INFO_MEMBERS("$1Members:$2 %members%", "Info"),
PLOT_INFO_DENIED("$1Denied:$2 %denied%", "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_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("$3====== $1Choose a Category $3======", false, "Help"),
HELP_INFO_ITEM("$1/plots help %category% $3- $2%category_desc%", "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 * Direction
*/ */
@ -478,32 +487,13 @@ public enum C {
*/ */
CUSTOM_STRING("-", "-"); CUSTOM_STRING("-", "-");
/** /**
* Special Language * Translated
*
* @see com.intellectualsites.translation.TranslationLanguage
*/ */
protected final static TranslationLanguage lang = new TranslationLanguage("PlotSquared", "this", "use"); private String s;
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;
/** /**
* Default * Default
*/ */
private String d; private String d;
/**
* Translated
*/
private String s;
/** /**
* What locale category should this translation fall under * What locale category should this translation fall under
*/ */
@ -546,40 +536,96 @@ public enum C {
this(d, true, cat.toLowerCase()); this(d, true, cat.toLowerCase());
} }
public static void setupTranslations() { public static String format(C c, Object... args) {
manager = new TranslationManager(); String m = c.s;
defaultFile = new YamlTranslationFile(BukkitTranslation.getParent(), lang, "PlotSquared", manager, true).read(); for (int i = args.length - 1 ; i >= 0; i--) {
// register everything in this class if (args[i] == null) {
for (final C c : values()) { continue;
manager.addTranslationObject(new TranslationObject(c.toString(), c.d, "", ""));
} }
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 { try {
manager.saveAll(defaultFile).saveFile(defaultFile); if (!file.exists()) {
} catch (final Exception e) { 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(); 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() { public String s() {
final String s = manager.getTranslated(toString(), lang).getTranslated().replaceAll("&-", "\n").replaceAll("\\n", "\n"); return this.s;
return s.replace("$1", COLOR_1.toString()).replace("$2", COLOR_2.toString()).replace("$3", COLOR_3.toString()).replace("$4", COLOR_4.toString());
} }
public boolean usePrefix() { public boolean usePrefix() {
@ -598,8 +644,4 @@ public enum C {
public String getCat() { public String getCat() {
return cat; return cat;
} }
public void setCat(String cat) {
this.cat = cat;
}
} }

View File

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

View File

@ -38,6 +38,13 @@ public class Settings {
public static boolean PERMISSION_CACHING = false; public static boolean PERMISSION_CACHING = false;
public static boolean CACHE_RATINGS = true; public static boolean CACHE_RATINGS = true;
public static boolean UUID_FROM_DISK = false; 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 * Ratings
*/ */

View File

@ -84,7 +84,7 @@ public interface AbstractDB {
* *
* @param plot Plot that should be deleted * @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); public void delete(final PlotCluster cluster);
@ -133,7 +133,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param merged boolean[] * @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 * Swap the settings, helpers etc. of two plots
@ -149,7 +149,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param flags flags to set (flag[]) * @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 * Set cluster flags
@ -170,7 +170,7 @@ public interface AbstractDB {
* @param plot Plot for which the alias should be set * @param plot Plot for which the alias should be set
* @param alias Plot Alias * @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 * Purgle a plot
@ -193,7 +193,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param position Plot Home Position * @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 plot Plot Object
* @param uuid Player that should be removed * @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 * @param cluster PlotCluster Object
@ -232,7 +232,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param uuid Player that should be removed * @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 plot Plot Object
* @param uuid Player that should be removed * @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 * @param cluster PlotCluster Object
@ -257,7 +257,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param uuid Player that should be added * @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 cluster
* @param uuid * @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 plot Plot Object
* @param uuid Player uuid * @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 plot Plot Object
* @param uuid Player uuid that should be added * @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 * Get Plots ratings
@ -303,7 +303,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param comment Comment to remove * @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 * Clear an inbox
@ -319,7 +319,7 @@ public interface AbstractDB {
* @param plot Plot Object * @param plot Plot Object
* @param comment Comment to add * @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 * Get Plot Comments
@ -330,7 +330,7 @@ public interface AbstractDB {
* *
* @return Plot Comments within the specified tier * @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); public void createPlotAndSettings(Plot plot);

View File

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

View File

@ -24,8 +24,6 @@ import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import com.intellectualcrafters.plot.PlotSquared;
/** /**
* Abstract Database class, serves as a base for any connection method (MySQL, SQLite, etc.) * 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 * @author tips48
*/ */
public abstract class Database { 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 ; public abstract Connection forceConnection() throws SQLException, ClassNotFoundException ;

View File

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

View File

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

View File

@ -4,8 +4,11 @@ import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; 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.Plot;
import com.intellectualcrafters.plot.object.PlotId; 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 Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException; 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; 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.DBFunc;
import com.intellectualcrafters.plot.database.SQLite; import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Location; 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.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.bukkit.UUIDHandler; 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 { public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin; 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 @Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) { public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase(); this.plugin = plugin.toLowerCase();
@ -44,57 +40,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
return DriverManager.getConnection(con, user, password); return DriverManager.getConnection(con, user, password);
// return new MySQL(plotsquared, hostname, port, database, username, password) // return new MySQL(plotsquared, hostname, port, database, username, password)
} else { } 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) {} catch (SQLException | ClassNotFoundException e) {}
return null; 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 @Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException { public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
ResultSet r; ResultSet r;
@ -106,21 +58,18 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Plots`"); stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Plots`");
r = stmt.executeQuery(); r = stmt.executeQuery();
boolean checkUUID = DBFunc.hasColumn(r, "ownerid"); boolean checkUUID = DBFunc.hasColumn(r, "ownerid");
boolean merge = !plugin.equals("plotme"); boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) { while (r.next()) {
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ")); final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("owner"); final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world")); final String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(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>()); plots.put(world, new HashMap<PlotId, Plot>());
if (merge) { 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[]>()); merges.put(world, new HashMap<PlotId,boolean[]>());
} }
} }
@ -175,7 +124,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
else { else {
UUIDHandler.add(new StringWrapper(name), owner); 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); plots.get(world).put(id, plot);
} }
@ -246,20 +195,11 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
return plots; return plots;
} }
public Location getPlotTopLocAbs(int path, int plot, final PlotId plotid) { @Override
final int px = plotid.x; public boolean accepts(String version) {
final int pz = plotid.y; if (version == null) {
final int x = (px * (path + plot)) - ((int) Math.floor(path / 2)) - 1; return true;
final int z = (pz * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 256, z);
} }
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; 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.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -47,6 +34,20 @@ import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; 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 * Created 2014-08-17 for PlotSquared
* *
@ -75,7 +76,7 @@ public class LikePlotMeConverter {
} }
private void sendMessage(final String message) { 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() { public String getPlotMePath() {
@ -118,11 +119,18 @@ public class LikePlotMeConverter {
try { try {
String dataFolder = getPlotMePath(); String dataFolder = getPlotMePath();
FileConfiguration plotConfig = getPlotMeConfig(dataFolder); FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) { if (plotConfig == null) {
return false; 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); Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
if (connection == null) { if (connection == null) {
@ -142,6 +150,7 @@ public class LikePlotMeConverter {
sendMessage(" - " + dbPrefix + "Plots"); sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig); final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (!Settings.CONVERT_PLOTME) {
sendMessage("Updating bukkit.yml"); sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml"); updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml"); updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
@ -150,27 +159,28 @@ public class LikePlotMeConverter {
try { try {
String actualWorldName = getWorld(world); String actualWorldName = getWorld(world);
final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); // final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.width", pathwidth); PS.get().config.set("worlds." + actualWorldName + ".road.width", pathwidth);
final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); // final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.size", plotsize); PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotsize);
final String wallblock = plotConfig.getString("worlds." + world + ".WallBlockId"); // final String wallblock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".wall.block", wallblock); PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallblock);
final String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); // final String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.floor", Arrays.asList(floor)); PS.get().config.set("worlds." + actualWorldName + ".plot.floor", Arrays.asList(floor));
final String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); // final String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); //
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.filling", Arrays.asList(filling)); PS.get().config.set("worlds." + actualWorldName + ".plot.filling", Arrays.asList(filling));
final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId"); final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.block", road); PS.get().config.set("worlds." + actualWorldName + ".road.block", road);
Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); // Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
if (height == null) { if (height == null) {
height = 64; height = 64;
} }
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.height", height); PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile); PS.get().config.save(PS.get().configFile);
} catch (final Exception e) { } 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"); sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
} }
} }
}
HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection); HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
@ -194,32 +204,32 @@ public class LikePlotMeConverter {
if (pathwidth == null) { if (pathwidth == null) {
pathwidth = 7; 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"); // Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if (plotsize == null) { if (plotsize == null) {
plotsize = 32; 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"); // String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); //
if (wallblock == null) { if (wallblock == null) {
wallblock = "44"; 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"); // String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); //
if (floor == null) { if (floor == null) {
floor = "2"; 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"); // String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); //
if (filling == null) { if (filling == null) {
filling = "3"; 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"); String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock");
if (road == null) { if (road == null) {
road = "5"; 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"); // Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if ((height == null) || (height == 0)) { if ((height == null) || (height == 0)) {
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); // height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
@ -227,10 +237,10 @@ public class LikePlotMeConverter {
height = 64; height = 64;
} }
} }
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".road.height", height); PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".plot.height", height); PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
PlotSquared.getInstance().config.set("worlds." + actualWorldName + ".wall.height", height); PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile); PS.get().config.save(PS.get().configFile);
} }
} catch (final Exception e) { } catch (final Exception e) {
} }
@ -238,14 +248,14 @@ public class LikePlotMeConverter {
for (final String world : plots.keySet()) { for (final String world : plots.keySet()) {
int duplicate = 0; int duplicate = 0;
for (final Plot plot : plots.get(world).values()) { 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); createdPlots.add(plot);
} else { } else {
duplicate++; duplicate++;
} }
} }
if (duplicate > 0) { 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"); sendMessage("Creating plot DB");
@ -254,16 +264,16 @@ public class LikePlotMeConverter {
@Override @Override
public void run() { public void run() {
sendMessage("&aDatabase conversion is now complete!"); sendMessage("&aDatabase conversion is now complete!");
PlotSquared.log("&c - Stop the server"); PS.log("&c - Stop the server");
PlotSquared.log("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml"); PS.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"); PS.log("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PlotSquared.log("&c - Start the server"); PS.log("&c - Start the server");
PlotSquared.getInstance().setAllPlotsRaw(DBFunc.getPlots()); PS.get().setAllPlotsRaw(DBFunc.getPlots());
} }
}); });
sendMessage("Saving configuration..."); sendMessage("Saving configuration...");
try { try {
PlotSquared.getInstance().config.save(PlotSquared.getInstance().configFile); PS.get().config.save(PS.get().configFile);
} catch (final IOException e) { } catch (final IOException e) {
sendMessage(" - &cFailed to save configuration."); sendMessage(" - &cFailed to save configuration.");
} }
@ -285,7 +295,7 @@ public class LikePlotMeConverter {
} }
final String actualWorldName = world.getName(); final String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PlotSquared.getInstance().removePlotWorld(actualWorldName); PS.get().removePlotWorld(actualWorldName);
if (MV) { if (MV) {
// unload world with MV // unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
@ -321,7 +331,8 @@ public class LikePlotMeConverter {
} }
}); });
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log("&/end/"); e.printStackTrace();
PS.log("&/end/");
} }
return true; 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 org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotCluster; import com.intellectualcrafters.plot.object.PlotCluster;
/** /**

View File

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

View File

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

View File

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

View File

@ -32,9 +32,9 @@ import com.intellectualcrafters.plot.object.Plot;
* @author Citymonstret * @author Citymonstret
* @author Empire92 * @author Empire92
*/ */
public class PlayerPlotTrustedEvent extends Event { public class PlayerPlotTrustedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Player initiator; private final Player initiator;
private final boolean added; private final boolean added;
private final UUID player; 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 * @param added true of the player was added, false if the player was removed
*/ */
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator; this.initiator = initiator;
this.plot = plot;
this.added = added; this.added = added;
this.player = player; this.player = player;
} }
@ -76,15 +76,6 @@ public class PlayerPlotTrustedEvent extends Event {
return this.player; return this.player;
} }
/**
* The plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/** /**
* The player initiating the action * 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 Citymonstret
* @author Empire92 * @author Empire92
*/ */
public class PlotFlagAddEvent extends Event implements Cancellable { public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final Flag flag; private final Flag flag;
private boolean cancelled; private boolean cancelled;
@ -46,7 +46,7 @@ public class PlotFlagAddEvent extends Event implements Cancellable {
* @param plot Plot to which the flag was added * @param plot Plot to which the flag was added
*/ */
public PlotFlagAddEvent(final Flag flag, final Plot plot) { public PlotFlagAddEvent(final Flag flag, final Plot plot) {
this.plot = plot; super(plot);
this.flag = flag; this.flag = flag;
} }
@ -54,15 +54,6 @@ public class PlotFlagAddEvent extends Event implements Cancellable {
return handlers; return handlers;
} }
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/** /**
* Get the flag involved * Get the flag involved
* *
@ -78,12 +69,12 @@ public class PlotFlagAddEvent extends Event implements Cancellable {
} }
@Override @Override
public boolean isCancelled() { public final boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(final boolean b) { public final void setCancelled(boolean cancelled) {
this.cancelled = b; this.cancelled = cancelled;
} }
} }

View File

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