Refractoring and Cleanup

Optimized some of the code where possible and removed some magic numbers as well.
This commit is contained in:
Matt
2016-02-13 20:01:18 -05:00
parent a1eec4eb0c
commit fde845e1d8
121 changed files with 5462 additions and 5803 deletions

View File

@@ -16,7 +16,56 @@ public class MemorySection implements ConfigurationSection {
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");
}
path = "";
fullPath = "";
parent = null;
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(final ConfigurationSection parent, final String path) {
if (parent == null) {
throw new NullPointerException("Parent may not be null");
}
if (path == null) {
throw new NullPointerException("Path may not be null");
}
this.path = path;
this.parent = parent;
root = parent.getRoot();
if (root == null) {
throw new NullPointerException("Path may not be orphaned");
}
fullPath = createPath(parent, path);
}
public static double toDouble(final Object obj, final double def) {
if (obj instanceof Number) {
return ((Number) obj).doubleValue();
@@ -28,7 +77,7 @@ public class MemorySection implements ConfigurationSection {
}
} else if (obj instanceof List) {
final List<?> val = ((List<?>) obj);
if (val.size() > 0) {
if (!val.isEmpty()) {
return toDouble(val.get(0), def);
}
}
@@ -46,7 +95,7 @@ public class MemorySection implements ConfigurationSection {
}
} else if (obj instanceof List) {
final List<?> val = ((List<?>) obj);
if (val.size() > 0) {
if (!val.isEmpty()) {
return toInt(val.get(0), def);
}
}
@@ -64,7 +113,7 @@ public class MemorySection implements ConfigurationSection {
}
} else if (obj instanceof List) {
final List<?> val = ((List<?>) obj);
if (val.size() > 0) {
if (!val.isEmpty()) {
return toLong(val.get(0), def);
}
}
@@ -72,87 +121,95 @@ public class MemorySection implements ConfigurationSection {
}
/**
* Creates an empty MemorySection for use as a root {@link Configuration}
* section.
* Creates a full path to the given {@link ConfigurationSection} from its
* root {@link Configuration}.
* <p>
* Note that calling this without being yourself a {@link Configuration}
* will throw an exception!
* You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}.
*
* @throws IllegalStateException Thrown if this is not a {@link
* Configuration} root.
* @param section Section to create a path for.
* @param key Name of the specified section.
* @return Full path of the section from its root.
*/
protected MemorySection() {
if (!(this instanceof Configuration)) {
throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration");
}
path = "";
fullPath = "";
parent = null;
root = (Configuration) this;
public static String createPath(final ConfigurationSection section, final String key) {
return createPath(section, key, (section == null) ? null : section.getRoot());
}
/**
* Creates an empty MemorySection with the specified parent and path.
* 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 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.
* @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.
*/
protected MemorySection(final ConfigurationSection parent, final String path) {
if (parent == null) {
throw new NullPointerException("Parent may not be null");
public static String createPath(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo) {
if (section == null) {
throw new NullPointerException("Cannot create path without a section");
}
if (path == null) {
throw new NullPointerException("Path may not be null");
}
this.path = path;
this.parent = parent;
root = parent.getRoot();
final Configuration root = section.getRoot();
if (root == null) {
throw new NullPointerException("Path may not be orphaned");
throw new IllegalStateException("Cannot create path without a root");
}
fullPath = createPath(parent, path);
final char separator = root.options().pathSeparator();
final StringBuilder builder = new StringBuilder();
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.isEmpty())) {
if (builder.length() > 0) {
builder.append(separator);
}
builder.append(key);
}
return builder.toString();
}
@Override
public Set<String> getKeys(final boolean deep) {
final Set<String> result = new LinkedHashSet<>();
final Configuration root = getRoot();
if ((root != null) && root.options().copyDefaults()) {
final ConfigurationSection defaults = getDefaultSection();
if (defaults != null) {
result.addAll(defaults.getKeys(deep));
}
}
mapChildrenKeys(result, this, deep);
return result;
}
@Override
public Map<String, Object> getValues(final boolean deep) {
final Map<String, Object> result = new LinkedHashMap<>();
final Configuration root = getRoot();
if ((root != null) && root.options().copyDefaults()) {
final ConfigurationSection defaults = getDefaultSection();
if (defaults != null) {
result.putAll(defaults.getValues(deep));
}
}
mapChildrenValues(result, this, deep);
return result;
}
@@ -198,7 +255,7 @@ public class MemorySection implements ConfigurationSection {
if (path == null) {
throw new NullPointerException("Path cannot be null");
}
final Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot add default without root");
@@ -213,13 +270,13 @@ public class MemorySection implements ConfigurationSection {
public ConfigurationSection getDefaultSection() {
final Configuration root = getRoot();
final Configuration defaults = root == null ? null : root.getDefaults();
if (defaults != null) {
if (defaults.isConfigurationSection(getCurrentPath())) {
return defaults.getConfigurationSection(getCurrentPath());
}
}
return null;
}
@@ -228,12 +285,12 @@ public class MemorySection implements ConfigurationSection {
if (path == null) {
throw new NullPointerException("Cannot set to an empty path");
}
final Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot use section without a root");
}
final char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
@@ -248,7 +305,7 @@ public class MemorySection implements ConfigurationSection {
section = subSection;
}
}
final String key = path.substring(i2);
if (section == this) {
if (value == null) {
@@ -271,16 +328,16 @@ public class MemorySection implements ConfigurationSection {
if (path == null) {
throw new NullPointerException("Path cannot be null");
}
if (path.length() == 0) {
if (path.isEmpty()) {
return this;
}
final Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot access section without a root");
}
final char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
@@ -292,7 +349,7 @@ public class MemorySection implements ConfigurationSection {
return def;
}
}
final String key = path.substring(i2);
if (section == this) {
final Object result = map.get(key);
@@ -310,7 +367,7 @@ public class MemorySection implements ConfigurationSection {
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
@@ -325,7 +382,7 @@ public class MemorySection implements ConfigurationSection {
section = subSection;
}
}
final String key = path.substring(i2);
if (section == this) {
final ConfigurationSection result = new MemorySection(this, key);
@@ -338,7 +395,7 @@ public class MemorySection implements ConfigurationSection {
@Override
public ConfigurationSection createSection(final String path, final Map<?, ?> map) {
final ConfigurationSection section = createSection(path);
for (final Map.Entry<?, ?> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
section.createSection(entry.getKey().toString(), (Map<?, ?>) entry.getValue());
@@ -346,7 +403,7 @@ public class MemorySection implements ConfigurationSection {
section.set(entry.getKey().toString(), entry.getValue());
}
}
return section;
}
@@ -463,32 +520,32 @@ public class MemorySection implements ConfigurationSection {
@Override
public List<String> getStringList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<String> result = new ArrayList<>();
for (final Object object : list) {
if ((object instanceof String) || (isPrimitiveWrapper(object))) {
result.add(String.valueOf(object));
}
}
return result;
}
@Override
public List<Integer> getIntegerList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Integer> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Integer) {
result.add((Integer) object);
@@ -503,20 +560,20 @@ public class MemorySection implements ConfigurationSection {
result.add(((Number) object).intValue());
}
}
return result;
}
@Override
public List<Boolean> getBooleanList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Boolean> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Boolean) {
result.add((Boolean) object);
@@ -528,20 +585,20 @@ public class MemorySection implements ConfigurationSection {
}
}
}
return result;
}
@Override
public List<Double> getDoubleList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Double> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Double) {
result.add((Double) object);
@@ -556,20 +613,20 @@ public class MemorySection implements ConfigurationSection {
result.add(((Number) object).doubleValue());
}
}
return result;
}
@Override
public List<Float> getFloatList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Float> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Float) {
result.add((Float) object);
@@ -584,20 +641,20 @@ public class MemorySection implements ConfigurationSection {
result.add(((Number) object).floatValue());
}
}
return result;
}
@Override
public List<Long> getLongList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Long> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Long) {
result.add((Long) object);
@@ -612,20 +669,20 @@ public class MemorySection implements ConfigurationSection {
result.add(((Number) object).longValue());
}
}
return result;
}
@Override
public List<Byte> getByteList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Byte> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Byte) {
result.add((Byte) object);
@@ -640,26 +697,26 @@ public class MemorySection implements ConfigurationSection {
result.add(((Number) object).byteValue());
}
}
return result;
}
@Override
public List<Character> getCharacterList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Character> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Character) {
result.add((Character) object);
} else if (object instanceof String) {
final String str = (String) object;
if (str.length() == 1) {
result.add(str.charAt(0));
}
@@ -667,20 +724,20 @@ public class MemorySection implements ConfigurationSection {
result.add((char) ((Number) object).intValue());
}
}
return result;
}
@Override
public List<Short> getShortList(final String path) {
final List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
final List<Short> result = new ArrayList<>();
for (final Object object : list) {
if (object instanceof Short) {
result.add((Short) object);
@@ -695,7 +752,7 @@ public class MemorySection implements ConfigurationSection {
result.add(((Number) object).shortValue());
}
}
return result;
}
@@ -703,17 +760,17 @@ public class MemorySection implements ConfigurationSection {
public List<Map<?, ?>> getMapList(final String path) {
final List<?> list = getList(path);
final List<Map<?, ?>> result = new ArrayList<>();
if (list == null) {
return result;
}
for (final Object object : list) {
if (object instanceof Map) {
result.add((Map<?, ?>) object);
}
}
return result;
}
@@ -723,7 +780,7 @@ public class MemorySection implements ConfigurationSection {
if (val != null) {
return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
}
val = get(path, getDefault(path));
return (val instanceof ConfigurationSection) ? createSection(path) : null;
}
@@ -749,7 +806,7 @@ public class MemorySection implements ConfigurationSection {
if (path == null) {
throw new NullPointerException("Path may not be null");
}
final Configuration root = getRoot();
final Configuration defaults = root == null ? null : root.getDefaults();
return (defaults == null) ? null : defaults.get(createPath(this, path));
@@ -758,10 +815,10 @@ public class MemorySection implements ConfigurationSection {
protected void mapChildrenKeys(final Set<String> output, final ConfigurationSection section, final boolean deep) {
if (section instanceof MemorySection) {
final MemorySection sec = (MemorySection) section;
for (final Map.Entry<String, Object> entry : sec.map.entrySet()) {
output.add(createPath(section, entry.getKey(), this));
if ((deep) && (entry.getValue() instanceof ConfigurationSection)) {
final ConfigurationSection subsection = (ConfigurationSection) entry.getValue();
mapChildrenKeys(output, subsection, deep);
@@ -769,7 +826,7 @@ public class MemorySection implements ConfigurationSection {
}
} else {
final Set<String> keys = section.getKeys(deep);
for (final String key : keys) {
output.add(createPath(section, key, this));
}
@@ -779,10 +836,10 @@ public class MemorySection implements ConfigurationSection {
protected void mapChildrenValues(final Map<String, Object> output, final ConfigurationSection section, final boolean deep) {
if (section instanceof MemorySection) {
final MemorySection sec = (MemorySection) section;
for (final 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);
@@ -791,70 +848,13 @@ public class MemorySection implements ConfigurationSection {
}
} else {
final Map<String, Object> values = section.getValues(deep);
for (final 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(final ConfigurationSection section, final 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(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo) {
if (section == null) {
throw new NullPointerException("Cannot create path without a section");
}
final Configuration root = section.getRoot();
if (root == null) {
throw new IllegalStateException("Cannot create path without a root");
}
final char separator = root.options().pathSeparator();
final StringBuilder builder = new StringBuilder();
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() {
final Configuration root = getRoot();

View File

@@ -1,22 +1,20 @@
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;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Map;
/**
* An implementation of {@link Configuration} which saves all files in Yaml.
@@ -28,139 +26,7 @@ public class YamlConfiguration extends FileConfiguration {
private final DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
@Override
@SuppressWarnings("deprecation")
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlOptions.setAllowUnicode(SYSTEM_UTF);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final String header = buildHeader();
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
return header + dump;
}
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
if (contents == null) {
throw new NullPointerException("Contents cannot be null");
}
Map<?, ?> input;
try {
input = (Map<?, ?>) yaml.load(contents);
} catch (final YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (final ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
final String header = parseHeader(contents);
if (header.length() > 0) {
options().header(header);
}
if (input != null) {
convertMapsToSections(input, this);
}
}
protected void convertMapsToSections(final Map<?, ?> input, final ConfigurationSection section) {
for (final Map.Entry<?, ?> entry : input.entrySet()) {
final String key = entry.getKey().toString();
final Object value = entry.getValue();
if (value instanceof Map) {
convertMapsToSections((Map<?, ?>) value, section.createSection(key));
} else {
section.set(key, value);
}
}
}
protected String parseHeader(final String input) {
final String[] lines = input.split("\r?\n", -1);
final StringBuilder result = new StringBuilder();
boolean readingHeader = true;
boolean foundHeader = false;
for (int i = 0; (i < lines.length) && (readingHeader); i++) {
final 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() {
final String header = options().header();
if (options().copyHeader()) {
final Configuration def = getDefaults();
if ((def != null) && (def instanceof FileConfiguration)) {
final FileConfiguration filedefaults = (FileConfiguration) def;
final String defaultsHeader = filedefaults.buildHeader();
if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) {
return defaultsHeader;
}
}
}
if (header == null) {
return "";
}
final StringBuilder builder = new StringBuilder();
final String[] lines = header.split("\r?\n", -1);
boolean startedHeader = false;
for (int i = lines.length - 1; i >= 0; i--) {
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>
@@ -178,12 +44,12 @@ public class YamlConfiguration extends FileConfiguration {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
try {
config.load(file);
} catch (final Exception ex) {
} catch (InvalidConfigurationException | IOException ex) {
try {
file.getAbsolutePath();
File dest = new File(file.getAbsolutePath() + "_broken");
@@ -201,45 +67,10 @@ public class YamlConfiguration extends FileConfiguration {
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(final InputStream stream) {
if (stream == null) {
throw new NullPointerException("Stream cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
try {
config.load(stream);
} catch (final IOException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
} catch (final InvalidConfigurationException ex) {
ex.printStackTrace();
PS.debug("Cannot load configuration from stream");
}
return config;
}
/**
* Creates a new {@link YamlConfiguration}, loading from the given reader.
* <p>
@@ -255,19 +86,148 @@ public class YamlConfiguration extends FileConfiguration {
if (reader == null) {
throw new NullPointerException("Reader cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
try {
config.load(reader);
} catch (final IOException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
} catch (final InvalidConfigurationException ex) {
} catch (final IOException | InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
}
return config;
}
@Override
@SuppressWarnings("deprecation")
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlOptions.setAllowUnicode(SYSTEM_UTF);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final String header = buildHeader();
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
return header + dump;
}
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
if (contents == null) {
throw new NullPointerException("Contents cannot be null");
}
Map<?, ?> input;
try {
input = (Map<?, ?>) yaml.load(contents);
} catch (final YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (final ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
final String header = parseHeader(contents);
if (!header.isEmpty()) {
options().header(header);
}
if (input != null) {
convertMapsToSections(input, this);
}
}
protected void convertMapsToSections(final Map<?, ?> input, final ConfigurationSection section) {
for (final Map.Entry<?, ?> entry : input.entrySet()) {
final String key = entry.getKey().toString();
final Object value = entry.getValue();
if (value instanceof Map) {
convertMapsToSections((Map<?, ?>) value, section.createSection(key));
} else {
section.set(key, value);
}
}
}
protected String parseHeader(final String input) {
final String[] lines = input.split("\r?\n", -1);
final StringBuilder result = new StringBuilder();
boolean readingHeader = true;
boolean foundHeader = false;
for (int i = 0; (i < lines.length) && (readingHeader); i++) {
final 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.isEmpty())) {
result.append("\n");
} else if (foundHeader) {
readingHeader = false;
}
}
return result.toString();
}
@Override
protected String buildHeader() {
final String header = options().header();
if (options().copyHeader()) {
final Configuration def = getDefaults();
if ((def != null) && (def instanceof FileConfiguration)) {
final FileConfiguration filedefaults = (FileConfiguration) def;
final String defaultsHeader = filedefaults.buildHeader();
if ((defaultsHeader != null) && (!defaultsHeader.isEmpty())) {
return defaultsHeader;
}
}
}
if (header == null) {
return "";
}
final StringBuilder builder = new StringBuilder();
final String[] lines = header.split("\r?\n", -1);
boolean startedHeader = false;
for (int i = lines.length - 1; i >= 0; i--) {
builder.insert(0, "\n");
if ((startedHeader) || (!lines[i].isEmpty())) {
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;
}
}

View File

@@ -21,12 +21,14 @@
package com.intellectualcrafters.jnbt;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* A class which holds constant values.
*/
public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8");
public static final Charset CHARSET = StandardCharsets.UTF_8;
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9,
TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;

View File

@@ -26,7 +26,7 @@ public final class NBTInputStream implements Closeable {
*
* @throws IOException if an I/O error occurs
*/
public NBTInputStream(final InputStream is) throws IOException {
public NBTInputStream(final InputStream is) {
this.is = new DataInputStream(is);
}

View File

@@ -48,7 +48,7 @@ public final class NBTOutputStream implements Closeable {
*
* @throws IOException if an I/O error occurs.
*/
public NBTOutputStream(final OutputStream os) throws IOException {
public NBTOutputStream(final OutputStream os) {
this.os = new DataOutputStream(os);
}

View File

@@ -75,7 +75,7 @@ public class CDL {
for (;;) {
final String value = getValue(x);
char c = x.next();
if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) {
if ((value == null) || ((ja.length() == 0) && (value.isEmpty()) && (c != ','))) {
return null;
}
ja.put(value);
@@ -128,7 +128,8 @@ public class CDL {
final Object object = ja.opt(i);
if (object != null) {
final String string = object.toString();
if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
if ((!string.isEmpty()) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (
string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
sb.append('"');
final int length = string.length();
for (int j = 0; j < length; j += 1) {

View File

@@ -360,7 +360,7 @@ public class JSONObject {
}
public static Writer quote(final String string, final Writer w) throws IOException {
if ((string == null) || (string.length() == 0)) {
if ((string == null) || (string.isEmpty())) {
w.write("\"\"");
return w;
}
@@ -1111,7 +1111,7 @@ public class JSONObject {
} else if (name.startsWith("is")) {
key = name.substring(2);
}
if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) {
if ((!key.isEmpty()) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) {
if (key.length() == 1) {
key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) {

View File

@@ -108,7 +108,7 @@ public class XML {
if ("CDATA".equals(token)) {
if (x.next() == '[') {
string = x.nextCDATA();
if (string.length() > 0) {
if (!string.isEmpty()) {
context.accumulate("content", string);
}
return false;
@@ -192,7 +192,7 @@ public class XML {
return false;
} else if (token instanceof String) {
string = (String) token;
if (string.length() > 0) {
if (!string.isEmpty()) {
jsonobject.accumulate("content", XML.stringToValue(string));
}
// Nested element
@@ -380,7 +380,8 @@ public class XML {
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">";
return (tagName == null) ? "\"" + string + "\"" :
(string.isEmpty()) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -21,17 +21,6 @@
package com.intellectualcrafters.plot.api;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.MainCommand;
@@ -51,6 +40,17 @@ import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* PlotSquared API
@@ -115,12 +115,8 @@ public class PlotAPI {
/**
* Add a plot world
*
* @param world World Name
* @param plotArea Plot World Object
* @param manager World Manager
*
* @see PS#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotArea,
* com.intellectualcrafters.plot.object.PlotManager)
* @see PS#addPlotArea(PlotArea)
*/
public void addPlotArea(final PlotArea plotArea) {
PS.get().addPlotArea(plotArea);
@@ -229,7 +225,7 @@ public class PlotAPI {
public String[] getPermissions() {
final ArrayList<String> perms = new ArrayList<>();
for (final C c : C.values()) {
if (c.getCat().equals("static.permissions")) {
if ("static.permissions".equals(c.getCat())) {
perms.add(c.s());
}
}
@@ -267,7 +263,7 @@ public class PlotAPI {
* @return PlotManager
*
* @see com.intellectualcrafters.plot.object.PlotManager
* @see PS#getPlotManager(String)
* @see PS#getPlotManager(Plot)
*/
@Deprecated
public PlotManager getPlotManager(final World world) {
@@ -292,7 +288,7 @@ public class PlotAPI {
*
* @return PlotManager
*
* @see PS#getPlotManager(String)
* @see PS#getPlotManager(Plot)
* @see com.intellectualcrafters.plot.object.PlotManager
*/
@Deprecated
@@ -335,7 +331,7 @@ public class PlotAPI {
*
* @return PlotArea class for that world ! will return null if not a plot world world
*
* @see PS#getPlotArea(String)
* @see PS#getPlotArea(String, String)
* @see com.intellectualcrafters.plot.object.PlotArea
*/
@Deprecated
@@ -388,7 +384,7 @@ public class PlotAPI {
* @see MainUtil#sendConsoleMessage(C, String...)
*/
public void sendConsoleMessage(final String msg) {
PS.log(msg);;
PS.log(msg);
}
/**
@@ -457,7 +453,6 @@ public class PlotAPI {
*
* @return plot if found, otherwise it creates a temporary plot-
*
* @see MainUtil#getPlotAbs(com.intellectualcrafters.plot.object.Location)
* @see Plot
*/
public Plot getPlot(final Location l) {
@@ -492,7 +487,7 @@ public class PlotAPI {
*/
@Deprecated
public boolean hasPlot(final World world, final Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0;
}
/**
@@ -507,7 +502,7 @@ public class PlotAPI {
UUID uuid = BukkitUtil.getPlayer(plr).getUUID();
for (final Plot plot : PS.get().getPlots(world.getName())) {
if (just_owner) {
if ((plot.owner != null) && (plot.owner.equals(uuid))) {
if (plot.hasOwner() && plot.isOwner(uuid)) {
pPlots.add(plot);
}
} else {
@@ -534,7 +529,8 @@ public class PlotAPI {
if (world == null) {
return new Plot[0];
}
return PS.get().getPlots(world.getName()).toArray(new Plot[0]);
Collection<Plot> plots = PS.get().getPlots(world.getName());
return plots.toArray(new Plot[plots.size()]);
}
/**
@@ -542,11 +538,11 @@ public class PlotAPI {
*
* @return World[] - array of plot worlds
*
* @see PS#getPlotWorlds()
*/
@Deprecated
public String[] getPlotWorlds() {
return PS.get().getPlotWorldStrings().toArray(new String[0]);
Set<String> plotWorldStrings = PS.get().getPlotWorldStrings();
return plotWorldStrings.toArray(new String[plotWorldStrings.size()]);
}
/**
@@ -572,9 +568,6 @@ public class PlotAPI {
*
* @deprecated As merged plots may not have a rectangular shape
*
* @see MainUtil#getPlotBottomLocAbs(String, PlotId)
* @see MainUtil#getPlotTopLocAbs(String, PlotId)
* @see MainUtil#getPlotHome(String, PlotId)
* @see Plot
*/
@Deprecated
@@ -589,7 +582,6 @@ public class PlotAPI {
*
* @return plot bottom location
*
* @see MainUtil#getPlotHome(String, PlotId)
* @see Plot
*/
public Location getHomeLocation(final Plot p) {
@@ -605,7 +597,6 @@ public class PlotAPI {
*
* @deprecated As merged plots may not have a rectangular shape
*
* @see MainUtil#getPlotBottomLocAbs(String, PlotId)
* @see Plot
*/
@Deprecated
@@ -622,7 +613,6 @@ public class PlotAPI {
*
* @deprecated As merged plots may not have a rectangular shape
*
* @see MainUtil#getPlotTopLocAbs(String, PlotId)
* @see Plot
*/
@Deprecated
@@ -637,7 +627,6 @@ public class PlotAPI {
*
* @return true if the player is in a plot, false if not-
*
* @see MainUtil#getPlotAbs(com.intellectualcrafters.plot.object.Location)
*/
public boolean isInPlot(final Player player) {
return getPlot(player) != null;
@@ -677,7 +666,6 @@ public class PlotAPI {
*
* @return the number of plots the player has
*
* @see MainUtil#getPlayerPlotCount(String, PlotPlayer)
*/
public int getPlayerPlotCount(final World world, final Player player) {
if (world == null) {

View File

@@ -42,7 +42,7 @@ public class Alias extends SetCommand {
@Override
public boolean set(final PlotPlayer plr, final Plot plot, final String alias) {
if (alias.length() == 0) {
if (alias.isEmpty()) {
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}

View File

@@ -1,10 +1,5 @@
package com.intellectualcrafters.plot.commands;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
@@ -32,6 +27,11 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
@CommandDeclaration(
command = "area",
permission = "plots.area",
@@ -59,7 +59,7 @@ public class Area extends SubCommand {
}
switch (args.length) {
case 1: {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [<modifier>=<value>]...");
return false;
}
case 2: {
@@ -67,7 +67,7 @@ public class Area extends SubCommand {
case "pos1": { // Set position 1
HybridPlotWorld area = plr.<HybridPlotWorld> getMeta("area_create_area");
if (area == null) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [<modifier>=<value>]...");
return false;
}
Location loc = plr.getLocation();
@@ -80,7 +80,7 @@ public class Area extends SubCommand {
case "pos2": { // Set position 2 and finish creation for type=2 (partial)
final HybridPlotWorld area = plr.<HybridPlotWorld> getMeta("area_create_area");
if (area == null) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [<modifier>=<value>]...");
return false;
}
Location pos1 = plr.getLocation();
@@ -100,7 +100,7 @@ public class Area extends SubCommand {
final int offsetz = bz - (area.ROAD_WIDTH == 0 ? 0 : lower);
final RegionWrapper region = new RegionWrapper(bx, tx, bz, tz);
Set<PlotArea> areas = PS.get().getPlotAreas(area.worldname, region);
if (areas.size() > 0) {
if (!areas.isEmpty()) {
C.CLUSTER_INTERSECTION.send(plr, areas.iterator().next().toString());
return false;
}
@@ -163,14 +163,14 @@ public class Area extends SubCommand {
return false;
}
Set<PlotArea> areas = PS.get().getPlotAreas(pa.worldname);
if (areas.size() > 0) {
if (!areas.isEmpty()) {
PlotArea area = areas.iterator().next();
pa.TYPE = area.TYPE;
}
for (int i = 2; i < args.length; i++) {
String[] pair = args[i].split("=");
if (pair.length != 2) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [<modifier>=<value>]...");
return false;
}
switch (pair[0].toLowerCase()) {
@@ -225,7 +225,7 @@ public class Area extends SubCommand {
break;
}
default: {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [<modifier>=<value>]...");
return false;
}
}
@@ -264,7 +264,7 @@ public class Area extends SubCommand {
return true;
}
if (pa.id == null) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [<modifier>=<value>]...");
return false;
}
if (WorldUtil.IMP.isWorld(pa.worldname)) {

View File

@@ -20,8 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.Set;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.FlagManager;
@@ -35,7 +33,10 @@ import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(command = "clear", description = "Clear a plot", permission = "plots.clear", category = CommandCategory.APPEARANCE, usage = "/plot clear [id]")
import java.util.Set;
@CommandDeclaration(command = "clear", description = "Clear a plot", permission = "plots.clear", category = CommandCategory.APPEARANCE,
usage = "/plot clear [type]")
public class Clear extends SubCommand {
@Override
@@ -45,7 +46,7 @@ public class Clear extends SubCommand {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("mine")) {
Set<Plot> plots = plr.getPlots();
if (plots.size() > 0) {
if (!plots.isEmpty()) {
plot = plots.iterator().next();
} else {
MainUtil.sendMessage(plr, C.NO_PLOTS);

View File

@@ -20,11 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
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.Settings;
@@ -43,6 +38,11 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@CommandDeclaration(
command = "cluster",
aliases = { "clusters" },
@@ -103,7 +103,7 @@ public class Cluster extends SubCommand {
return false;
}
if (args.length != 4) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster create <name> <id-bot> <id-top>");
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster create <name> <type-bot> <type-top>");
return false;
}
// check pos1 / pos2
@@ -132,7 +132,7 @@ public class Cluster extends SubCommand {
}
// Check if it occupies existing plots
final Set<Plot> plots = area.getPlotSelectionOwned(pos1, pos2);
if (plots.size() > 0) {
if (!plots.isEmpty()) {
if (!Permissions.hasPermission(plr, "plots.cluster.create.other")) {
final UUID uuid = plr.getUUID();
for (final Plot plot : plots) {
@@ -263,14 +263,14 @@ public class Cluster extends SubCommand {
final HashSet<Plot> removed = ((HashSet<Plot>) existing.clone());
removed.removeAll(newplots);
// Check expand / shrink
if (removed.size() > 0) {
if (!removed.isEmpty()) {
if (!Permissions.hasPermission(plr, "plots.cluster.resize.shrink")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.shrink");
return false;
}
}
newplots.removeAll(existing);
if (newplots.size() > 0) {
if (!newplots.isEmpty()) {
if (!Permissions.hasPermission(plr, "plots.cluster.resize.expand")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.expand");
return false;
@@ -336,7 +336,6 @@ public class Cluster extends SubCommand {
if (!cluster.isAdded(uuid)) {
// add the user if not added
cluster.invited.add(uuid);
final String world = plr.getLocation().getWorld();
DBFunc.setInvited(cluster, uuid);
final PlotPlayer player = UUIDHandler.getPlayer(uuid);
if (player != null) {

View File

@@ -20,14 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
@@ -39,6 +31,14 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
@CommandDeclaration(command = "condense", permission = "plots.admin", description = "Condense a plotworld", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE)
public class Condense extends SubCommand {
@@ -126,7 +126,7 @@ public class Condense extends SubCommand {
}
start = Auto.getNextPlotId(start, 1);
}
if ((free.size() == 0) || (to_move.size() == 0)) {
if ((free.isEmpty()) || (to_move.isEmpty())) {
MainUtil.sendMessage(plr, "NO FREE PLOTS FOUND");
return false;
}
@@ -137,7 +137,7 @@ public class Condense extends SubCommand {
if (!TASK) {
MainUtil.sendMessage(plr, "TASK CANCELLED.");
}
if (allPlots.size() == 0) {
if (allPlots.isEmpty()) {
TASK = false;
MainUtil.sendMessage(plr, "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK.");
return;
@@ -147,7 +147,7 @@ public class Condense extends SubCommand {
int i = 0;
while (free.size() > i) {
final Plot possible = origin.getArea().getPlotAbs(free.get(i));
if (possible.owner != null) {
if (possible.hasOwner()) {
free.remove(i);
continue;
}
@@ -166,7 +166,7 @@ public class Condense extends SubCommand {
break;
}
}
if (free.size() == 0) {
if (free.isEmpty()) {
TASK = false;
MainUtil.sendMessage(plr, "TASK FAILED. NO FREE PLOTS FOUND!");
return;

View File

@@ -1,11 +1,5 @@
package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.MySQL;
@@ -19,6 +13,12 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
@CommandDeclaration(
command = "database",
aliases = { "convert" },
@@ -101,7 +101,7 @@ public class Database extends SubCommand {
for (final Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
final Plot plot = entry2.getValue();
if (pa.getOwnedPlotAbs(plot.getId()) != null) {
MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp);
MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | type=" + plot.temp);
continue;
}
PS.get().updatePlot(plot);

View File

@@ -20,9 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.UUID;
import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
@@ -42,6 +39,10 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
@CommandDeclaration(
command = "debugclaimtest",
description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. Execution time may vary",
@@ -109,14 +110,14 @@ public class DebugClaimTest extends SubCommand {
final String[] lines = WorldUtil.IMP.getSign(loc);
if (lines != null) {
String line = lines[2];
if ((line != null) && (line.length() > 2)) {
if (line != null && line.length() > 2) {
line = line.substring(2);
final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = (map.get(new StringWrapper(line)));
UUID uuid = map.get(new StringWrapper(line));
if (uuid == null) {
for (final StringWrapper string : map.keySet()) {
if (string.value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = map.get(string);
for (final Map.Entry<StringWrapper, UUID> stringWrapperUUIDEntry : map.entrySet()) {
if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = stringWrapperUUIDEntry.getValue();
break;
}
}
@@ -134,7 +135,7 @@ public class DebugClaimTest extends SubCommand {
}
}
}
if (plots.size() > 0) {
if (!plots.isEmpty()) {
MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override

View File

@@ -74,7 +74,8 @@ import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = { "exec" }, category = CommandCategory.DEBUG)
@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = "exec",
category = CommandCategory.DEBUG)
public class DebugExec extends SubCommand {
private ScriptEngine engine;
@@ -85,13 +86,16 @@ public class DebugExec extends SubCommand {
final File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js");
if (file.exists()) {
init();
final String script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
final String script = StringMan.join(Files
.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"),
StandardCharsets.UTF_8),
System.getProperty("line.separator"));
scope.put("THIS", this);
scope.put("PlotPlayer", ConsolePlayer.getConsole());
engine.eval(script, scope);
}
} catch (final Exception e) {}
} catch (IOException | ScriptException e) {
}
}
public ScriptEngine getEngine() {
@@ -106,9 +110,9 @@ public class DebugExec extends SubCommand {
if (engine != null) {
return;
}
engine = (new ScriptEngineManager(null)).getEngineByName("nashorn");
engine = new ScriptEngineManager(null).getEngineByName("nashorn");
if (engine == null) {
engine = (new ScriptEngineManager(null)).getEngineByName("JavaScript");
engine = new ScriptEngineManager(null).getEngineByName("JavaScript");
}
final ScriptContext context = new SimpleScriptContext();
scope = context.getBindings(ScriptContext.ENGINE_SCOPE);
@@ -168,7 +172,7 @@ public class DebugExec extends SubCommand {
final PlotAnalysis analysis = plot.getComplexity();
if (analysis != null) {
final int complexity = analysis.getComplexity();
MainUtil.sendMessage(player, "Changes/column: " + (analysis.changes / 1.0));
MainUtil.sendMessage(player, "Changes/column: " + analysis.changes / 1.0);
MainUtil.sendMessage(player, "Complexity: " + complexity);
return true;
}
@@ -181,7 +185,7 @@ public class DebugExec extends SubCommand {
});
return true;
}
case "calibrate-analysis": {
case "calibrate-analysis":
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze <threshold>");
MainUtil.sendMessage(player, "$1<threshold> $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating it)");
@@ -202,8 +206,7 @@ public class DebugExec extends SubCommand {
}
}, threshold);
return true;
}
case "stop-expire": {
case "stop-expire":
if (ExpireManager.task != -1) {
PS.get().TASK.cancelTask(ExpireManager.task);
} else {
@@ -211,8 +214,7 @@ public class DebugExec extends SubCommand {
}
ExpireManager.task = -1;
return MainUtil.sendMessage(player, "Cancelled task.");
}
case "remove-flag": {
case "remove-flag":
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag <flag>");
return false;
@@ -224,20 +226,19 @@ public class DebugExec extends SubCommand {
}
}
return MainUtil.sendMessage(player, "Cleared flag: " + flag);
}
case "start-rgar": {
if (args.length != 2) {
MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar <world>");
return false;
}
boolean result;
PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (area == null) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
return false;
}
boolean result;
if (HybridUtils.regions != null) {
result = ((HybridUtils.manager)).scheduleRoadUpdate(area, HybridUtils.regions, 0);
result = HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0);
} else {
result = HybridUtils.manager.scheduleRoadUpdate(area, 0);
}
@@ -247,7 +248,7 @@ public class DebugExec extends SubCommand {
}
return true;
}
case "stop-rgar": {
case "stop-rgar":
if (!HybridUtils.UPDATE) {
MainUtil.sendMessage(player, "&cTASK NOT RUNNING!");
return false;
@@ -255,16 +256,14 @@ public class DebugExec extends SubCommand {
HybridUtils.UPDATE = false;
MainUtil.sendMessage(player, "&cCancelling task... (please wait)");
return true;
}
case "start-expire": {
case "start-expire":
if (ExpireManager.task == -1) {
ExpireManager.runTask();
} else {
return MainUtil.sendMessage(player, "Plot expiry task already started");
}
return MainUtil.sendMessage(player, "Started plot expiry task");
}
case "update-expired": {
case "update-expired":
if (args.length > 1) {
PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
@@ -276,8 +275,7 @@ public class DebugExec extends SubCommand {
return true;
}
return MainUtil.sendMessage(player, "Use /plot debugexec update-expired <world>");
}
case "show-expired": {
case "show-expired":
if (args.length > 1) {
final String world = args[1];
if (!WorldUtil.IMP.isWorld(world)) {
@@ -294,8 +292,7 @@ public class DebugExec extends SubCommand {
return true;
}
return MainUtil.sendMessage(player, "Use /plot debugexec show-expired <world>");
}
case "seen": {
case "seen":
if (args.length != 2) {
return MainUtil.sendMessage(player, "Use /plot debugexec seen <player>");
}
@@ -304,7 +301,7 @@ public class DebugExec extends SubCommand {
return MainUtil.sendMessage(player, "player not found: " + args[1]);
}
final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid);
if ((op == null) || (op.getLastPlayed() == 0)) {
if (op == null || op.getLastPlayed() == 0) {
return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]);
}
final Timestamp stamp = new Timestamp(op.getLastPlayed());
@@ -315,8 +312,7 @@ public class DebugExec extends SubCommand {
MainUtil.sendMessage(player, "GMT: " + date.toGMTString());
MainUtil.sendMessage(player, "Local: " + date.toLocaleString());
return true;
}
case "trim-check": {
case "trim-check":
if (args.length != 2) {
MainUtil.sendMessage(player, "Use /plot debugexec trim-check <world>");
MainUtil.sendMessage(player, "&7 - Generates a list of regions to trim");
@@ -332,12 +328,11 @@ public class DebugExec extends SubCommand {
public void run() {
Trim.sendMessage("Processing is complete! Here's how many chunks would be deleted:");
Trim.sendMessage(" - MCA #: " + empty.size());
Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)");
Trim.sendMessage(" - CHUNKS: " + empty.size() * 1024 + " (max)");
Trim.sendMessage("Exporting log for manual approval...");
final File file = new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt");
PrintWriter writer;
try {
writer = new PrintWriter(file);
PrintWriter writer = new PrintWriter(file);
for (final ChunkLoc loc : empty) {
writer.println(world + "/region/r." + loc.x + "." + loc.z + ".mca");
}
@@ -357,18 +352,18 @@ public class DebugExec extends SubCommand {
MainUtil.sendMessage(player, "Trim task already started!");
}
return result;
}
case "h":
case "he":
case "?":
case "help": {
case "help":
MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">");
return false;
}
case "addcmd": {
case "addcmd":
try {
final String cmd = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
final String cmd = StringMan.join(Files
.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]),
StandardCharsets.UTF_8),
System.getProperty("line.separator"));
final Command<PlotPlayer> subcommand = new Command<PlotPlayer>(args[1].split("\\.")[0]) {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
@@ -386,16 +381,14 @@ public class DebugExec extends SubCommand {
};
MainCommand.getInstance().addCommand(subcommand);
return true;
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd <file>");
return false;
}
}
case "runasync": {
case "runasync":
async = true;
}
case "run": {
case "run":
try {
script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
@@ -411,8 +404,7 @@ public class DebugExec extends SubCommand {
return false;
}
break;
}
case "allcmd": {
case "allcmd":
if (args.length < 3) {
C.COMMAND_SYNTAX.send(player, "/plot debugexec allcmd <condition> <command>");
return false;
@@ -420,9 +412,9 @@ public class DebugExec extends SubCommand {
long start = System.currentTimeMillis();
Command<PlotPlayer> cmd = MainCommand.getInstance().getCommand(args[3]);
String[] params = Arrays.copyOfRange(args, 4, args.length);
if (args[1].equals("true")) {
Location loc = (Location) player.getMeta("location");
Plot plot = (Plot) player.getMeta("lastplot");
if ("true".equals(args[1])) {
Location loc = player.getMeta("location");
Plot plot = player.getMeta("lastplot");
for (Plot current : PS.get().getBasePlots()) {
player.setMeta("location", current.getBottomAbs());
player.setMeta("lastplot", current);
@@ -445,19 +437,20 @@ public class DebugExec extends SubCommand {
scope.put("_2", params);
scope.put("_3", cmd);
script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand(PlotPlayer,_2)}}";
break;
}
case "all": {
case "all":
if (args.length < 3) {
C.COMMAND_SYNTAX.send(player, "/plot debugexec all <condition> <code>");
return false;
}
script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ") + "}}";
script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan
.join(Arrays.copyOfRange(args, 2, args.length), " ")
+ "}}";
break;
}
default: {
default:
script = StringMan.join(args, " ");
}
}
if (!ConsolePlayer.isConsole(player)) {
MainUtil.sendMessage(player, C.NOT_CONSOLE);

View File

@@ -40,7 +40,7 @@ public class Desc extends SetCommand {
@Override
public boolean set(PlotPlayer plr, Plot plot, String desc) {
if (desc.length() == 0) {
if (desc.isEmpty()) {
plot.removeFlag("description");
MainUtil.sendMessage(plr, C.DESC_UNSET);
return true;

View File

@@ -20,10 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.AbstractFlag;
@@ -38,6 +34,11 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@CommandDeclaration(
command = "setflag",
aliases = { "f", "flag", "setf", "setflag" },
@@ -81,7 +82,7 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag.other");
return false;
}
if ((args.length > 1) && FlagManager.isReserved(args[1])) {
if (args.length > 1 && FlagManager.isReserved(args[1])) {
MainUtil.sendMessage(player, C.NOT_VALID_FLAG);
return false;
}
@@ -147,7 +148,7 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.remove");
return false;
}
if ((args.length != 2) && (args.length != 3)) {
if (args.length != 2 && args.length != 3) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove <flag> [values]");
return false;
}
@@ -173,7 +174,7 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.FLAG_NOT_IN_PLOT);
return false;
}
if ((args.length == 3) && flag.getAbstractFlag().isList()) {
if (args.length == 3 && flag.getAbstractFlag().isList()) {
final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ");
((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value);
DBFunc.setFlags(plot, plot.getFlags().values());
@@ -214,7 +215,7 @@ public class FlagCmd extends SubCommand {
return false;
}
Flag flag = FlagManager.getPlotFlag(plot, args[1].toLowerCase());
if ((flag == null) || !flag.getAbstractFlag().isList()) {
if (flag == null || !flag.getAbstractFlag().isList()) {
flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed);
} else {
((FlagValue.ListValue) flag.getAbstractFlag().value).add(flag.getValue(), value);
@@ -228,7 +229,7 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.FLAG_ADDED);
return true;
}
case "list": {
case "list":
if (!Permissions.hasPermission(player, "plots.flag.list")) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.list");
return false;
@@ -247,13 +248,12 @@ public class FlagCmd extends SubCommand {
}
String message = "";
String prefix = "";
for (final String flag : flags.keySet()) {
message += prefix + "&6" + flag + ": &7" + StringMan.join(flags.get(flag), ", ");
for (final Map.Entry<String, ArrayList<String>> stringArrayListEntry : flags.entrySet()) {
message += prefix + "&6" + stringArrayListEntry.getKey() + ": &7" + StringMan.join(stringArrayListEntry.getValue(), ", ");
prefix = "\n";
}
MainUtil.sendMessage(player, message);
return true;
}
}
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>");
return false;

View File

@@ -1,5 +1,10 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.Command;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -11,11 +16,6 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.Command;
public class GenerateDocs {
public static void main(final String[] args) {
MainCommand.getInstance().addCommand(new WE_Anywhere());
@@ -56,7 +56,7 @@ public class GenerateDocs {
log("#### Description");
log("`" + command.getDescription() + "`");
if (comment.length() > 0) {
if (!comment.isEmpty()) {
log("##### Comments");
log("``` java");
log(comment);
@@ -72,7 +72,7 @@ public class GenerateDocs {
}
final Set<String> aliases = command.getAliases();
if (aliases.size() > 0) {
if (!aliases.isEmpty()) {
log("#### Aliases");
log("`" + StringMan.getString(command.getAliases()) + "`");
}
@@ -80,7 +80,7 @@ public class GenerateDocs {
log("#### Permissions");
log("##### Primary");
log(" - `" + command.getPermission() + "` ");
if (perms.size() > 0) {
if (!perms.isEmpty()) {
log("");
log("##### Other");
log(" - `" + StringMan.join(perms, "`\n - `") + "`");

View File

@@ -23,7 +23,8 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(command = "home", aliases = { "h" }, description = "Go to your plot", usage = "/plot home [id|alias]", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE)
@CommandDeclaration(command = "home", aliases = {"h"}, description = "Go to your plot", usage = "/plot home [type|alias]",
category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE)
public class Home extends SubCommand {
@Override

View File

@@ -20,9 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.List;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
@@ -34,6 +31,9 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.List;
@CommandDeclaration(
command = "inbox",
description = "Review the comments for a plot",
@@ -44,7 +44,7 @@ requiredType = RequiredType.NONE)
public class Inbox extends SubCommand {
public void displayComments(final PlotPlayer player, final List<PlotComment> oldComments, int page) {
if ((oldComments == null) || (oldComments.size() == 0)) {
if ((oldComments == null) || (oldComments.isEmpty())) {
MainUtil.sendMessage(player, C.INBOX_EMPTY);
return;
}

View File

@@ -20,8 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Plot;
@@ -32,7 +30,10 @@ import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(command = "info", aliases = { "i" }, description = "Display plot info", usage = "/plot info <id>", category = CommandCategory.INFO)
import java.util.UUID;
@CommandDeclaration(command = "info", aliases = {"i"}, description = "Display plot info", usage = "/plot info <type>",
category = CommandCategory.INFO)
public class Info extends SubCommand {
@Override
@@ -48,7 +49,7 @@ public class Info extends SubCommand {
case "biome":
case "denied":
case "flags":
case "id":
case "type":
case "size":
case "members":
case "owner":
@@ -156,7 +157,7 @@ public class Info extends SubCommand {
return C.PLOT_INFO_DENIED.s();
case "flags":
return C.PLOT_INFO_FLAGS.s();
case "id":
case "type":
return C.PLOT_INFO_ID.s();
case "size":
return C.PLOT_INFO_SIZE.s();

View File

@@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.commands;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
@@ -18,6 +14,10 @@ import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
@CommandDeclaration(
command = "load",
aliases = { "restore" },
@@ -121,7 +121,7 @@ public class Load extends SubCommand {
public void run() {
final List<String> schematics = SchematicHandler.manager.getSaves(plr.getUUID());
plot.removeRunning();
if ((schematics == null) || (schematics.size() == 0)) {
if ((schematics == null) || (schematics.isEmpty())) {
MainUtil.sendMessage(plr, C.LOAD_FAILED);
return;
}

View File

@@ -55,13 +55,6 @@ public class MainCommand extends CommandManager<PlotPlayer> {
private static MainCommand instance;
private HashMap<String, Command<PlotPlayer>> setCommands;
public static MainCommand getInstance() {
if (instance == null) {
instance = new MainCommand();
}
return instance;
}
private MainCommand() {
super(null, new ArrayList<Command<PlotPlayer>>());
instance = this;
@@ -141,6 +134,13 @@ public class MainCommand extends CommandManager<PlotPlayer> {
}
}
public static MainCommand getInstance() {
if (instance == null) {
instance = new MainCommand();
}
return instance;
}
public static boolean no_permission(final PlotPlayer player, final String permission) {
MainUtil.sendMessage(player, C.NO_PERMISSION, permission);
return false;
@@ -347,9 +347,9 @@ public class MainCommand extends CommandManager<PlotPlayer> {
require = 0;
}
String[] split = usage[i].split("\\|| |\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/");
for (int j = 0; j < split.length; j++) {
for (String aSplit : split) {
for (String arg : args) {
if (StringMan.isEqualIgnoreCase(arg, split[j])) {
if (StringMan.isEqualIgnoreCase(arg, aSplit)) {
count += 5 - i + require;
}
}
@@ -395,7 +395,7 @@ public class MainCommand extends CommandManager<PlotPlayer> {
MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND);
{
final List<Command<PlotPlayer>> cmds = getCommands(null, plr);
if ((label == null) || (cmds.size() == 0)) {
if ((label == null) || (cmds.isEmpty())) {
MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help");
} else {
final HashSet<String> setargs = new HashSet<>(args.length + 1);

View File

@@ -20,9 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.HashSet;
import java.util.UUID;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
@@ -37,14 +34,12 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "merge",
aliases = { "m" },
description = "Merge the plot you are standing on, with another plot",
permission = "plots.merge",
usage = "/plot merge <all|n|e|s|w> [removeroads]",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE)
import java.util.HashSet;
import java.util.UUID;
@CommandDeclaration(command = "merge", aliases = "m", description = "Merge the plot you are standing on, with another plot",
permission = "plots.merge", usage = "/plot merge <all|n|e|s|w> [removeroads]", category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE)
public class Merge extends SubCommand {
public final static String[] values = new String[] { "north", "east", "south", "west", "auto" };
public final static String[] aliases = new String[] { "n", "e", "s", "w", "all" };
@@ -93,17 +88,18 @@ public class Merge extends SubCommand {
}
}
final PlotArea plotworld = plot.getArea();
if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d && EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) {
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d
&& EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, plotworld.MERGE_PRICE + "");
return false;
}
int direction = -1;
final int size = plot.getConnectedPlots().size();
final int maxSize = Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS);
if (size - 1> maxSize) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.merge." + (size + 1));
return false;
}
int direction = -1;
if (args.length == 0) {
// switch (direction(plr.getLocationFull().getYaw())) {
// case "NORTH":
@@ -120,13 +116,13 @@ public class Merge extends SubCommand {
// break;
// }
} else {
if (args[0].equalsIgnoreCase("all") || args[0].equalsIgnoreCase("auto")) {
if ("all".equalsIgnoreCase(args[0]) || "auto".equalsIgnoreCase(args[0])) {
boolean terrain = Settings.MERGE_REMOVES_ROADS;
if (args.length == 2) {
terrain = args[1].equalsIgnoreCase("true");
terrain = "true".equalsIgnoreCase(args[1]);
}
if (plot.autoMerge(-1, maxSize, uuid, terrain)) {
if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE);
sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + "");
}
@@ -151,12 +147,12 @@ public class Merge extends SubCommand {
}
final boolean terrain;
if (args.length == 2) {
terrain = args[1].equalsIgnoreCase("true");
terrain = "true".equalsIgnoreCase(args[1]);
} else {
terrain = Settings.MERGE_REMOVES_ROADS;
}
if (plot.autoMerge(direction, maxSize - size, uuid, terrain)) {
if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE);
sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + "");
}
@@ -191,7 +187,7 @@ public class Merge extends SubCommand {
sendMessage(accepter, C.MERGE_NOT_VALID);
return;
}
if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
if (EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, plotworld.MERGE_PRICE + "");
return;

View File

@@ -39,7 +39,7 @@ import java.util.Set;
import java.util.UUID;
@CommandDeclaration(
usage = "/plot purge world:<world> area:<area> id:<id> owner:<owner> shared:<shared> unknown:[true|false]",
usage = "/plot purge world:<world> area:<area> type:<type> owner:<owner> shared:<shared> unknown:[true|false]",
command = "purge",
permission = "plots.admin",
description = "Purge all plots for a world",
@@ -80,7 +80,7 @@ public class Purge extends SubCommand {
break;
}
case "plotid":
case "id": {
case "type": {
id = PlotId.fromString(split[1]);
if (id == null) {
C.NOT_VALID_PLOT_ID.send(plr, split[1]);
@@ -169,7 +169,7 @@ public class Purge extends SubCommand {
}
}
}
if (toDelete.size() == 0) {
if (toDelete.isEmpty()) {
C.FOUND_NO_PLOTS.send(plr);
return false;
}

View File

@@ -20,15 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
import org.apache.commons.lang.mutable.MutableInt;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
@@ -45,6 +36,14 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import org.apache.commons.lang.mutable.MutableInt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(
command = "rate",
@@ -113,7 +112,7 @@ public class Rate extends SubCommand {
sendMessage(player, C.RATING_NOT_DONE);
return false;
}
if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() != 0)) {
if ((Settings.RATING_CATEGORIES != null) && (!Settings.RATING_CATEGORIES.isEmpty())) {
final Runnable run = new Runnable() {
@Override
public void run() {
@@ -183,7 +182,7 @@ public class Rate extends SubCommand {
}
final String arg = args[0];
final int rating;
if (MathMan.isInteger(arg) && (arg.length() < 3) && (arg.length() > 0)) {
if (MathMan.isInteger(arg) && (arg.length() < 3) && (!arg.isEmpty())) {
rating = Integer.parseInt(arg);
if (rating > 10 || rating < 1) {
sendMessage(player, C.RATING_NOT_VALID);

View File

@@ -20,11 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
@@ -41,6 +36,11 @@ import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
@CommandDeclaration(
command = "schematic",
permission = "plots.schematic",
@@ -153,7 +153,7 @@ public class SchematicCmd extends SubCommand {
// }
// final int l1 = schematic.getSchematicDimension().getX();
// final int l2 = schematic.getSchematicDimension().getZ();
// final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.id);
// final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.type);
// if ((l1 < length) || (l2 < length)) {
// sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length));
// break;
@@ -177,7 +177,7 @@ public class SchematicCmd extends SubCommand {
return false;
}
final Collection<Plot> plots = area.getPlots();
if ((plots.size() == 0)) {
if ((plots.isEmpty())) {
MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall <area>");
return false;
}

View File

@@ -20,11 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.ConfigurationNode;
@@ -39,6 +34,11 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
@CommandDeclaration(
command = "setup",
permission = "plots.admin.command.setup",
@@ -172,14 +172,14 @@ public class Setup extends SubCommand {
}
break;
}
case 2: { // area id
case 2: { // area type
if (!StringMan.isAlphanumericUnd(args[0])) {
MainUtil.sendMessage(plr, "&cThe area id must be alphanumerical!");
MainUtil.sendMessage(plr, "&cThe area type must be alphanumerical!");
return false;
}
for (PlotArea area : PS.get().getPlotAreas()) {
if (area.id != null && area.id.equalsIgnoreCase(args[0])) {
MainUtil.sendMessage(plr, "&cYou must choose an area id that is not in use!");
MainUtil.sendMessage(plr, "&cYou must choose an area type that is not in use!");
return false;
}
}

View File

@@ -20,20 +20,19 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.List;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.util.MainUtil;
import java.util.List;
/**
* SubCommand class
*
*/
@SuppressWarnings({ "deprecation" })
public abstract class SubCommand extends com.plotsquared.general.commands.Command<PlotPlayer> {
/**
@@ -64,7 +63,7 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman
if (page > totalPages) {
page = totalPages;
}
int max = (page * size) + size;
int max = page * size + size;
if (max > c.size()) {
max = c.size();
}
@@ -81,18 +80,20 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman
msg.send(player);
}
// Send the footer
if ((page < totalPages) && (page > 0)) { // Back | Next
new PlotMessage().text("<-").color("$1").command(baseCommand + " " + (page)).text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2))
if (page < totalPages && page > 0) { // Back | Next
new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$1")
.command(baseCommand + " " + (page + 2))
.text(C.CLICKABLE.s()).color("$2").send(player);
return;
}
if ((page == 0) && (totalPages != 0)) { // Next
if (page == 0 && totalPages != 0) { // Next
new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)).text(C.CLICKABLE.s()).color("$2").send(player);
return;
}
if ((page == totalPages) && (totalPages != 0)) { // Back
new PlotMessage().text("<-").color("$1").command(baseCommand + " " + (page)).text(" | ").color("$3").text("->").color("$3").text(C.CLICKABLE.s()).color("$2").send(player);
return;
if (page == totalPages && totalPages != 0) { // Back
new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$3")
.text(C.CLICKABLE.s()).color("$2").send(player);
}
}
}

View File

@@ -20,15 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
@@ -46,6 +37,16 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
@CommandDeclaration(
command = "template",
permission = "plots.admin",
@@ -55,7 +56,6 @@ category = CommandCategory.ADMINISTRATION)
public class Template extends SubCommand {
public static boolean extractAllFiles(final String world, final String template) {
final byte[] buffer = new byte[2048];
try {
final File folder = new File(PS.get().IMP.getDirectory() + File.separator + "templates");
if (!folder.exists()) {
@@ -66,24 +66,28 @@ public class Template extends SubCommand {
if (!output.exists()) {
output.mkdirs();
}
final ZipInputStream zis = new ZipInputStream(new FileInputStream(input));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
final String name = ze.getName().replace('\\', File.separatorChar).replace('/', File.separatorChar);
final File newFile = new File((output + File.separator + name).replaceAll("__TEMP_DIR__", world));
new File(newFile.getParent()).mkdirs();
final FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input))) {
ZipEntry ze = zis.getNextEntry();
final byte[] buffer = new byte[2048];
while (ze != null) {
final String name = ze.getName().replace('\\', File.separatorChar).replace('/', File.separatorChar);
final File newFile = new File((output + File.separator + name).replaceAll("__TEMP_DIR__", world));
new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
ze = zis.getNextEntry();
}
fos.close();
ze = zis.getNextEntry();
zis.closeEntry();
}
zis.closeEntry();
zis.close();
return true;
} catch (final Exception e) {
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
@@ -105,21 +109,21 @@ public class Template extends SubCommand {
public static void zipAll(final String world, final Set<FileBytes> files) throws IOException {
final File output = new File(PS.get().IMP.getDirectory() + File.separator + "templates");
output.mkdirs();
final FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template");
final ZipOutputStream zos = new ZipOutputStream(fos);
for (final FileBytes file : files) {
final ZipEntry ze = new ZipEntry(file.path);
zos.putNextEntry(ze);
zos.write(file.data);
try (FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template");
ZipOutputStream zos = new ZipOutputStream(fos)) {
for (final FileBytes file : files) {
final ZipEntry ze = new ZipEntry(file.path);
zos.putNextEntry(ze);
zos.write(file.data);
}
zos.closeEntry();
}
zos.closeEntry();
zos.close();
}
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
if ((args.length != 2) && (args.length != 3)) {
if (args.length != 2 && args.length != 3) {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("export")) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export <world>");
@@ -186,7 +190,7 @@ public class Template extends SubCommand {
});
return true;
}
case "export": {
case "export":
if (args.length != 2) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export <world>");
return false;
@@ -197,25 +201,22 @@ public class Template extends SubCommand {
return false;
}
final PlotManager manager = area.getPlotManager();
final PlotPlayer finalPlr = plr;
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
try {
manager.exportTemplate(area);
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
MainUtil.sendMessage(finalPlr, "Failed: " + e.getMessage());
MainUtil.sendMessage(plr, "Failed: " + e.getMessage());
return;
}
MainUtil.sendMessage(finalPlr, "Done!");
MainUtil.sendMessage(plr, "Done!");
}
});
return true;
}
default: {
default:
C.COMMAND_SYNTAX.send(plr, getUsage());
}
}
return false;
}

View File

@@ -20,11 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
@@ -34,6 +29,11 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
@CommandDeclaration(
command = "toggle",
aliases = { "attribute" },
@@ -44,25 +44,12 @@ requiredType = RequiredType.NONE,
category = CommandCategory.SETTINGS)
public class Toggle extends SubCommand {
public void noArgs(final PlotPlayer plr) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot toggle <setting>");
final ArrayList<String> options = new ArrayList<>();
for (final Entry<String, Command<PlotPlayer>> entry : toggles.entrySet()) {
if (Permissions.hasPermission(plr, entry.getValue().getPermission())) {
options.add(entry.getKey());
}
}
if (options.size() > 0) {
MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan.join(options, ","));
}
}
private HashMap<String, Command<PlotPlayer>> toggles;
public Toggle() {
toggles = new HashMap<>();
toggles.put("titles", new Command<PlotPlayer>("titles", "/plot toggle titles", "Toggle titles for yourself", C.PERMISSION_PLOT_TOGGLE_TITLES.s()) {
@Override
public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "disabletitles")) {
@@ -74,7 +61,7 @@ public class Toggle extends SubCommand {
}
});
toggles.put("chatspy", new Command<PlotPlayer>("chatspy", "/plot toggle chatspy", "Toggle chat spying", C.PERMISSION_COMMANDS_CHAT.s()) {
@Override
public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "chatspy")) {
@@ -86,7 +73,7 @@ public class Toggle extends SubCommand {
}
});
toggles.put("chat", new Command<PlotPlayer>("chat", "/plot toggle chat", "Toggle plot chat for yourself", C.PERMISSION_PLOT_TOGGLE_CHAT.s()) {
@Override
public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "chat")) {
@@ -99,7 +86,7 @@ public class Toggle extends SubCommand {
});
if (PS.get() != null && PS.get().worldedit != null) {
toggles.put("worldedit", new Command<PlotPlayer>("worldedit", "/plot toggle worldedit", "Toggle worldedit bypass", C.PERMISSION_WORLDEDIT_BYPASS.s()) {
@Override
public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "worldedit")) {
@@ -111,7 +98,20 @@ public class Toggle extends SubCommand {
}
});
}
}
public void noArgs(final PlotPlayer plr) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot toggle <setting>");
final ArrayList<String> options = new ArrayList<>();
for (final Entry<String, Command<PlotPlayer>> entry : toggles.entrySet()) {
if (Permissions.hasPermission(plr, entry.getValue().getPermission())) {
options.add(entry.getKey());
}
}
if (!options.isEmpty()) {
MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan.join(options, ","));
}
}
@Override

View File

@@ -20,15 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.ChunkLoc;
@@ -43,6 +34,15 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
@CommandDeclaration(
command = "trim",
permission = "plots.admin",
@@ -76,7 +76,7 @@ public class Trim extends SubCommand {
final int z = Integer.parseInt(split[2]);
final ChunkLoc loc = new ChunkLoc(x, z);
empty.add(loc);
} catch (final Exception e) {
} catch (NumberFormatException e) {
PS.debug("INVALID MCA: " + name);
}
} else {
@@ -97,7 +97,7 @@ public class Trim extends SubCommand {
PS.debug("INVALID MCA: " + name);
}
}
} catch (IOException e) {
} catch (IOException ignored) {
}
}
}
@@ -127,7 +127,7 @@ public class Trim extends SubCommand {
public void run() {
final long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < 50) {
if (plots.size() == 0) {
if (plots.isEmpty()) {
empty.addAll(chunks);
Trim.TASK = false;
TaskManager.runTaskAsync(whenDone);

View File

@@ -20,14 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Plot;
@@ -39,11 +31,19 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
@CommandDeclaration(
command = "visit",
permission = "plots.visit",
description = "Visit someones plot",
usage = "/plot visit [player|alias|world|id] [#]",
usage = "/plot visit [player|alias|world|type] [#]",
aliases = { "v", "tp", "teleport", "goto" },
requiredType = RequiredType.NONE,
category = CommandCategory.TELEPORT)
@@ -110,7 +110,7 @@ public class Visit extends SubCommand {
if (page == Integer.MIN_VALUE) {
page = 1;
}
if (unsorted == null || unsorted.size() == 0) {
if (unsorted == null || unsorted.isEmpty()) {
sendMessage(player, C.FOUND_NO_PLOTS);
return false;
}

View File

@@ -20,15 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.PS.SortType;
import com.intellectualcrafters.plot.config.C;
@@ -49,6 +40,15 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(
command = "list",
aliases = { "l", "find", "search" },
@@ -346,8 +346,8 @@ public class list extends SubCommand {
sendMessage(plr, C.DID_YOU_MEAN, new StringComparison<String>(args[0], new String[] { "mine", "shared", "world", "all" }).getBestMatch());
return false;
}
if (plots.size() == 0) {
if (plots.isEmpty()) {
MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS);
return false;
}
@@ -384,7 +384,7 @@ public class list extends SubCommand {
final PlotMessage trusted = new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s().replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))).color("$1");
final PlotMessage members = new PlotMessage().text(C.color(C.PLOT_INFO_MEMBERS.s().replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))).color("$1");
String strFlags = StringMan.join(plot.getFlags().values(), ",");
if (strFlags.length() == 0) {
if (strFlags.isEmpty()) {
strFlags = C.NONE.s();
}
final PlotMessage flags = new PlotMessage().text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))).color("$1");

View File

@@ -20,6 +20,13 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.config;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.CommandCaller;
import java.io.File;
import java.util.EnumSet;
import java.util.HashMap;
@@ -28,13 +35,6 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.CommandCaller;
/**
* Captions class.
*
@@ -150,7 +150,7 @@ public enum C {
CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"),
CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"),
CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"),
CLUSTER_INFO("$1Current cluster: $2%id%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", "Cluster"),
CLUSTER_INFO("$1Current cluster: $2%type%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", "Cluster"),
/*
* Border
*/
@@ -187,7 +187,7 @@ public enum C {
*/
SWAP_OVERLAP("$2The proposed areas are not allowed to overlap", "Swap"),
SWAP_DIMENSIONS("$2The proposed areas must have comparable dimensions", "Swap"),
SWAP_SYNTAX("$2/plots swap <plot id>", "Swap"),
SWAP_SYNTAX("$2/plots swap <plot type>", "Swap"),
SWAP_SUCCESS("$4Successfully swapped plots", "Swap"),
STARTED_SWAP("$2Started plot swap task. You will be notified when it finishes", "Swap"),
/*
@@ -225,7 +225,7 @@ public enum C {
PASTED("$4The plot selection was successfully pasted. It has been cleared from your clipboard.", "Clipboard"),
PASTE_FAILED("$2Failed to paste the selection. Reason: $2%s", "Clipboard"),
NO_CLIPBOARD("$2You don't have a selection in your clipboard", "Clipboard"),
CLIPBOARD_INFO("$2Current Selection - Plot ID: $1%id$2, Width: $1%width$2, Total Blocks: $1%total$2", "Clipboard"),
CLIPBOARD_INFO("$2Current Selection - Plot ID: $1%type$2, Width: $1%width$2, Total Blocks: $1%total$2", "Clipboard"),
/*
* Toggle
*/
@@ -298,8 +298,8 @@ public enum C {
*/
TITLE_ENTERED_PLOT("$1Plot: %world%;%x%;%z%", "Titles"),
TITLE_ENTERED_PLOT_SUB("$4Owned by %s", "Titles"),
PREFIX_GREETING("$1%id%$2> ", "Titles"),
PREFIX_FAREWELL("$1%id%$2> ", "Titles"),
PREFIX_GREETING("$1%type%$2> ", "Titles"),
PREFIX_FAREWELL("$1%type%$2> ", "Titles"),
/*
* Core Stuff
*/
@@ -315,7 +315,7 @@ public enum C {
/*
* BarAPI
*/
BOSSBAR_CLEARING("$2Clearing plot: $1%id%", "Bar API"),
BOSSBAR_CLEARING("$2Clearing plot: $1%type%", "Bar API"),
DESC_SET("$2Plot description set", "Desc"),
DESC_UNSET("$2Plot description unset", "Desc"),
@@ -443,12 +443,12 @@ public enum C {
/*
* Invalid
*/
NOT_VALID_DATA("$2That's not a valid data id.", "Invalid"),
NOT_VALID_DATA("$2That's not a valid data type.", "Invalid"),
NOT_VALID_BLOCK("$2That's not a valid block: %s", "Invalid"),
NOT_ALLOWED_BLOCK("$2That block is not allowed: %s", "Invalid"),
NOT_VALID_NUMBER("$2That's not a valid number within the range: %s", "Invalid"),
NOT_VALID_PLOT_ID("$2That's not a valid plot id.", "Invalid"),
PLOT_ID_FORM("$2The plot id must be in the form: $1X;Y $2e.g. $1-5;7", "Invalid"),
NOT_VALID_PLOT_ID("$2That's not a valid plot type.", "Invalid"),
PLOT_ID_FORM("$2The plot type must be in the form: $1X;Y $2e.g. $1-5;7", "Invalid"),
NOT_YOUR_PLOT("$2That is not your plot.", "Invalid"),
NO_SUCH_PLOT("$2There is no such plot", "Invalid"),
PLAYER_HAS_NOT_BEEN_ON("$2That player hasn't been in the plotworld", "Invalid"),
@@ -463,7 +463,7 @@ public enum C {
*/
NEED_PLOT_NUMBER("$2You've got to specify a plot number or alias", "Need"),
NEED_BLOCK("$2You've got to specify a block", "Need"),
NEED_PLOT_ID("$2You've got to specify a plot id.", "Need"),
NEED_PLOT_ID("$2You've got to specify a plot type.", "Need"),
NEED_PLOT_WORLD("$2You've got to specify a plot area.", "Need"),
NEED_USER("$2You need to specify a username", "Need"),
/*
@@ -475,7 +475,7 @@ public enum C {
PLOT_UNOWNED("$2The current plot must have an owner to perform this action", "Info"),
PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"),
PLOT_INFO_HEADER("$3&m---------&r $1INFO $3&m---------", false, "Info"),
PLOT_INFO("$1ID: $2%id%$1&-"
PLOT_INFO("$1ID: $2%type%$1&-"
+ "$1Alias: $2%alias%$1&-"
+ "$1Owner: $2%owner%$1&-"
+ "$1Biome: $2%biome%$1&-"
@@ -493,7 +493,7 @@ public enum C {
PLOT_INFO_BIOME("$1Biome:$2 %biome%", "Info"),
PLOT_INFO_RATING("$1Rating:$2 %rating%", "Info"),
PLOT_INFO_OWNER("$1Owner:$2 %owner%", "Info"),
PLOT_INFO_ID("$1ID:$2 %id%", "Info"),
PLOT_INFO_ID("$1ID:$2 %type%", "Info"),
PLOT_INFO_ALIAS("$1Alias:$2 %alias%", "Info"),
PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"),
PLOT_USER_LIST(" $1%user%$2,", "Info"),
@@ -521,8 +521,8 @@ public enum C {
AREA_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% areas", "List"),
PLOT_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% plots", "List"),
PLOT_LIST_HEADER("$1List of %word% plots", "List"),
PLOT_LIST_ITEM("$2>> $1%id$2:$1%world $2- $1%owner", "List"),
PLOT_LIST_ITEM_ORDERED("$2[$1%in$2] >> $1%id$2:$1%world $2- $1%owner", "List"),
PLOT_LIST_ITEM("$2>> $1%type$2:$1%world $2- $1%owner", "List"),
PLOT_LIST_ITEM_ORDERED("$2[$1%in$2] >> $1%type$2:$1%world $2- $1%owner", "List"),
PLOT_LIST_FOOTER("$2>> $1%word% a total of $2%num% $1claimed %plot%.", "List"),
/*
* Left
@@ -595,7 +595,7 @@ public enum C {
/*
* Signs
*/
OWNER_SIGN_LINE_1("$1ID: $1%id%", "Signs"),
OWNER_SIGN_LINE_1("$1ID: $1%type%", "Signs"),
OWNER_SIGN_LINE_2("$1Owner:", "Signs"),
OWNER_SIGN_LINE_3("$2%plr%", "Signs"),
OWNER_SIGN_LINE_4("$3Claimed", "Signs"),
@@ -670,11 +670,6 @@ public enum C {
this(d, true, cat.toLowerCase());
}
@Override
public String toString() {
return s;
}
public static String format(String m, final Object... args) {
if (args.length == 0) {
return m;
@@ -683,7 +678,7 @@ public enum C {
if (args.length > 0) {
for (int i = args.length - 1; i >= 0; i--) {
String arg = args[i].toString();
if (arg == null || arg.length() == 0) {
if (arg == null || arg.isEmpty()) {
map.put("%s" + i, "");
} else {
arg = C.color(arg);
@@ -784,6 +779,11 @@ public enum C {
e.printStackTrace();
}
}
@Override
public String toString() {
return s;
}
public String s() {
return s;

View File

@@ -20,15 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.database;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
@@ -38,6 +29,15 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.comment.PlotComment;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
@@ -123,7 +123,7 @@ public interface AbstractDB {
int getId(final Plot plot);
/**
* Get the id of a given plot cluster
* Get the type of a given plot cluster
*
* @param cluster PlotCluster Object
*
@@ -193,15 +193,14 @@ public interface AbstractDB {
/**
* Purgle a plot
*
* @param world World in which the plot is located
* @param uniqueIds list of plot id (db) to be purged
* @param uniqueIds list of plot type (db) to be purged
*/
void purgeIds(final Set<Integer> uniqueIds);
/**
* Purge a whole world
*
* @param world World in which the plots should be purged
* @param area World in which the plots should be purged
*/
void purge(final PlotArea area, final Set<PlotId> plotIds);

View File

@@ -20,6 +20,14 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.database;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.comment.PlotComment;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
@@ -30,14 +38,6 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.comment.PlotComment;
/**
* Database Functions
* - These functions do not update the local plot objects and only make changes to the DB
@@ -241,7 +241,7 @@ public class DBFunc {
}
/**
* Get a plot id
* Get a plot type
*
* @param plot Plot Object
*
@@ -250,10 +250,10 @@ public class DBFunc {
/*
* public static int getId(String plotId id2) { Statement stmt =
* null; try { stmt = connection.createStatement(); ResultSet r =
* stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x
* stmt.executeQuery("SELECT `type` FROM `plot` WHERE `plot_id_x` = '" + id2.x
* + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world +
* "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE;
* while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; }
* "' ORDER BY `timestamp` ASC"); int type = Integer.MAX_VALUE;
* while(r.next()) { type = r.getInt("type"); } stmt.close(); return type; }
* catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE;
* }
*/

View File

@@ -24,7 +24,9 @@ import com.intellectualcrafters.plot.util.StringMan;
/**
* Created 2014-09-23 for PlotSquared
*
*
*/
public class AbstractFlag {
public final String key;
@@ -105,6 +107,6 @@ public class AbstractFlag {
return false;
}
final AbstractFlag otherObj = (AbstractFlag) other;
}
return otherObj.key.equals(key);
}
}

View File

@@ -20,10 +20,11 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.flag;
import java.lang.reflect.Method;
import com.intellectualcrafters.plot.util.StringMan;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Flag implements Cloneable {
private AbstractFlag key;
private Object value;
@@ -51,13 +52,6 @@ public class Flag implements Cloneable {
}
}
public void setKey(final AbstractFlag key) {
this.key = key;
if (value instanceof String) {
value = key.parseValueRaw((String) value);
}
}
/**
* Warning: Unchecked
*/
@@ -83,7 +77,14 @@ public class Flag implements Cloneable {
public String getKey() {
return key.getKey();
}
public void setKey(final AbstractFlag key) {
this.key = key;
if (value instanceof String) {
value = key.parseValueRaw((String) value);
}
}
/**
* Get the value
*
@@ -99,7 +100,7 @@ public class Flag implements Cloneable {
@Override
public String toString() {
if (value.equals("")) {
if ("".equals(value)) {
return key.getKey();
}
return key + ":" + getValueString();
@@ -117,7 +118,7 @@ public class Flag implements Cloneable {
return false;
}
final Flag other = (Flag) obj;
return (key.getKey().equals(other.key.getKey()) && value.equals(other.value));
return key.getKey().equals(other.key.getKey()) && value.equals(other.value);
}
@Override
@@ -139,7 +140,22 @@ public class Flag implements Cloneable {
return new Flag(key, method.invoke(value));
}
return new Flag(key, key.parseValueRaw(value.toString()));
} catch (Exception e) {
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return this;
} catch (IllegalAccessException e) {
e.printStackTrace();
return this;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return this;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return this;
} catch (SecurityException e) {
e.printStackTrace();
return this;
} catch (InvocationTargetException e) {
e.printStackTrace();
return this;
}

View File

@@ -115,7 +115,7 @@ public class FlagManager {
}
}
});
if ((getFlag(af.getKey()) == null) && flags.add(af)) {
if (getFlag(af.getKey()) == null && flags.add(af)) {
if (reserved) {
reserveFlag(af.getKey());
}
@@ -126,11 +126,11 @@ public class FlagManager {
public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) {
Flag flag;
if ((settings.flags.size() == 0) || ((flag = settings.flags.get(id)) == null)) {
if (settings.flags.isEmpty() || (flag = settings.flags.get(id)) == null) {
if (area == null) {
return null;
}
if (area.DEFAULT_FLAGS.size() == 0) {
if (area.DEFAULT_FLAGS.isEmpty()) {
return null;
}
return area.DEFAULT_FLAGS.get(id);
@@ -181,7 +181,7 @@ public class FlagManager {
return false;
}
final Flag flag = getPlotFlagRaw(plot, strFlag);
return !((flag == null) || !((Boolean) flag.getValue()));
return !(flag == null || !((Boolean) flag.getValue()));
}
public static boolean isPlotFlagFalse(final Plot plot, final String strFlag) {
@@ -189,7 +189,7 @@ public class FlagManager {
return false;
}
final Flag flag = getPlotFlagRaw(plot, strFlag);
if ((flag == null) || ((Boolean) flag.getValue())) {
if (flag == null || (Boolean) flag.getValue()) {
return false;
}
return false;
@@ -206,7 +206,7 @@ public class FlagManager {
}
public static Flag getSettingFlagAbs(final PlotSettings settings, final String flag) {
if ((settings.flags == null) || (settings.flags.size() == 0)) {
if (settings.flags == null || settings.flags.isEmpty()) {
return null;
}
return settings.flags.get(flag);
@@ -260,7 +260,7 @@ public class FlagManager {
public static HashMap<String, Flag> getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) {
final HashMap<String, Flag> flags = new HashMap<>();
if ((area != null) && (area.DEFAULT_FLAGS.size() != 0)) {
if (area != null && !area.DEFAULT_FLAGS.isEmpty()) {
flags.putAll(area.DEFAULT_FLAGS);
}
if (ignorePluginflags) {
@@ -312,12 +312,12 @@ public class FlagManager {
public static void setPlotFlags(final Plot origin, final Set<Flag> flags) {
for (Plot plot : origin.getConnectedPlots()) {
if ((flags != null) && (flags.size() != 0)) {
if (flags != null && !flags.isEmpty()) {
plot.getFlags().clear();
for (final Flag flag : flags) {
plot.getFlags().put(flag.getKey(), flag);
}
} else if (plot.getFlags().size() == 0) {
} else if (plot.getFlags().isEmpty()) {
return;
} else {
plot.getFlags().clear();
@@ -328,12 +328,12 @@ public class FlagManager {
}
public static void setClusterFlags(final PlotCluster cluster, final Set<Flag> flags) {
if ((flags != null) && (flags.size() != 0)) {
if (flags != null && !flags.isEmpty()) {
cluster.settings.flags.clear();
for (final Flag flag : flags) {
cluster.settings.flags.put(flag.getKey(), flag);
}
} else if (cluster.settings.flags.size() == 0) {
} else if (cluster.settings.flags.isEmpty()) {
return;
} else {
cluster.settings.flags.clear();
@@ -413,7 +413,7 @@ public class FlagManager {
* @return AbstractFlag
*/
public static AbstractFlag getFlag(final String string, final boolean create) {
if ((getFlag(string) == null) && create) {
if (getFlag(string) == null && create) {
return new AbstractFlag(string);
}
return getFlag(string);

View File

@@ -1,7 +1,5 @@
package com.intellectualcrafters.plot.generator;
import java.util.Set;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock;
@@ -12,6 +10,8 @@ import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import java.util.Set;
public class AugmentedUtils {
private static boolean enabled = true;
@@ -30,7 +30,7 @@ public class AugmentedUtils {
final int bz = cz << 4;
RegionWrapper region = new RegionWrapper(bx, bx + 15, bz, bz + 15);
Set<PlotArea> areas = PS.get().getPlotAreas(world, region);
if (areas.size() == 0) {
if (areas.isEmpty()) {
return;
}
final PseudoRandom r = new PseudoRandom();

View File

@@ -20,14 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.generator;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.Template;
import com.intellectualcrafters.plot.object.ChunkLoc;
@@ -44,6 +36,14 @@ import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.WorldUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
public class HybridPlotManager extends ClassicPlotManager {
@Override
@@ -66,7 +66,7 @@ public class HybridPlotManager extends ClassicPlotManager {
if (plot.exists()) {
files.add(new FileBytes(newDir + "plot.schematic", Files.readAllBytes(plot.toPath())));
}
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
}
Template.zipAll(plotworld.worldname, files);

View File

@@ -20,9 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.generator;
import java.util.HashMap;
import java.util.HashSet;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
@@ -35,21 +32,133 @@ import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SchematicHandler.Dimension;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
public class HybridPlotWorld extends ClassicPlotWorld {
public HybridPlotWorld(String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) {
super(worldname, id, generator, min, max);
}
import java.util.HashMap;
import java.util.HashSet;
public class HybridPlotWorld extends ClassicPlotWorld {
public boolean ROAD_SCHEMATIC_ENABLED;
public short SCHEMATIC_HEIGHT;
public boolean PLOT_SCHEMATIC = false;
public short REQUIRED_CHANGES = 0;
public short PATH_WIDTH_LOWER;
public short PATH_WIDTH_UPPER;
public HashMap<Integer, HashMap<Integer, PlotBlock>> G_SCH;
public HashMap<Integer, HashSet<PlotItem>> G_SCH_STATE;
public HybridPlotWorld(String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) {
super(worldname, id, generator, min, max);
}
public static byte wrap(byte data, final int start) {
if ((data >= start) && (data < (start + 4))) {
data = (byte) ((((data - start) + 2) & 3) + start);
}
return data;
}
public static byte wrap2(byte data, final int start) {
if ((data >= start) && (data < (start + 2))) {
data = (byte) ((((data - start) + 1) & 1) + start);
}
return data;
}
// FIXME depends on block ids
// Possibly make abstract?
public static byte rotate(final short id, byte data) {
switch (id) {
case 162:
case 17:
if (data >= 4 && data < 12) {
if (data >= 8) {
return (byte) (data - 4);
}
return (byte) (data + 4);
}
return data;
case 183:
case 184:
case 185:
case 186:
case 187:
case 107:
case 53:
case 67:
case 108:
case 109:
case 114:
case 128:
case 134:
case 135:
case 136:
case 156:
case 163:
case 164:
case 180:
data = wrap(data, 0);
data = wrap(data, 4);
return data;
case 26:
case 86:
data = wrap(data, 0);
return data;
case 64:
case 71:
case 193:
case 194:
case 195:
case 196:
case 197:
case 93:
case 94:
case 131:
case 145:
case 149:
case 150:
case 96:
case 167:
data = wrap(data, 0);
data = wrap(data, 4);
data = wrap(data, 8);
data = wrap(data, 12);
return data;
case 28:
case 66:
case 157:
case 27:
data = wrap2(data, 0);
data = wrap2(data, 3);
if (data == 2) {
data = 5;
} else if (data == 5) {
data = 2;
}
return data;
case 23:
case 29:
case 33:
case 158:
case 54:
case 130:
case 146:
case 61:
case 62:
case 65:
case 68:
case 144:
data = wrap(data, 2);
return data;
case 143:
case 77:
data = wrap(data, 1);
return data;
default:
return data;
}
}
/**
* This method is called when a world loads. Make sure you set all your constants here. You are provided with the
* configuration section for that specific world.
@@ -72,10 +181,10 @@ public class HybridPlotWorld extends ClassicPlotWorld {
@Override
public boolean isCompatible(PlotArea plotworld) {
if (plotworld == null || !(plotworld instanceof SquarePlotWorld)) {
if (!(plotworld instanceof SquarePlotWorld)) {
return false;
}
return ((ClassicPlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH;
return ((SquarePlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH;
}
public void setupSchematics() {
@@ -99,11 +208,11 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short w3 = (short) d3.getX();
final short l3 = (short) d3.getZ();
final short h3 = (short) d3.getY();
int center_shift_x = 0;
int center_shift_z = 0;
if (l3 < PLOT_WIDTH) {
center_shift_z = (PLOT_WIDTH - l3) / 2;
}
int center_shift_x = 0;
if (w3 < PLOT_WIDTH) {
center_shift_x = (PLOT_WIDTH - w3) / 2;
}
@@ -114,7 +223,8 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short id = ids[index];
final byte data = datas[index];
if (id != 0) {
addOverlayBlock((short) (x + shift + oddshift + center_shift_x), (y), (short) (z + shift + oddshift + center_shift_z), id, data, false);
addOverlayBlock((short) (x + shift + oddshift + center_shift_x), y, (short) (z + shift + oddshift + center_shift_z), id,
data, false);
}
}
}
@@ -136,20 +246,20 @@ public class HybridPlotWorld extends ClassicPlotWorld {
}
}
}
if ((schem1 == null) || (schem2 == null) || (ROAD_WIDTH == 0)) {
if (schem1 == null || schem2 == null || ROAD_WIDTH == 0) {
PS.debug(C.PREFIX.s() + "&3 - schematic: &7false");
return;
}
ROAD_SCHEMATIC_ENABLED = true;
// Do not populate road if using schematic population
ROAD_BLOCK = new PlotBlock(ROAD_BLOCK.id, (byte) 0);
final short[] ids1 = schem1.getIds();
final byte[] datas1 = schem1.getDatas();
final short[] ids2 = schem2.getIds();
final byte[] datas2 = schem2.getDatas();
final Dimension d1 = schem1.getSchematicDimension();
final short w1 = (short) d1.getX();
final short l1 = (short) d1.getZ();
@@ -166,8 +276,8 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short id = ids1[index];
final byte data = datas1[index];
if (id != 0) {
addOverlayBlock((short) (x - (shift)), (y), (short) (z + shift + oddshift), id, data, false);
addOverlayBlock((short) (z + shift + oddshift), (y), (short) (x - shift), id, data, true);
addOverlayBlock((short) (x - shift), y, (short) (z + shift + oddshift), id, data, false);
addOverlayBlock((short) (z + shift + oddshift), y, (short) (x - shift), id, data, true);
}
}
}
@@ -179,130 +289,13 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short id = ids2[index];
final byte data = datas2[index];
if (id != 0) {
addOverlayBlock((short) (x - shift), (y), (short) (z - shift), id, data, false);
addOverlayBlock((short) (x - shift), y, (short) (z - shift), id, data, false);
}
}
}
}
}
public static byte wrap(byte data, final int start) {
if ((data >= start) && (data < (start + 4))) {
data = (byte) ((((data - start) + 2) & 3) + start);
}
return data;
}
public static byte wrap2(byte data, final int start) {
if ((data >= start) && (data < (start + 2))) {
data = (byte) ((((data - start) + 1) & 1) + start);
}
return data;
}
// FIXME depends on block ids
// Possibly make abstract?
public static byte rotate(final short id, byte data) {
switch (id) {
case 162:
case 17: {
if ((data >= 4) && (data < 12)) {
if (data >= 8) {
return (byte) (data - 4);
}
return (byte) (data + 4);
}
return data;
}
case 183:
case 184:
case 185:
case 186:
case 187:
case 107:
case 53:
case 67:
case 108:
case 109:
case 114:
case 128:
case 134:
case 135:
case 136:
case 156:
case 163:
case 164:
case 180: {
data = wrap(data, 0);
data = wrap(data, 4);
return data;
}
case 26:
case 86: {
data = wrap(data, 0);
return data;
}
case 64:
case 71:
case 193:
case 194:
case 195:
case 196:
case 197:
case 93:
case 94:
case 131:
case 145:
case 149:
case 150:
case 96:
case 167: {
data = wrap(data, 0);
data = wrap(data, 4);
data = wrap(data, 8);
data = wrap(data, 12);
return data;
}
case 28:
case 66:
case 157:
case 27: {
data = wrap2(data, 0);
data = wrap2(data, 3);
if (data == 2) {
data = 5;
} else if (data == 5) {
data = 2;
}
return data;
}
case 23:
case 29:
case 33:
case 158:
case 54:
case 130:
case 146:
case 61:
case 62:
case 65:
case 68:
case 144: {
data = wrap(data, 2);
return data;
}
case 143:
case 77: {
data = wrap(data, 1);
return data;
}
default:
return data;
}
}
public void addOverlayBlock(short x, final short y, short z, final short id, byte data, final boolean rotate) {
if (z < 0) {
z += SIZE;
@@ -312,7 +305,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
}
if (rotate) {
final byte newdata = rotate(id, data);
if ((data == 0) && (newdata == 0)) {
if (data == 0 && newdata == 0) {
return;
}
data = newdata;

View File

@@ -36,17 +36,21 @@ import java.util.concurrent.atomic.AtomicInteger;
public abstract class HybridUtils {
public static HybridUtils manager;
public static Set<ChunkLoc> regions;
public static Set<ChunkLoc> chunks = new HashSet<>();
public static PlotArea area;
public static boolean UPDATE = false;
public abstract void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal<PlotAnalysis> whenDone);
public void analyzePlot(final Plot origin, final RunnableVal<PlotAnalysis> whenDone) {
final ArrayDeque<RegionWrapper> zones = new ArrayDeque<>(origin.getRegions());
final ArrayList<PlotAnalysis> analysis = new ArrayList<>();
Runnable run = new Runnable() {
@Override
public void run() {
if (zones.size() == 0) {
if (analysis.size() > 0) {
if (zones.isEmpty()) {
if (!analysis.isEmpty()) {
whenDone.value = new PlotAnalysis();
for (PlotAnalysis data : analysis) {
whenDone.value.air += data.air;
@@ -80,7 +84,7 @@ public abstract class HybridUtils {
result.add(whenDone.value.data);
result.add(whenDone.value.air);
result.add(whenDone.value.variety);
result.add(whenDone.value.changes_sd);
result.add(whenDone.value.faces_sd);
result.add(whenDone.value.data_sd);
@@ -104,14 +108,9 @@ public abstract class HybridUtils {
};
run.run();
}
public abstract int checkModified(final String world, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks);
public static Set<ChunkLoc> regions;
public static Set<ChunkLoc> chunks = new HashSet<>();
public static PlotArea area;
public static boolean UPDATE = false;
public final ArrayList<ChunkLoc> getChunks(final ChunkLoc region) {
final ArrayList<ChunkLoc> chunks = new ArrayList<>();
final int sx = region.x << 5;
@@ -145,7 +144,7 @@ public abstract class HybridUtils {
Runnable run = new Runnable() {
@Override
public void run() {
if (zones.size() == 0) {
if (zones.isEmpty()) {
TaskManager.runTask(whenDone);
return;
@@ -209,7 +208,7 @@ public abstract class HybridUtils {
if ((count.intValue() % 20) == 0) {
PS.debug("PROGRESS: " + ((100 * (2048 - chunks.size())) / 2048) + "%");
}
if ((regions.size() == 0) && (chunks.size() == 0)) {
if ((regions.isEmpty()) && (chunks.isEmpty())) {
HybridUtils.UPDATE = false;
PS.debug(C.PREFIX.s() + "Finished road conversion");
// CANCEL TASK
@@ -223,7 +222,7 @@ public abstract class HybridUtils {
last.set((int) (System.currentTimeMillis() - baseTime));
}
if (chunks.size() < 1024) {
if (regions.size() > 0) {
if (!regions.isEmpty()) {
Iterator<ChunkLoc> iter = regions.iterator();
final ChunkLoc loc = iter.next();
iter.remove();
@@ -233,7 +232,7 @@ public abstract class HybridUtils {
System.gc();
}
}
if (chunks.size() > 0) {
if (!chunks.isEmpty()) {
final long diff = System.currentTimeMillis() + 1;
if (((System.currentTimeMillis() - baseTime - last.get()) > 2000) && (last.get() != 0)) {
last.set(0);
@@ -252,7 +251,7 @@ public abstract class HybridUtils {
return;
}
if ((((System.currentTimeMillis() - baseTime) - last.get()) < 1500) && (last.get() != 0)) {
while ((System.currentTimeMillis() < diff) && (chunks.size() > 0)) {
while ((System.currentTimeMillis() < diff) && (!chunks.isEmpty())) {
Iterator<ChunkLoc> iter = chunks.iterator();
final ChunkLoc chunk = iter.next();
iter.remove();

View File

@@ -29,8 +29,8 @@ public abstract class IndependentPlotGenerator {
* Return a new PlotArea object
* @param world world name
* @param id (May be null) Area name
* @param min Min plot id (may be null)
* @param max Max plot id (may be null)
* @param min Min plot type (may be null)
* @param max Max plot type (may be null)
* @return
*/
public abstract PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max);

View File

@@ -23,7 +23,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
Runnable run = new Runnable() {
@Override
public void run() {
if (regions.size() == 0) {
if (regions.isEmpty()) {
whenDone.run();
return;
}

View File

@@ -4,20 +4,15 @@ import com.intellectualcrafters.plot.PS;
/**
* Created 2015-02-11 for PlotSquared
*
*
*/
public class Location implements Cloneable, Comparable<Location> {
private int x, y, z;
private float yaw, pitch;
private String world;
private boolean built;
private boolean built;
private final Object o;
@Override
public Location clone() {
return new Location(world, x, y, z, yaw, pitch);
}
public Location(final String world, final int x, final int y, final int z, final float yaw, final float pitch) {
this.world = world;
this.x = x;
@@ -26,7 +21,6 @@ public class Location implements Cloneable, Comparable<Location> {
this.yaw = yaw;
this.pitch = pitch;
built = false;
built = false;
}
public Location() {
@@ -36,7 +30,12 @@ public class Location implements Cloneable, Comparable<Location> {
public Location(final String world, final int x, final int y, final int z) {
this(world, x, y, z, 0f, 0f);
}
}
@Override
public Location clone() {
return new Location(world, x, y, z, yaw, pitch);
}
public int getX() {
return x;
}
@@ -67,7 +66,12 @@ public class Location implements Cloneable, Comparable<Location> {
public String getWorld() {
return world;
}
}
public void setWorld(final String world) {
this.world = world;
built = false;
}
public PlotArea getPlotArea() {
return PS.get().getPlotAreaAbs(this);
}
@@ -76,7 +80,7 @@ public class Location implements Cloneable, Comparable<Location> {
PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getOwnedPlot(this) : null;
}
}
public Plot getOwnedPlotAbs() {
PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getOwnedPlotAbs(this) : null;
@@ -88,25 +92,19 @@ public class Location implements Cloneable, Comparable<Location> {
public boolean isPlotRoad() {
PlotArea area = PS.get().getPlotAreaAbs(this);
PlotArea area = PS.get().getPlotAreaAbs(this);
if (area == null) {
return false;
}
return area != null && area.getPlotAbs(this) == null;
}
}
public boolean isUnownedPlotArea() {
PlotArea area = PS.get().getPlotAreaAbs(this);
PlotArea area = PS.get().getPlotAreaAbs(this);
if (area == null) {
return false;
}
return area != null && area.getOwnedPlotAbs(this) == null;
}
public PlotManager getPlotManager() {
PlotArea pa = getPlotArea();
return pa != null ? pa.getPlotManager() : null;
}
}
public Plot getPlotAbs() {
PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getPlotAbs(this) : null;
@@ -116,15 +114,10 @@ public class Location implements Cloneable, Comparable<Location> {
PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getPlot(this) : null;
}
}
public ChunkLoc getChunkLoc() {
return new ChunkLoc(x >> 4, z >> 4);
}
}
public void setWorld(final String world) {
this.world = world;
built = false;
public float getYaw() {
return yaw;
@@ -156,7 +149,7 @@ public class Location implements Cloneable, Comparable<Location> {
final double x = getX() - l2.getX();
final double y = getY() - l2.getY();
final double z = getZ() - l2.getZ();
final double z = getZ() - l2.getZ();
return x * x + y * y + z * z;
}
public double getEuclideanDistance(final Location l2) {
@@ -164,32 +157,31 @@ public class Location implements Cloneable, Comparable<Location> {
}
public boolean isInSphere(final Location origin, final int radius) {
public boolean isInSphere(final Location origin, final int radius) {
return getEuclideanDistanceSquared(origin) < radius * radius;
}
@Override
public int hashCode() {
int hash = 127;
int hash = 127;
hash = (hash * 31) + x;
hash = (hash * 31) + y;
hash = (hash * 31) + z;
hash = (int) ((hash * 31) + getYaw());
hash = (int) ((hash * 31) + getPitch());
hash = hash * 31 + x;
hash = hash * 31 + y;
hash = hash * 31 + z;
hash = (int) (hash * 31 + getYaw());
hash = (int) (hash * 31 + getPitch());
return hash * 31 + (world == null ? 127 : world.hashCode());
}
public boolean isInAABB(final Location min, final Location max) {
public boolean isInAABB(final Location min, final Location max) {
return x >= min.getX() && x <= max.getX() && y >= min.getY() && y <= max.getY() && z >= min.getX() && z < max.getZ();
}
public void lookTowards(final int x, final int y) {
final double l = this.x - x;
final double l = this.x - x;
final double w = z - z;
final double c = Math.sqrt((l * l) + (w * w));
if (((Math.asin(w / c) / Math.PI) * 180) > 90) {
final double c = Math.sqrt(l * l + 0.0);
if (Math.asin((double) 0 / c) / Math.PI * 180 > 90) {
setYaw((float) (180 - -Math.asin(l / c) / Math.PI * 180));
} else {
} else {
setYaw((float) (-Math.asin(l / c) / Math.PI * 180));
}
built = false;
}
@@ -211,7 +203,7 @@ public class Location implements Cloneable, Comparable<Location> {
return false;
}
final Location l = (Location) o;
final Location l = (Location) o;
return x == l.getX() && y == l.getY() && z == l.getZ() && world.equals(l.getWorld()) && yaw == l.getY() && pitch == l.getPitch();
}
@Override
@@ -219,10 +211,10 @@ public class Location implements Cloneable, Comparable<Location> {
if (o == null) {
throw new NullPointerException("Specified object was null");
}
}
if (x == o.getX() && y == o.getY() || z == o.getZ()) {
return 0;
}
}
if (x < o.getX() && y < o.getY() && z < o.getZ()) {
return -1;
}
return 1;

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,13 @@
package com.intellectualcrafters.plot.object;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayDeque;
@@ -9,31 +17,22 @@ import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
public class PlotAnalysis {
public static PlotAnalysis MODIFIERS = new PlotAnalysis();
public static boolean running = false;
public int changes;
public int faces;
public int data;
public int air;
public int variety;
public int changes_sd;
public int faces_sd;
public int data_sd;
public int air_sd;
public int variety_sd;
private int complexity;
public static PlotAnalysis MODIFIERS = new PlotAnalysis();
public static PlotAnalysis getAnalysis(final Plot plot) {
final Flag flag = FlagManager.getPlotFlagRaw(plot, "analysis");
if (flag != null) {
@@ -44,46 +43,23 @@ public class PlotAnalysis {
analysis.data = values.get(2); // 0
analysis.air = values.get(3); // 19100
analysis.variety = values.get(4); // 266
analysis.changes_sd = values.get(5); // 2104
analysis.faces_sd = values.get(6); // 89
analysis.data_sd = values.get(7); // 0
analysis.air_sd = values.get(8); // 18909
analysis.variety_sd = values.get(9); // 263
analysis.complexity = analysis.getComplexity();
return analysis;
}
return null;
}
public List<Integer> asList() {
return Arrays.asList(changes, faces, data, air, variety, changes_sd, faces_sd, data_sd, air_sd, variety_sd);
}
public int getComplexity() {
if (complexity != 0) {
return complexity;
}
complexity = ((changes) * MODIFIERS.changes)
+ ((faces) * MODIFIERS.faces)
+ ((data) * MODIFIERS.data)
+ ((air) * MODIFIERS.air)
+ ((variety) * MODIFIERS.variety)
+ ((changes_sd) * MODIFIERS.changes_sd)
+ ((faces_sd) * MODIFIERS.faces_sd)
+ ((data_sd) * MODIFIERS.data_sd)
+ ((air_sd) * MODIFIERS.air_sd)
+ ((variety_sd) * MODIFIERS.variety_sd);
return complexity;
}
public static void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone) {
HybridUtils.manager.analyzePlot(plot, whenDone);
}
public static boolean running = false;
/**
* This will set the optimal modifiers for the plot analysis based on the current plot ratings<br>
* - Will be used to calibrate the threshold for plot clearing
@@ -108,14 +84,14 @@ public class PlotAnalysis {
PS.debug(" - $1Reducing " + plots.size() + " plots to those with sufficient data");
while (iter.hasNext()) {
final Plot plot = iter.next();
if ((plot.getSettings().ratings == null) || (plot.getSettings().ratings.size() == 0)) {
if ((plot.getSettings().ratings == null) || (plot.getSettings().ratings.isEmpty())) {
iter.remove();
} else {
plot.addRunning();
}
}
PS.debug(" - | Reduced to " + plots.size() + " plots");
if (plots.size() < 3) {
PS.debug("Calibration cancelled due to insufficient comparison data, please try again later");
running = false;
@@ -124,25 +100,25 @@ public class PlotAnalysis {
}
return;
}
PS.debug(" - $1Analyzing plot contents (this may take a while)");
final int[] changes = new int[plots.size()];
final int[] faces = new int[plots.size()];
final int[] data = new int[plots.size()];
final int[] air = new int[plots.size()];
final int[] variety = new int[plots.size()];
final int[] changes_sd = new int[plots.size()];
final int[] faces_sd = new int[plots.size()];
final int[] data_sd = new int[plots.size()];
final int[] air_sd = new int[plots.size()];
final int[] variety_sd = new int[plots.size()];
final int[] ratings = new int[plots.size()];
final AtomicInteger mi = new AtomicInteger(0);
final Thread ratingAnalysis = new Thread(new Runnable() {
@Override
public void run() {
@@ -155,7 +131,7 @@ public class PlotAnalysis {
}
});
ratingAnalysis.start();
final ArrayDeque<Plot> plotsQueue = new ArrayDeque<>(plots);
while (true) {
final Plot queuePlot = plotsQueue.poll();
@@ -193,44 +169,44 @@ public class PlotAnalysis {
e.printStackTrace();
}
}
PS.debug(" - $1Waiting on plot rating thread: " + ((mi.intValue() * 100) / plots.size()) + "%");
try {
ratingAnalysis.join();
} catch (final InterruptedException e) {
e.printStackTrace();
}
PS.debug(" - $1Processing and grouping single plot analysis for bulk processing");
for (int i = 0; i < plots.size(); i++) {
final Plot plot = plots.get(i);
PS.debug(" | " + plot);
final PlotAnalysis analysis = plot.getComplexity();
changes[i] = analysis.changes;
faces[i] = analysis.faces;
data[i] = analysis.data;
air[i] = analysis.air;
variety[i] = analysis.variety;
changes_sd[i] = analysis.changes_sd;
faces_sd[i] = analysis.faces_sd;
data_sd[i] = analysis.data_sd;
air_sd[i] = analysis.air_sd;
variety_sd[i] = analysis.variety_sd;
}
PS.debug(" - $1Calculating rankings");
final int[] rank_ratings = rank(ratings);
final int n = rank_ratings.length;
final int optimal_index = (int) Math.round((1 - threshold) * (n - 1));
PS.debug(" - $1Calculating rank correlation: ");
PS.debug(" - The analyzed plots which were processed and put into bulk data will be compared and correlated to the plot ranking");
PS.debug(" - The calculated correlation constant will then be used to calibrate the threshold for auto plot clearing");
final int[] rank_changes = rank(changes);
final int[] sd_changes = getSD(rank_changes, rank_ratings);
final int[] variance_changes = square(sd_changes);
@@ -238,7 +214,7 @@ public class PlotAnalysis {
final double factor_changes = getCC(n, sum_changes);
PlotAnalysis.MODIFIERS.changes = factor_changes == 1 ? 0 : (int) ((factor_changes * 1000) / MathMan.getMean(changes));
PS.debug(" - | changes " + factor_changes);
final int[] rank_faces = rank(faces);
final int[] sd_faces = getSD(rank_faces, rank_ratings);
final int[] variance_faces = square(sd_faces);
@@ -246,7 +222,7 @@ public class PlotAnalysis {
final double factor_faces = getCC(n, sum_faces);
PlotAnalysis.MODIFIERS.faces = factor_faces == 1 ? 0 : (int) ((factor_faces * 1000) / MathMan.getMean(faces));
PS.debug(" - | faces " + factor_faces);
final int[] rank_data = rank(data);
final int[] sd_data = getSD(rank_data, rank_ratings);
final int[] variance_data = square(sd_data);
@@ -254,7 +230,7 @@ public class PlotAnalysis {
final double factor_data = getCC(n, sum_data);
PlotAnalysis.MODIFIERS.data = factor_data == 1 ? 0 : (int) ((factor_data * 1000) / MathMan.getMean(data));
PS.debug(" - | data " + factor_data);
final int[] rank_air = rank(air);
final int[] sd_air = getSD(rank_air, rank_ratings);
final int[] variance_air = square(sd_air);
@@ -262,7 +238,7 @@ public class PlotAnalysis {
final double factor_air = getCC(n, sum_air);
PlotAnalysis.MODIFIERS.air = factor_air == 1 ? 0 : (int) ((factor_air * 1000) / MathMan.getMean(air));
PS.debug(" - | air " + factor_air);
final int[] rank_variety = rank(variety);
final int[] sd_variety = getSD(rank_variety, rank_ratings);
final int[] variance_variety = square(sd_variety);
@@ -270,7 +246,7 @@ public class PlotAnalysis {
final double factor_variety = getCC(n, sum_variety);
PlotAnalysis.MODIFIERS.variety = factor_variety == 1 ? 0 : (int) ((factor_variety * 1000) / MathMan.getMean(variety));
PS.debug(" - | variety " + factor_variety);
final int[] rank_changes_sd = rank(changes_sd);
final int[] sd_changes_sd = getSD(rank_changes_sd, rank_ratings);
final int[] variance_changes_sd = square(sd_changes_sd);
@@ -278,7 +254,7 @@ public class PlotAnalysis {
final double factor_changes_sd = getCC(n, sum_changes_sd);
PlotAnalysis.MODIFIERS.changes_sd = factor_changes_sd == 1 ? 0 : (int) ((factor_changes_sd * 1000) / MathMan.getMean(changes_sd));
PS.debug(" - | changes_sd " + factor_changes_sd);
final int[] rank_faces_sd = rank(faces_sd);
final int[] sd_faces_sd = getSD(rank_faces_sd, rank_ratings);
final int[] variance_faces_sd = square(sd_faces_sd);
@@ -286,7 +262,7 @@ public class PlotAnalysis {
final double factor_faces_sd = getCC(n, sum_faces_sd);
PlotAnalysis.MODIFIERS.faces_sd = factor_faces_sd == 1 ? 0 : (int) ((factor_faces_sd * 1000) / MathMan.getMean(faces_sd));
PS.debug(" - | faces_sd " + factor_faces_sd);
final int[] rank_data_sd = rank(data_sd);
final int[] sd_data_sd = getSD(rank_data_sd, rank_ratings);
final int[] variance_data_sd = square(sd_data_sd);
@@ -294,7 +270,7 @@ public class PlotAnalysis {
final double factor_data_sd = getCC(n, sum_data_sd);
PlotAnalysis.MODIFIERS.data_sd = factor_data_sd == 1 ? 0 : (int) ((factor_data_sd * 1000) / MathMan.getMean(data_sd));
PS.debug(" - | data_sd " + factor_data_sd);
final int[] rank_air_sd = rank(air_sd);
final int[] sd_air_sd = getSD(rank_air_sd, rank_ratings);
final int[] variance_air_sd = square(sd_air_sd);
@@ -302,7 +278,7 @@ public class PlotAnalysis {
final double factor_air_sd = getCC(n, sum_air_sd);
PlotAnalysis.MODIFIERS.air_sd = factor_air_sd == 1 ? 0 : (int) ((factor_air_sd * 1000) / MathMan.getMean(air_sd));
PS.debug(" - | air_sd " + factor_air_sd);
final int[] rank_variety_sd = rank(variety_sd);
final int[] sd_variety_sd = getSD(rank_variety_sd, rank_ratings);
final int[] variance_variety_sd = square(sd_variety_sd);
@@ -310,9 +286,9 @@ public class PlotAnalysis {
final double factor_variety_sd = getCC(n, sum_variety_sd);
PlotAnalysis.MODIFIERS.variety_sd = factor_variety_sd == 1 ? 0 : (int) ((factor_variety_sd * 1000) / MathMan.getMean(variety_sd));
PS.debug(" - | variety_sd " + factor_variety_sd);
final int[] complexity = new int[n];
PS.debug(" $1Calculating threshold");
int max = 0;
int min = 0;
@@ -358,7 +334,7 @@ public class PlotAnalysis {
logln("Ratings: ");
logln(rank_ratings);
}
// Save calibration
PS.debug(" $1Saving calibration");
final YamlConfiguration config = PS.get().config;
@@ -378,7 +354,7 @@ public class PlotAnalysis {
} catch (final IOException e) {
e.printStackTrace();
}
PS.debug("$1Done!");
running = false;
for (final Plot plot : plots) {
@@ -397,7 +373,7 @@ public class PlotAnalysis {
String result = "";
if (obj.getClass().isArray()) {
String prefix = "";
for (int i = 0; i < Array.getLength(obj); i++) {
result += prefix + log(Array.get(obj, i));
prefix = ",";
@@ -520,7 +496,7 @@ public class PlotAnalysis {
}
}
}
final int[] ranks = new int[input.length];
for (int i = 0; i < input.length; i++) {
final int index = input[i];
@@ -557,4 +533,25 @@ public class PlotAnalysis {
placement *= SIZE;
}
}
public List<Integer> asList() {
return Arrays.asList(changes, faces, data, air, variety, changes_sd, faces_sd, data_sd, air_sd, variety_sd);
}
public int getComplexity() {
if (complexity != 0) {
return complexity;
}
complexity = ((changes) * MODIFIERS.changes)
+ ((faces) * MODIFIERS.faces)
+ ((data) * MODIFIERS.data)
+ ((air) * MODIFIERS.air)
+ ((variety) * MODIFIERS.variety)
+ ((changes_sd) * MODIFIERS.changes_sd)
+ ((faces_sd) * MODIFIERS.faces_sd)
+ ((data_sd) * MODIFIERS.data_sd)
+ ((air_sd) * MODIFIERS.air_sd)
+ ((variety_sd) * MODIFIERS.variety_sd);
return complexity;
}
}

View File

@@ -20,18 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.object;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
@@ -50,10 +38,31 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.area.QuadMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Jesse Boyd
*/
public abstract class PlotArea {
public final String worldname;
public final String id;
public final PlotManager manager;
public final int worldhash;
private final PlotId min;
private final PlotId max;
private final ConcurrentHashMap<PlotId, Plot> plots = new ConcurrentHashMap<>();
private final IndependentPlotGenerator generator;
public int MAX_PLOT_MEMBERS = 128;
public boolean AUTO_MERGE = false;
public boolean ALLOW_SIGNS = true;
@@ -80,33 +89,22 @@ public abstract class PlotArea {
public int MAX_BUILD_HEIGHT = 256;
public int MIN_BUILD_HEIGHT = 1;
public PlotGamemode GAMEMODE = PlotGamemode.CREATIVE;
public final String worldname;
public final String id;
public final PlotManager manager;
private final PlotId min;
private final PlotId max;
int hash;
private RegionWrapper region;
/**
* Please ignore
*/
@Deprecated
private int compatibility_id;
private ConcurrentHashMap<String, Object> meta;
private final ConcurrentHashMap<PlotId, Plot> plots = new ConcurrentHashMap<>();
private QuadMap<PlotCluster> clusters;
private final IndependentPlotGenerator generator;
public PlotArea(final String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) {
this.worldname = worldname;
this.id = id;
this.manager = generator != null ? generator.getNewPlotManager() : null;
this.generator = generator;
if ((min == null) || (max == null)) {
if (min == null || max == null) {
if (min != max) {
throw new IllegalArgumentException("None of the ids can be null for this constructor");
}
@@ -127,7 +125,7 @@ public abstract class PlotArea {
public ConfigurationNode[] getSettingNodes() {return null;}
};
}
/**
* Returns the region for this PlotArea
* @return
@@ -158,7 +156,7 @@ public abstract class PlotArea {
public PlotId getMin() {
return min == null ? new PlotId(Integer.MIN_VALUE, Integer.MIN_VALUE) : min;
}
/**
* Returns the max PlotId
* @return
@@ -171,8 +169,6 @@ public abstract class PlotArea {
return generator;
}
public final int worldhash;
@Override
public boolean equals(final Object obj) {
if (this == obj) {
@@ -187,7 +183,7 @@ public abstract class PlotArea {
final PlotArea plotarea = (PlotArea) obj;
return this.worldhash == plotarea.worldhash && this.worldname.equals(plotarea.worldname) && StringMan.isEqual(this.id, plotarea.id);
}
public Set<PlotCluster> getClusters() {
return clusters == null ? new HashSet<PlotCluster>() : clusters.getAll();
}
@@ -238,7 +234,7 @@ public abstract class PlotArea {
SCHEMATIC_FILE = config.getString("schematic.file");
SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim");
SCHEMATICS = config.getStringList("schematic.schematics");
USE_ECONOMY = config.getBoolean("economy.use") && (EconHandler.manager != null);
USE_ECONOMY = config.getBoolean("economy.use") && EconHandler.manager != null;
PLOT_PRICE = config.getDouble("economy.prices.claim");
MERGE_PRICE = config.getDouble("economy.prices.merge");
SELL_PRICE = config.getDouble("economy.prices.sell");
@@ -246,7 +242,7 @@ public abstract class PlotArea {
WORLD_BORDER = config.getBoolean("world.border");
MAX_BUILD_HEIGHT = config.getInt("world.max_height");
MIN_BUILD_HEIGHT = config.getInt("min.max_height");
switch (config.getString("world.gamemode").toLowerCase()) {
case "survival":
case "s":
@@ -271,10 +267,10 @@ public abstract class PlotArea {
PS.debug("&cInvalid gamemode set for: " + worldname);
break;
}
HOME_ALLOW_NONMEMBER = config.getBoolean("home.allow-nonmembers");
final String homeDefault = config.getString("home.default");
if (homeDefault.equalsIgnoreCase("side")) {
if ("side".equalsIgnoreCase(homeDefault)) {
DEFAULT_HOME = null;
} else if (StringMan.isEqualIgnoreCaseToAny(homeDefault, "center", "middle")) {
DEFAULT_HOME = new PlotLoc(Integer.MAX_VALUE, Integer.MAX_VALUE);
@@ -282,20 +278,20 @@ public abstract class PlotArea {
try {
final String[] split = homeDefault.split(",");
DEFAULT_HOME = new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
} catch (final Exception e) {
} catch (NumberFormatException e) {
DEFAULT_HOME = null;
}
}
List<String> flags = config.getStringList("flags.default");
if ((flags == null) || (flags.size() == 0)) {
if (flags == null || flags.isEmpty()) {
flags = config.getStringList("flags");
if ((flags == null) || (flags.size() == 0)) {
if (flags == null || flags.isEmpty()) {
flags = new ArrayList<>();
final ConfigurationSection section = config.getConfigurationSection("flags");
final Set<String> keys = section.getKeys(false);
for (final String key : keys) {
if (!key.equals("default")) {
if (!"default".equals(key)) {
flags.add(key + ";" + section.get(key));
}
}
@@ -347,8 +343,8 @@ public abstract class PlotArea {
options.put("world.max_height", MAX_BUILD_HEIGHT);
options.put("world.min_height", MIN_BUILD_HEIGHT);
options.put("world.gamemode", GAMEMODE.name().toLowerCase());
if ((TYPE != 0)) {
if (TYPE != 0) {
options.put("generator.terrain", TERRAIN);
options.put("generator.type", TYPE);
}
@@ -359,9 +355,9 @@ public abstract class PlotArea {
for (final ConfigurationNode setting : settings) {
options.put(setting.getConstant(), setting.getValue());
}
for (final String option : options.keySet()) {
if (!config.contains(option)) {
config.set(option, options.get(option));
for (final Entry<String, Object> stringObjectEntry : options.entrySet()) {
if (!config.contains(stringObjectEntry.getKey())) {
config.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
}
}
if (!config.contains("flags")) {
@@ -371,11 +367,9 @@ public abstract class PlotArea {
@Override
public String toString() {
return (compatibility_id == 1 || id == null) ? worldname : worldname + ";" + id;
return compatibility_id == 1 || id == null ? worldname : worldname + ";" + id;
}
int hash;
@Override
public int hashCode() {
if (hash != 0) {
@@ -559,7 +553,7 @@ public abstract class PlotArea {
*/
public void setMeta(final String key, final Object value) {
if (meta == null) {
meta = new ConcurrentHashMap<String, Object>();
meta = new ConcurrentHashMap<>();
}
meta.put(key, value);
}
@@ -716,7 +710,7 @@ public abstract class PlotArea {
}
public boolean mergePlots(final PlotPlayer player, final ArrayList<PlotId> plotIds) {
if ((EconHandler.manager != null) && USE_ECONOMY) {
if (EconHandler.manager != null && USE_ECONOMY) {
final double cost = plotIds.size() * MERGE_PRICE;
if (cost > 0d) {
if (EconHandler.manager.getMoney(player) < cost) {
@@ -746,10 +740,10 @@ public abstract class PlotArea {
if (!result) {
return false;
}
final HashSet<UUID> trusted = new HashSet<UUID>();
final HashSet<UUID> members = new HashSet<UUID>();
final HashSet<UUID> denied = new HashSet<UUID>();
final HashSet<UUID> trusted = new HashSet<>();
final HashSet<UUID> members = new HashSet<>();
final HashSet<UUID> denied = new HashSet<>();
manager.startPlotMerge(this, plotIds);
for (int x = pos1.x; x <= pos2.x; x++) {
@@ -767,7 +761,6 @@ public abstract class PlotArea {
members.removeAll(trusted);
denied.removeAll(trusted);
denied.removeAll(members);
Plot plot2;
for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) {
final boolean lx = x < pos2.x;
@@ -777,6 +770,7 @@ public abstract class PlotArea {
plot.setTrusted(trusted);
plot.setMembers(members);
plot.setDenied(denied);
Plot plot2;
if (lx) {
if (ly) {
if (!plot.getMerged(1) || !plot.getMerged(2)) {
@@ -810,20 +804,20 @@ public abstract class PlotArea {
* @return
*/
public HashSet<Plot> getPlotSelectionOwned(final PlotId pos1, final PlotId pos2) {
final int size = ((1 + pos2.x) - pos1.x) * ((1 + pos2.y) - pos1.y);
final int size = (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y);
final HashSet<Plot> result = new HashSet<>();
if (size < 16 || size < getPlotCount()) {
for (final PlotId pid : MainUtil.getPlotSelectionIds(pos1, pos2)) {
final Plot plot = getPlotAbs(pid);
if (plot.hasOwner()) {
if ((plot.getId().x > pos1.x) || (plot.getId().y > pos1.y) || (plot.getId().x < pos2.x) || (plot.getId().y < pos2.y)) {
if (plot.getId().x > pos1.x || plot.getId().y > pos1.y || plot.getId().x < pos2.x || plot.getId().y < pos2.y) {
result.add(plot);
}
}
}
} else {
for (final Plot plot : getPlots()) {
if ((plot.getId().x > pos1.x) || (plot.getId().y > pos1.y) || (plot.getId().x < pos2.x) || (plot.getId().y < pos2.y)) {
if (plot.getId().x > pos1.x || plot.getId().y > pos1.y || plot.getId().x < pos2.x || plot.getId().y < pos2.y) {
result.add(plot);
}
}

View File

@@ -5,7 +5,6 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
@@ -41,9 +40,8 @@ public class PlotHandler {
return false;
}
HashSet<Plot> connected = plot.getConnectedPlots();
Iterator<Plot> iter = connected.iterator();
while (iter.hasNext()) {
if (uuid.equals(iter.next().owner)) {
for (Plot aConnected : connected) {
if (aConnected.isOwner(uuid)) {
return true;
}
}
@@ -58,7 +56,7 @@ public class PlotHandler {
return UUIDHandler.getPlayer(plot.owner) != null;
}
for (Plot current : plot.getConnectedPlots()) {
if (current.owner != null && UUIDHandler.getPlayer(current.owner) != null) {
if (current.hasOwner() && UUIDHandler.getPlayer(current.owner) != null) {
return true;
}
}
@@ -92,7 +90,7 @@ public class PlotHandler {
}
final HashSet<UUID> owners = getOwners(plot1);
owners.retainAll(getOwners(plot2));
return owners.size() > 0;
return !owners.isEmpty();
}
public static boolean isAdded(final Plot plot, final UUID uuid) {

View File

@@ -29,6 +29,7 @@ public class PlotId {
* y value
*/
public Integer y;
private int hash;
/**
* PlotId class (PlotId x,y values do not correspond to Block locations)
@@ -44,7 +45,7 @@ public class PlotId {
/**
* Get a Plot Id based on a string
*
* @param string to create id from
* @param string to create type from
*
* @return null if the string is invalid
*/
@@ -65,7 +66,11 @@ public class PlotId {
}
return new PlotId(x, y);
}
public static PlotId unpair(int hash) {
return new PlotId(hash >> 16, hash & 0xFFFF);
}
public PlotId getRelative(final int direction) {
switch (direction) {
case 0:
@@ -104,12 +109,6 @@ public class PlotId {
return x + ";" + y;
}
public static PlotId unpair(int hash) {
return new PlotId(hash >> 16, hash & 0xFFFF);
}
private int hash;
public void recalculateHash() {
hash = 0;
hashCode();

View File

@@ -20,16 +20,16 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.object;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.comment.PlotComment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.comment.PlotComment;
/**
* Generic settings class
* - Does not keep a reference to a parent class
@@ -98,7 +98,7 @@ public class PlotSettings {
* Returns true if the plot is merged (i.e. if it's a mega plot)
*/
public boolean isMerged() {
return (merged[0] || merged[1] || merged[2] || merged[3]);
return merged[0] || merged[1] || merged[2] || merged[3];
}
public boolean[] getMerged() {

View File

@@ -51,12 +51,12 @@ public class SetupObject {
public String id;
/**
* Minimum plot id (may be null)
* Minimum plot type (may be null)
*/
public PlotId min;
/**
* Max plot id (may be null)
* Max plot type (may be null)
*/
public PlotId max;

View File

@@ -1,11 +1,5 @@
package com.intellectualcrafters.plot.util;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ConsolePlayer;
@@ -15,19 +9,24 @@ import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class ChunkManager {
public static ChunkManager manager = null;
private static RunnableVal<PlotChunk<?>> CURRENT_FORCE_CHUNK;
private static RunnableVal<PlotChunk<?>> CURRENT_ADD_CHUNK;
public static ChunkLoc getChunkChunk(final Location loc) {
final int x = loc.getX() >> 9;
final int z = loc.getZ() >> 9;
return new ChunkLoc(x, z);
}
private static RunnableVal<PlotChunk<?>> CURRENT_FORCE_CHUNK;
private static RunnableVal<PlotChunk<?>> CURRENT_ADD_CHUNK;
public static void setChunkInPlotArea(RunnableVal<PlotChunk<?>> force, RunnableVal<PlotChunk<?>> add, String world, ChunkLoc loc) {
if (PS.get().isAugmented(world)) {
ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
@@ -131,7 +130,7 @@ public abstract class ChunkManager {
@Override
public void run() {
final long start = System.currentTimeMillis();
while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < allocate)) {
while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < allocate)) {
final ChunkLoc chunk = chunks.remove(0);
task.value = new int[7];
task.value[0] = chunk.x;
@@ -158,7 +157,7 @@ public abstract class ChunkManager {
}
task.run();
}
if (chunks.size() != 0) {
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
TaskManager.runTask(whenDone);

View File

@@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.util;
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.flag.Flag;
@@ -19,6 +15,10 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
import com.plotsquared.listener.PlayerBlockEventType;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.UUID;
public abstract class EventUtil {
public static EventUtil manager = null;
@@ -64,18 +64,16 @@ public abstract class EventUtil {
return true;
}
switch (type) {
case TELEPORT_OBJECT: {
case TELEPORT_OBJECT:
return false;
}
case EAT:
case READ: {
case READ:
return true;
}
case BREAK_BLOCK: {
case BREAK_BLOCK:
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
final Flag use = FlagManager.getPlotFlagRaw(plot, "use");
@@ -96,7 +94,6 @@ public abstract class EventUtil {
return true;
}
return !(!notifyPerms || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_USE.s() + "/" + C.FLAG_BREAK.s()));
}
case BREAK_HANGING:
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
@@ -143,12 +140,12 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
@@ -160,12 +157,12 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED.s(), notifyPerms);
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER.s(), notifyPerms)) {
return true;
}
@@ -177,7 +174,7 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), false);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), false);
}
if (FlagManager.isPlotFlagTrue(plot, "device-interact")) {
@@ -185,10 +182,7 @@ public abstract class EventUtil {
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), false)) {
return true;
}
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
// TODO: fix the commented dead code
return true; //!(!false || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_USE.s() + "/" + C.FLAG_DEVICE_INTERACT.s()));
}
@@ -198,7 +192,7 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "hanging-interact")) {
@@ -206,7 +200,7 @@ public abstract class EventUtil {
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
@@ -218,7 +212,7 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "misc-interact")) {
@@ -226,7 +220,7 @@ public abstract class EventUtil {
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
@@ -238,7 +232,7 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "vehicle-use")) {
@@ -246,7 +240,7 @@ public abstract class EventUtil {
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
@@ -258,7 +252,7 @@ public abstract class EventUtil {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
@@ -267,7 +261,7 @@ public abstract class EventUtil {
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
@@ -275,7 +269,7 @@ public abstract class EventUtil {
}
return true;
}
case PLACE_HANGING: {
case PLACE_HANGING:
// if (plot == null) {
// return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
// }
@@ -292,12 +286,11 @@ public abstract class EventUtil {
// return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
// }
return true;
}
case PLACE_MISC: {
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
@@ -306,7 +299,7 @@ public abstract class EventUtil {
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
@@ -314,27 +307,26 @@ public abstract class EventUtil {
}
return true;
}
case PLACE_VEHICLE: {
case PLACE_VEHICLE:
if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
}
if (plot.owner == null) {
if (!plot.hasOwner()) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
}
if (FlagManager.isPlotFlagTrue(plot, "vehicle-place")) {
return true;
}
final Flag flag = FlagManager.getPlotFlagRaw(plot, "place");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true;
}
return !(!notifyPerms || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_VEHICLE_PLACE.s() + "/" + C.FLAG_PLACE.s()));
}
return true;
}
default:
break;
}

View File

@@ -78,7 +78,7 @@ public class ExpireManager {
updateExpired(area);
return;
}
if ((plots.size() == 0)) {
if ((plots.isEmpty())) {
if (updateExpired(area)) {
PS.debug("$2[&5Expire&dManager$2] $4Re-evaluating expired plots for: " + area);
return;
@@ -168,7 +168,7 @@ public class ExpireManager {
final String name = UUIDHandler.getName(uuid);
if (name != null) {
long last;
if (dates.contains(uuid)) {
if (dates.containsKey(uuid)) {
last = dates.get(uuid);
} else {
OfflinePlotPlayer opp;
@@ -207,9 +207,7 @@ public class ExpireManager {
public static List<Plot> getOldPlots(final PlotArea area) {
final ArrayList<Plot> plots = new ArrayList<>(area.getPlots());
final List<Plot> toRemove = new ArrayList<>();
final Iterator<Plot> iter = plots.iterator();
while (iter.hasNext()) {
final Plot plot = iter.next();
for (Plot plot : plots) {
final Flag keepFlag = FlagManager.getPlotFlagRaw(plot, "keep");
if ((keepFlag != null) && (Boolean) keepFlag.getValue()) {
continue;

View File

@@ -80,9 +80,9 @@ public class MainUtil {
for (int i = 0; i < 16; i++) {
final int i4 = i << 4;
for (int j = 0; j < 4096; j++) {
final int y = (i4) + (j >> 8);
final int a = (j - ((y & 0xF) << 8));
final int z1 = (a >> 4);
final int y = i4 + (j >> 8);
final int a = j - ((y & 0xF) << 8);
final int z1 = a >> 4;
final int x1 = a - (z1 << 4);
x_loc[i][j] = (short) x1;
y_loc[i][j] = (short) y;
@@ -97,7 +97,7 @@ public class MainUtil {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < 256; y++) {
final short i = (short) (y >> 4);
final short j = (short) (((y & 0xF) << 8) | (z << 4) | x);
final short j = (short) ((y & 0xF) << 8 | z << 4 | x);
CACHE_I[y][x][z] = i;
CACHE_J[y][x][z] = j;
}
@@ -120,8 +120,8 @@ public class MainUtil {
return ((array[0] ? 1 : 0) << 3) + ((array[1] ? 1 : 0) << 2) + ((array[2] ? 1 : 0) << 1) + (array[3] ? 1 : 0);
}
int n = 0;
for (int j = 0; j < array.length; ++j) {
n = (n << 1) + (array[j] ? 1 : 0);
for (boolean anArray : array) {
n = (n << 1) + (anArray ? 1 : 0);
}
return n;
}
@@ -197,7 +197,7 @@ public class MainUtil {
/**
* Fuzzy plot search with spaces separating terms<br>
* - Terms: id, alias, world, owner, trusted, member
* - Terms: type, alias, world, owner, trusted, member
* @param search
* @return
*/
@@ -236,7 +236,7 @@ public class MainUtil {
for (final Plot plot : PS.get().getPlots()) {
int count = 0;
if (uuids.size() > 0) {
if (!uuids.isEmpty()) {
for (final UUID uuid : uuids) {
if (plot.isOwner(uuid)) {
count += 2;
@@ -250,20 +250,20 @@ public class MainUtil {
count++;
}
}
if ((area != null) && plot.getArea().equals(area)) {
if (area != null && plot.getArea().equals(area)) {
count++;
}
if ((alias != null) && alias.equals(plot.getAlias())) {
if (alias != null && alias.equals(plot.getAlias())) {
count += 2;
}
if (count != 0) {
plotList.get(count - 1).add(plot);
}
}
final List<Plot> plots = new ArrayList<Plot>();
final List<Plot> plots = new ArrayList<>();
for (int i = plotList.size() - 1; i >= 0; i--) {
if (plotList.get(i).size() > 0) {
if (!plotList.get(i).isEmpty()) {
plots.addAll(plotList.get(i));
}
}
@@ -287,8 +287,7 @@ public class MainUtil {
}
return player.getLocation().getPlotAbs();
}
PlotArea area = null;
PlotId id = null;
PlotArea area;
if (player != null) {
area = player.getApplicablePlotArea();
}
@@ -296,6 +295,7 @@ public class MainUtil {
area = ConsolePlayer.getConsole().getApplicablePlotArea();
}
final String[] split = arg.split(";|,");
PlotId id;
if (split.length == 4) {
area = PS.get().getPlotAreaByString(split[0] + ";" + split[1]);
id = PlotId.fromString(split[2] + ";" + split[3]);
@@ -314,7 +314,7 @@ public class MainUtil {
} else {
for (final Plot p : area.getPlots()) {
final String name = p.getAlias();
if ((name.length() != 0) && StringMan.isEqualIgnoreCase(name, arg)) {
if (!name.isEmpty() && StringMan.isEqualIgnoreCase(name, arg)) {
return p;
}
}
@@ -325,12 +325,10 @@ public class MainUtil {
}
}
if (id == null) {
if (id == null) {
if (message) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID);
}
return null;
if (message) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID);
}
return null;
}
if (area == null) {
if (message) {
@@ -490,7 +488,7 @@ public class MainUtil {
* @return
*/
public static boolean sendMessage(final PlotPlayer plr, final String msg, final boolean prefix) {
if ((msg.length() > 0) && !msg.equals("")) {
if (!msg.isEmpty()) {
if (plr == null) {
ConsolePlayer.getConsole().sendMessage((prefix ? C.PREFIX.s() : "") + msg);
} else {
@@ -521,7 +519,7 @@ public class MainUtil {
* @return boolean success
*/
public static boolean sendMessage(final PlotPlayer plr, final C c, final Object... args) {
if (c.s().length() == 0) {
if (c.s().isEmpty()) {
return true;
}
TaskManager.runTaskAsync(new Runnable() {
@@ -529,10 +527,10 @@ public class MainUtil {
public void run() {
String msg = c.s();
if (args.length != 0) {
msg = c.format(c, args);
msg = C.format(c, args);
}
if (plr != null) {
plr.sendMessage((c.usePrefix() ? C.PREFIX.s() + msg : msg));
plr.sendMessage(c.usePrefix() ? C.PREFIX.s() + msg : msg);
} else {
ConsolePlayer.getConsole().sendMessage((c.usePrefix() ? C.PREFIX.s() : "") + msg);
}
@@ -556,19 +554,19 @@ public class MainUtil {
} else {
rating = DBFunc.getRatings(plot);
}
if ((rating == null) || (rating.size() == 0)) {
if (rating == null || rating.isEmpty()) {
return 0;
}
double val = 0;
int size = 0;
for (final Entry<UUID, Integer> entry : rating.entrySet()) {
int current = entry.getValue();
if ((Settings.RATING_CATEGORIES == null) || (Settings.RATING_CATEGORIES.size() == 0)) {
if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) {
val += current;
size++;
} else {
for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) {
val += (current % 10) - 1;
val += current % 10 - 1;
current /= 10;
size++;
}
@@ -597,16 +595,16 @@ public class MainUtil {
size = Math.max(1, Settings.RATING_CATEGORIES.size());
}
final double[] ratings = new double[size];
if ((rating == null) || (rating.size() == 0)) {
if (rating == null || rating.isEmpty()) {
return ratings;
}
for (final Entry<UUID, Integer> entry : rating.entrySet()) {
int current = entry.getValue();
if ((Settings.RATING_CATEGORIES == null) || (Settings.RATING_CATEGORIES.size() == 0)) {
if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) {
ratings[0] += current;
} else {
for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) {
ratings[i] += (current % 10) - 1;
ratings[i] += current % 10 - 1;
current /= 10;
}
}
@@ -619,7 +617,7 @@ public class MainUtil {
/**
* Format a string with plot information:<br>
* %id%, %alias%, %num%, %desc%, %biome%, %owner%, %members%, %trusted%, %helpers%, %denied%, %flags%, %build%, %desc%, %rating%
* %type%, %alias%, %num%, %desc%, %biome%, %owner%, %members%, %trusted%, %helpers%, %denied%, %flags%, %build%, %desc%, %rating%
* @param info
* @param plot
* @param player
@@ -628,7 +626,7 @@ public class MainUtil {
*/
public static void format(String info, final Plot plot, final PlotPlayer player, final boolean full, final RunnableVal<String> whenDone) {
final int num = plot.getConnectedPlots().size();
final String alias = plot.getAlias().length() > 0 ? plot.getAlias() : C.NONE.s();
final String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : C.NONE.s();
final Location bot = plot.getCorners()[0];
final String biome = WorldUtil.IMP.getBiome(plot.getArea().worldname, bot.getX(), bot.getZ());
final String trusted = getPlayerList(plot.getTrusted());
@@ -640,7 +638,8 @@ public class MainUtil {
final String flags = StringMan.replaceFromMap(
"$2"
+ (StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "").length() > 0 ? StringMan.join(FlagManager.getPlotFlags(
+ (!StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "").isEmpty() ?
StringMan.join(FlagManager.getPlotFlags(
plot.getArea(), plot.getSettings(), true)
.values(), "$1, $2") : C.NONE.s()), C.replacements);
@@ -655,7 +654,7 @@ public class MainUtil {
info = info.replaceAll("%biome%", biome);
info = info.replaceAll("%owner%", owner);
info = info.replaceAll("%members%", members);
info = info.replaceAll("%player%", player != null ? player.getName() : C.NONE.s());
info = info.replaceAll("%player%", player.getName());
info = info.replaceAll("%trusted%", trusted);
info = info.replaceAll("%helpers%", members);
info = info.replaceAll("%denied%", denied);
@@ -668,11 +667,11 @@ public class MainUtil {
@Override
public void run() {
int max = 10;
if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() > 0)) {
if (Settings.RATING_CATEGORIES != null && !Settings.RATING_CATEGORIES.isEmpty()) {
max = 8;
}
String info;
if (full && (Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() > 1)) {
if (full && Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 1) {
String rating = "";
String prefix = "";
final double[] ratings = MainUtil.getAverageRatings(plot);
@@ -706,7 +705,7 @@ public class MainUtil {
final String c = C.PLOT_USER_LIST.s();
final StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) {
if ((x + 1) == l.size()) {
if (x + 1 == l.size()) {
list.append(c.replace("%user%", getName(l.get(x))).replace(",", ""));
} else {
list.append(c.replace("%user%", getName(l.get(x))));

View File

@@ -36,13 +36,6 @@ import java.util.List;
public class ReflectionUtils {
private static String version;
public ReflectionUtils(final String version) {
ReflectionUtils.version = version;
preClassB += "." + version;
preClassM += "." + version;
}
/**
* prefix of bukkit classes
*/
@@ -51,6 +44,12 @@ public class ReflectionUtils {
* prefix of minecraft classes
*/
private static String preClassM = "net.minecraft.server";
public ReflectionUtils(final String version) {
ReflectionUtils.version = version;
preClassB += "." + version;
preClassM += "." + version;
}
public static Class<?> getNmsClass(final String name) {
final String className = "net.minecraft.server." + version + "." + name;
@@ -252,7 +251,7 @@ public class ReflectionUtils {
*
* @throws RuntimeException if method not found
*/
public RefMethod getMethod(final String name, final Object... types) throws NoSuchMethodException {
public RefMethod getMethod(final String name, final Object... types) {
try {
final Class[] classes = new Class[types.length];
int i = 0;

View File

@@ -11,6 +11,7 @@ import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.StringTag;
import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.json.JSONArray;
import com.intellectualcrafters.json.JSONException;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.generator.ClassicPlotWorld;
@@ -26,6 +27,7 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem;
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;
@@ -61,7 +63,7 @@ public abstract class SchematicHandler {
if (exportAll) {
return false;
}
if (collection.size() == 0) {
if (collection.isEmpty()) {
return false;
}
exportAll = true;
@@ -69,7 +71,7 @@ public abstract class SchematicHandler {
TaskManager.runTask(new Runnable() {
@Override
public void run() {
if (plots.size() == 0) {
if (plots.isEmpty()) {
exportAll = false;
TaskManager.runTask(ifSuccess);
return;
@@ -162,7 +164,7 @@ public abstract class SchematicHandler {
TaskManager.runTask(whenDone);
return;
}
// block id and data arrays
// block type and data arrays
final short[] ids = schematic.ids;
final byte[] datas = schematic.datas;
// Calculate the optimal height to paste the schematic at
@@ -198,7 +200,7 @@ public abstract class SchematicHandler {
@Override
public void run() {
int count = 0;
while ((chunks.size() > 0) && (count < 256)) {
while (!chunks.isEmpty() && count < 256) {
count++;
final ChunkLoc chunk = chunks.remove(0);
final int x = chunk.x;
@@ -220,8 +222,7 @@ public abstract class SchematicHandler {
zzt = p2z;
}
// Paste schematic here
int id;
for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) {
final int yy = y_offset + ry;
if (yy > 255) {
@@ -235,9 +236,9 @@ public abstract class SchematicHandler {
final int xx = p1x + rx;
final int zz = p1z + rz;
id = ids[i];
int id = ids[i];
switch (id) {
case 0:
case 2:
@@ -305,20 +306,18 @@ public abstract class SchematicHandler {
case 189:
case 190:
case 191:
case 192: {
case 192:
SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, id);
break;
}
default: {
default:
SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, new PlotBlock((short) id, datas[i]));
break;
}
}
}
}
}
}
if (chunks.size() != 0) {
if (!chunks.isEmpty()) {
final Runnable task = this;
// Run when the queue is free
SetQueue.IMP.addTask(new Runnable() {
@@ -367,7 +366,7 @@ public abstract class SchematicHandler {
final int sy = MainUtil.getHeighestBlock(plot.getArea().worldname, l1.getX() + 1, l1.getZ() + 1);
final Dimension demensions = schematic.getSchematicDimension();
final int HEIGHT = demensions.getY();
if ((HEIGHT < 255)) {
if (HEIGHT < 255) {
l1 = l1.add(0, sy - 1, 0);
}
final int X = l1.getX() + x_offset;
@@ -459,12 +458,10 @@ public abstract class SchematicHandler {
* @return schematic if found, else null
*/
public Schematic getSchematic(final String name) {
{
final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics");
if (!parent.exists()) {
if (!parent.mkdir()) {
throw new RuntimeException("Could not create schematic parent directory");
}
final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics");
if (!parent.exists()) {
if (!parent.mkdir()) {
throw new RuntimeException("Could not create schematic parent directory");
}
}
final File file = new File(PS.get().IMP.getDirectory() + File.separator + "schematics" + File.separator + name + (name.endsWith(".schematic") ? "" : ".schematic"));
@@ -484,7 +481,7 @@ public abstract class SchematicHandler {
}
try {
return getSchematic(new FileInputStream(file));
} catch (final Exception e) {
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
@@ -495,7 +492,7 @@ public abstract class SchematicHandler {
final ReadableByteChannel rbc = Channels.newChannel(url.openStream());
final InputStream is = Channels.newInputStream(rbc);
return getSchematic(is);
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
@@ -511,7 +508,7 @@ public abstract class SchematicHandler {
is.close();
stream.close();
return getSchematic(tag);
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
PS.debug(is.toString() + " | " + is.getClass().getCanonicalName() + " is not in GZIP format : " + e.getMessage());
}
@@ -538,7 +535,7 @@ public abstract class SchematicHandler {
schematics.add(schematic);
}
return Lists.reverse(schematics);
} catch (final Exception e) {
} catch (JSONException | IOException e) {
e.printStackTrace();
PS.debug("ERROR PARSING: " + rawJSON);
}
@@ -559,17 +556,17 @@ public abstract class SchematicHandler {
} else {
website = Settings.WEB_URL + "save.php?" + uuid;
}
final String charset = "UTF-8";
final String param = "value";
final String boundary = Long.toHexString(System.currentTimeMillis());
final String CRLF = "\r\n";
final URLConnection con = new URL(website).openConnection();
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStream output = con.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true)) {
try (OutputStream output = con.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
final String CRLF = "\r\n";
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF);
final String param = "value";
writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + file + ".schematic" + "\"").append(CRLF);
@@ -585,7 +582,6 @@ public abstract class SchematicHandler {
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
nos.close();
output.close();
}
try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) {
final char[] buffer = new char[256];
@@ -600,7 +596,7 @@ public abstract class SchematicHandler {
if (!result.toString().equals("The file plot.schematic has been uploaded.")) {
PS.debug(result);
}
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
}
final int responseCode = ((HttpURLConnection) con).getResponseCode();
@@ -608,7 +604,7 @@ public abstract class SchematicHandler {
return null;
}
return new URL(Settings.WEB_URL + "?key=" + uuid + "&ip=" + Settings.WEB_IP);
} catch (final Exception e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
@@ -630,11 +626,9 @@ public abstract class SchematicHandler {
try {
final File tmp = new File(path);
tmp.getParentFile().mkdirs();
final OutputStream stream = new FileOutputStream(path);
final NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream));
output.writeTag(tag);
output.close();
stream.close();
try (OutputStream stream = new FileOutputStream(path); NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream))) {
output.writeTag(tag);
}
} catch (final IOException e) {
e.printStackTrace();
return false;
@@ -675,6 +669,36 @@ public abstract class SchematicHandler {
getCompoundTag(plot.getArea().worldname, plot.getRegions(), whenDone);
}
/**
* Schematic Dimensions
*
*/
public static class Dimension {
private final int x;
private final int y;
private final int z;
public Dimension(final int x, final int y, final int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
}
/**
* Schematic Class
*
@@ -693,7 +717,7 @@ public abstract class SchematicHandler {
datas = b;
schematicDimension = d;
}
/**
* Add an item to the schematic
* @param item
@@ -704,7 +728,7 @@ public abstract class SchematicHandler {
}
items.add(item);
}
/**
* Get any items associated with this schematic
* @return
@@ -712,7 +736,7 @@ public abstract class SchematicHandler {
public HashSet<PlotItem> getItems() {
return items;
}
/**
* Get the schematic dimensions
* @return
@@ -720,15 +744,15 @@ public abstract class SchematicHandler {
public Dimension getSchematicDimension() {
return schematicDimension;
}
/**
* Get the block id array
* Get the block type array
* @return
*/
public short[] getIds() {
return ids;
}
/**
* Get the block data array
* @return
@@ -741,24 +765,24 @@ public abstract class SchematicHandler {
int x1 = region.minX;
int x2 = region.maxX;
int z1 = region.minZ;
int z2 = region.maxZ;
int y1 = region.minY;
int y2 = Math.min(region.maxY, 255);
int width = x2 - x1 + 1;
int length = z2 - z1 + 1;
int height = y2 - y1 + 1;
short[] ids2 = new short[width * length * height];
byte[] datas2 = new byte[width * length * height];
int dx = schematicDimension.getX();
int dy = schematicDimension.getY();
int dz = schematicDimension.getZ();
for (int y = y1; y <= y2; y++) {
int yy = y >= 0 ? (y < dy ? y : y - dy) : y + dy;
int i1 = yy * dx * dz;
@@ -778,7 +802,7 @@ public abstract class SchematicHandler {
}
return new Schematic(ids2, datas2, new Dimension(width, height, length));
}
public void save(final File file) {
byte[] ids2 = new byte[ids.length];
for (int i = 0; i < ids.length; i++) {
@@ -788,34 +812,5 @@ public abstract class SchematicHandler {
SchematicHandler.this.save(tag, file.toString());
}
}
/**
* Schematic Dimensions
*
*/
public static class Dimension {
private final int x;
private final int y;
private final int z;
public Dimension(final int x, final int y, final int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
}
}

View File

@@ -1,19 +1,17 @@
package com.intellectualcrafters.plot.util;
import com.intellectualcrafters.plot.object.PlotBlock;
import java.util.ArrayDeque;
import java.util.concurrent.atomic.AtomicInteger;
import com.intellectualcrafters.plot.object.PlotBlock;
public class SetQueue {
public static final SetQueue IMP = new SetQueue();
public PlotQueue<?> queue;
private final AtomicInteger time_waiting = new AtomicInteger(2);
private final AtomicInteger time_current = new AtomicInteger(0);
private final ArrayDeque<Runnable> runnables = new ArrayDeque<>();
public PlotQueue<?> queue;
private long last;
private long last2;
@@ -72,7 +70,7 @@ public class SetQueue {
}
public boolean tasks() {
if (runnables.size() == 0) {
if (runnables.isEmpty()) {
return false;
}
final ArrayDeque<Runnable> tmp = runnables.clone();
@@ -106,8 +104,7 @@ public class SetQueue {
* @param x
* @param y
* @param z
* @param id
* @param data
* @param block
* @return
*/
public boolean setBlock(final String world, final int x, final int y, final int z, PlotBlock block) {

View File

@@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.util;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
@@ -13,6 +9,10 @@ import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
public class UUIDHandler {
public static UUIDHandlerImplementation implementation;
@@ -61,7 +61,7 @@ public class UUIDHandler {
public static HashSet<UUID> getAllUUIDS() {
final HashSet<UUID> uuids = new HashSet<>();
for (final Plot plot : PS.get().getPlots()) {
if (plot.owner != null) {
if (plot.hasOwner()) {
uuids.add(plot.owner);
uuids.addAll(plot.getTrusted());
uuids.addAll(plot.getMembers());

View File

@@ -7,18 +7,28 @@ 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.*;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public abstract class UUIDHandlerImplementation {
private BiMap<StringWrapper, UUID> uuidMap = HashBiMap.create(new HashMap<StringWrapper, UUID>());
public final ConcurrentHashMap<String, PlotPlayer> players;
public boolean CACHED = false;
public UUIDWrapper uuidWrapper = null;
public final ConcurrentHashMap<String, PlotPlayer> players;
public HashSet<UUID> unknown = new HashSet<>();
private BiMap<StringWrapper, UUID> uuidMap = HashBiMap.create(new HashMap<StringWrapper, UUID>());
public UUIDHandlerImplementation(final UUIDWrapper wrapper) {
uuidWrapper = wrapper;
@@ -57,7 +67,7 @@ public abstract class UUIDHandlerImplementation {
}
public void add(final BiMap<StringWrapper, UUID> toAdd) {
if (uuidMap.size() == 0) {
if (uuidMap.isEmpty()) {
uuidMap = toAdd;
}
for (final Map.Entry<StringWrapper, UUID> entry : toAdd.entrySet()) {
@@ -79,8 +89,6 @@ public abstract class UUIDHandlerImplementation {
PS.debug(C.PREFIX.s() + "&6Cached a total of: " + uuidMap.size() + " UUIDs");
}
public HashSet<UUID> unknown = new HashSet<>();
public boolean add(final StringWrapper name, final UUID uuid) {
if ((uuid == null)) {
return false;
@@ -99,7 +107,7 @@ public abstract class UUIDHandlerImplementation {
* lazy UUID conversion:
* - Useful if the person misconfigured the database, or settings before PlotMe conversion
*/
if (!Settings.OFFLINE_MODE && unknown.size() > 0) {
if (!Settings.OFFLINE_MODE && !unknown.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@@ -113,7 +121,7 @@ public abstract class UUIDHandlerImplementation {
if (offline != null && !offline.equals(uuid)) {
unknown.remove(offline);
final Set<Plot> plots = PS.get().getPlotsAbs(offline);
if (plots.size() > 0) {
if (!plots.isEmpty()) {
for (final Plot plot : plots) {
plot.owner = uuid;
}
@@ -131,7 +139,7 @@ public abstract class UUIDHandlerImplementation {
if (offline != null) {
if (!offline.equals(uuid)) {
final Set<Plot> plots = PS.get().getPlots(offline);
if (plots.size() > 0) {
if (!plots.isEmpty()) {
for (final Plot plot : plots) {
plot.owner = uuid;
}
@@ -194,7 +202,7 @@ public abstract class UUIDHandlerImplementation {
}
public UUID getUUID(final String name, final RunnableVal<UUID> ifFetch) {
if ((name == null) || (name.length() == 0)) {
if ((name == null) || (name.isEmpty())) {
return null;
}
// check online

View File

@@ -1,27 +1,22 @@
package com.intellectualcrafters.plot.util.area;
import com.intellectualcrafters.plot.object.RegionWrapper;
import java.util.HashSet;
import java.util.Set;
import com.intellectualcrafters.plot.object.RegionWrapper;
public class QuadMap<T> {
public final int size;
public final int x;
public final int z;
private final int newsize;
private final int min;
public HashSet<T> objects;
public QuadMap<T> one;
public QuadMap<T> two;
public QuadMap<T> three;
public QuadMap<T> four;
public QuadMap<T> skip;
private final int newsize;
private final int min;
public QuadMap(int size, int x, int z) {
this.size = size;
@@ -161,7 +156,7 @@ public class QuadMap<T> {
public boolean remove(T area) {
if (objects != null) {
if (objects.remove(area)) {
return objects.size() == 0;
return objects.isEmpty();
}
}
if (skip != null) {

View File

@@ -13,7 +13,8 @@ public class HelpObject {
public HelpObject(final Command command, final String label) {
_command = command;
_rendered = StringMan.replaceAll(C.HELP_ITEM.s(), "%usage%", _command.getUsage().replaceAll("\\{label\\}", label), "[%alias%]",
_command.getAliases().size() > 0 ? "(" + StringMan.join(_command.getAliases(), "|") + ")" : "", "%desc%", _command.getDescription(), "%arguments%",
!_command.getAliases().isEmpty() ? "(" + StringMan.join(_command.getAliases(), "|") + ")" : "", "%desc%", _command.getDescription(),
"%arguments%",
buildArgumentList(_command.getRequiredArguments()), "{label}", label);
}