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

View File

@ -1,22 +1,20 @@
package com.intellectualcrafters.configuration.file; 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.Configuration;
import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.InvalidConfigurationException; import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.plot.PS; 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. * 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 DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter(); private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); 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. * Creates a new {@link YamlConfiguration}, loading from the given file.
* <p> * <p>
@ -178,12 +44,12 @@ public class YamlConfiguration extends FileConfiguration {
if (file == null) { if (file == null) {
throw new NullPointerException("File cannot be null"); throw new NullPointerException("File cannot be null");
} }
final YamlConfiguration config = new YamlConfiguration(); final YamlConfiguration config = new YamlConfiguration();
try { try {
config.load(file); config.load(file);
} catch (final Exception ex) { } catch (InvalidConfigurationException | IOException ex) {
try { try {
file.getAbsolutePath(); file.getAbsolutePath();
File dest = new File(file.getAbsolutePath() + "_broken"); File dest = new File(file.getAbsolutePath() + "_broken");
@ -201,45 +67,10 @@ public class YamlConfiguration extends FileConfiguration {
e.printStackTrace(); e.printStackTrace();
} }
} }
return config; 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. * Creates a new {@link YamlConfiguration}, loading from the given reader.
* <p> * <p>
@ -255,19 +86,148 @@ public class YamlConfiguration extends FileConfiguration {
if (reader == null) { if (reader == null) {
throw new NullPointerException("Reader cannot be null"); throw new NullPointerException("Reader cannot be null");
} }
final YamlConfiguration config = new YamlConfiguration(); final YamlConfiguration config = new YamlConfiguration();
try { try {
config.load(reader); config.load(reader);
} catch (final IOException ex) { } catch (final IOException | InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
} catch (final InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream"); PS.debug("Cannot load configuration from stream");
ex.printStackTrace(); ex.printStackTrace();
} }
return config; 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; package com.intellectualcrafters.jnbt;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/** /**
* A class which holds constant values. * A class which holds constant values.
*/ */
public final class NBTConstants { public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8");
public static final 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, 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; 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 * @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); 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. * @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); this.os = new DataOutputStream(os);
} }

View File

@ -75,7 +75,7 @@ public class CDL {
for (;;) { for (;;) {
final String value = getValue(x); final String value = getValue(x);
char c = x.next(); 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; return null;
} }
ja.put(value); ja.put(value);
@ -128,7 +128,8 @@ public class CDL {
final Object object = ja.opt(i); final Object object = ja.opt(i);
if (object != null) { if (object != null) {
final String string = object.toString(); 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('"'); sb.append('"');
final int length = string.length(); final int length = string.length();
for (int j = 0; j < length; j += 1) { 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 { 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("\"\""); w.write("\"\"");
return w; return w;
} }
@ -1111,7 +1111,7 @@ public class JSONObject {
} else if (name.startsWith("is")) { } else if (name.startsWith("is")) {
key = name.substring(2); 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) { if (key.length() == 1) {
key = key.toLowerCase(); key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) { } else if (!Character.isUpperCase(key.charAt(1))) {

View File

@ -108,7 +108,7 @@ public class XML {
if ("CDATA".equals(token)) { if ("CDATA".equals(token)) {
if (x.next() == '[') { if (x.next() == '[') {
string = x.nextCDATA(); string = x.nextCDATA();
if (string.length() > 0) { if (!string.isEmpty()) {
context.accumulate("content", string); context.accumulate("content", string);
} }
return false; return false;
@ -192,7 +192,7 @@ public class XML {
return false; return false;
} else if (token instanceof String) { } else if (token instanceof String) {
string = (String) token; string = (String) token;
if (string.length() > 0) { if (!string.isEmpty()) {
jsonobject.accumulate("content", XML.stringToValue(string)); jsonobject.accumulate("content", XML.stringToValue(string));
} }
// Nested element // Nested element
@ -380,7 +380,8 @@ public class XML {
return sb.toString(); return sb.toString();
} else { } else {
string = (object == null) ? "null" : escape(object.toString()); 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; 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.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.MainCommand; 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.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.BukkitUtil; 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 * PlotSquared API
@ -115,12 +115,8 @@ public class PlotAPI {
/** /**
* Add a plot world * Add a plot world
* *
* @param world World Name
* @param plotArea Plot World Object * @param plotArea Plot World Object
* @param manager World Manager * @see PS#addPlotArea(PlotArea)
*
* @see PS#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotArea,
* com.intellectualcrafters.plot.object.PlotManager)
*/ */
public void addPlotArea(final PlotArea plotArea) { public void addPlotArea(final PlotArea plotArea) {
PS.get().addPlotArea(plotArea); PS.get().addPlotArea(plotArea);
@ -229,7 +225,7 @@ public class PlotAPI {
public String[] getPermissions() { public String[] getPermissions() {
final ArrayList<String> perms = new ArrayList<>(); final ArrayList<String> perms = new ArrayList<>();
for (final C c : C.values()) { for (final C c : C.values()) {
if (c.getCat().equals("static.permissions")) { if ("static.permissions".equals(c.getCat())) {
perms.add(c.s()); perms.add(c.s());
} }
} }
@ -267,7 +263,7 @@ public class PlotAPI {
* @return PlotManager * @return PlotManager
* *
* @see com.intellectualcrafters.plot.object.PlotManager * @see com.intellectualcrafters.plot.object.PlotManager
* @see PS#getPlotManager(String) * @see PS#getPlotManager(Plot)
*/ */
@Deprecated @Deprecated
public PlotManager getPlotManager(final World world) { public PlotManager getPlotManager(final World world) {
@ -292,7 +288,7 @@ public class PlotAPI {
* *
* @return PlotManager * @return PlotManager
* *
* @see PS#getPlotManager(String) * @see PS#getPlotManager(Plot)
* @see com.intellectualcrafters.plot.object.PlotManager * @see com.intellectualcrafters.plot.object.PlotManager
*/ */
@Deprecated @Deprecated
@ -335,7 +331,7 @@ public class PlotAPI {
* *
* @return PlotArea class for that world ! will return null if not a plot world world * @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 * @see com.intellectualcrafters.plot.object.PlotArea
*/ */
@Deprecated @Deprecated
@ -388,7 +384,7 @@ public class PlotAPI {
* @see MainUtil#sendConsoleMessage(C, String...) * @see MainUtil#sendConsoleMessage(C, String...)
*/ */
public void sendConsoleMessage(final String msg) { 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- * @return plot if found, otherwise it creates a temporary plot-
* *
* @see MainUtil#getPlotAbs(com.intellectualcrafters.plot.object.Location)
* @see Plot * @see Plot
*/ */
public Plot getPlot(final Location l) { public Plot getPlot(final Location l) {
@ -492,7 +487,7 @@ public class PlotAPI {
*/ */
@Deprecated @Deprecated
public boolean hasPlot(final World world, final Player player) { 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(); UUID uuid = BukkitUtil.getPlayer(plr).getUUID();
for (final Plot plot : PS.get().getPlots(world.getName())) { for (final Plot plot : PS.get().getPlots(world.getName())) {
if (just_owner) { if (just_owner) {
if ((plot.owner != null) && (plot.owner.equals(uuid))) { if (plot.hasOwner() && plot.isOwner(uuid)) {
pPlots.add(plot); pPlots.add(plot);
} }
} else { } else {
@ -534,7 +529,8 @@ public class PlotAPI {
if (world == null) { if (world == null) {
return new Plot[0]; 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 * @return World[] - array of plot worlds
* *
* @see PS#getPlotWorlds()
*/ */
@Deprecated @Deprecated
public String[] getPlotWorlds() { 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 * @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 * @see Plot
*/ */
@Deprecated @Deprecated
@ -589,7 +582,6 @@ public class PlotAPI {
* *
* @return plot bottom location * @return plot bottom location
* *
* @see MainUtil#getPlotHome(String, PlotId)
* @see Plot * @see Plot
*/ */
public Location getHomeLocation(final Plot p) { public Location getHomeLocation(final Plot p) {
@ -605,7 +597,6 @@ public class PlotAPI {
* *
* @deprecated As merged plots may not have a rectangular shape * @deprecated As merged plots may not have a rectangular shape
* *
* @see MainUtil#getPlotBottomLocAbs(String, PlotId)
* @see Plot * @see Plot
*/ */
@Deprecated @Deprecated
@ -622,7 +613,6 @@ public class PlotAPI {
* *
* @deprecated As merged plots may not have a rectangular shape * @deprecated As merged plots may not have a rectangular shape
* *
* @see MainUtil#getPlotTopLocAbs(String, PlotId)
* @see Plot * @see Plot
*/ */
@Deprecated @Deprecated
@ -637,7 +627,6 @@ public class PlotAPI {
* *
* @return true if the player is in a plot, false if not- * @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) { public boolean isInPlot(final Player player) {
return getPlot(player) != null; return getPlot(player) != null;
@ -677,7 +666,6 @@ public class PlotAPI {
* *
* @return the number of plots the player has * @return the number of plots the player has
* *
* @see MainUtil#getPlayerPlotCount(String, PlotPlayer)
*/ */
public int getPlayerPlotCount(final World world, final Player player) { public int getPlayerPlotCount(final World world, final Player player) {
if (world == null) { if (world == null) {

View File

@ -42,7 +42,7 @@ public class Alias extends SetCommand {
@Override @Override
public boolean set(final PlotPlayer plr, final Plot plot, final String alias) { 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()); C.COMMAND_SYNTAX.send(plr, getUsage());
return false; return false;
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,5 @@
package com.intellectualcrafters.plot.commands; 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.PS;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.MySQL; import com.intellectualcrafters.plot.database.MySQL;
@ -19,6 +13,12 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration; 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( @CommandDeclaration(
command = "database", command = "database",
aliases = { "convert" }, aliases = { "convert" },
@ -101,7 +101,7 @@ public class Database extends SubCommand {
for (final Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) { for (final Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
final Plot plot = entry2.getValue(); final Plot plot = entry2.getValue();
if (pa.getOwnedPlotAbs(plot.getId()) != null) { 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; continue;
} }
PS.get().updatePlot(plot); PS.get().updatePlot(plot);

View File

@ -20,9 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.UUID;
import com.google.common.collect.BiMap; import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
@ -42,6 +39,10 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
@CommandDeclaration( @CommandDeclaration(
command = "debugclaimtest", 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", 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); final String[] lines = WorldUtil.IMP.getSign(loc);
if (lines != null) { if (lines != null) {
String line = lines[2]; String line = lines[2];
if ((line != null) && (line.length() > 2)) { if (line != null && line.length() > 2) {
line = line.substring(2); line = line.substring(2);
final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap(); final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = (map.get(new StringWrapper(line))); UUID uuid = map.get(new StringWrapper(line));
if (uuid == null) { if (uuid == null) {
for (final StringWrapper string : map.keySet()) { for (final Map.Entry<StringWrapper, UUID> stringWrapperUUIDEntry : map.entrySet()) {
if (string.value.toLowerCase().startsWith(line.toLowerCase())) { if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = map.get(string); uuid = stringWrapperUUIDEntry.getValue();
break; 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!"); MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlotsAndData(plots, new Runnable() { DBFunc.createPlotsAndData(plots, new Runnable() {
@Override @Override

View File

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

View File

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

View File

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

View File

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

View File

@ -23,7 +23,8 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandDeclaration; 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 { public class Home extends SubCommand {
@Override @Override

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -39,7 +39,7 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
@CommandDeclaration( @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", command = "purge",
permission = "plots.admin", permission = "plots.admin",
description = "Purge all plots for a world", description = "Purge all plots for a world",
@ -80,7 +80,7 @@ public class Purge extends SubCommand {
break; break;
} }
case "plotid": case "plotid":
case "id": { case "type": {
id = PlotId.fromString(split[1]); id = PlotId.fromString(split[1]);
if (id == null) { if (id == null) {
C.NOT_VALID_PLOT_ID.send(plr, split[1]); 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); C.FOUND_NO_PLOTS.send(plr);
return false; return false;
} }

View File

@ -20,15 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
@ -45,6 +36,14 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration; 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( @CommandDeclaration(
command = "rate", command = "rate",
@ -113,7 +112,7 @@ public class Rate extends SubCommand {
sendMessage(player, C.RATING_NOT_DONE); sendMessage(player, C.RATING_NOT_DONE);
return false; 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() { final Runnable run = new Runnable() {
@Override @Override
public void run() { public void run() {
@ -183,7 +182,7 @@ public class Rate extends SubCommand {
} }
final String arg = args[0]; final String arg = args[0];
final int rating; 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); rating = Integer.parseInt(arg);
if (rating > 10 || rating < 1) { if (rating > 10 || rating < 1) {
sendMessage(player, C.RATING_NOT_VALID); sendMessage(player, C.RATING_NOT_VALID);

View File

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

View File

@ -20,11 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.ConfigurationNode; import com.intellectualcrafters.plot.config.ConfigurationNode;
@ -39,6 +34,11 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
@CommandDeclaration( @CommandDeclaration(
command = "setup", command = "setup",
permission = "plots.admin.command.setup", permission = "plots.admin.command.setup",
@ -172,14 +172,14 @@ public class Setup extends SubCommand {
} }
break; break;
} }
case 2: { // area id case 2: { // area type
if (!StringMan.isAlphanumericUnd(args[0])) { 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; return false;
} }
for (PlotArea area : PS.get().getPlotAreas()) { for (PlotArea area : PS.get().getPlotAreas()) {
if (area.id != null && area.id.equalsIgnoreCase(args[0])) { 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; return false;
} }
} }

View File

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

View File

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

View File

@ -20,11 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
@ -34,6 +29,11 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
@CommandDeclaration( @CommandDeclaration(
command = "toggle", command = "toggle",
aliases = { "attribute" }, aliases = { "attribute" },
@ -44,25 +44,12 @@ requiredType = RequiredType.NONE,
category = CommandCategory.SETTINGS) category = CommandCategory.SETTINGS)
public class Toggle extends SubCommand { 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; private HashMap<String, Command<PlotPlayer>> toggles;
public Toggle() { public Toggle() {
toggles = new HashMap<>(); toggles = new HashMap<>();
toggles.put("titles", new Command<PlotPlayer>("titles", "/plot toggle titles", "Toggle titles for yourself", C.PERMISSION_PLOT_TOGGLE_TITLES.s()) { toggles.put("titles", new Command<PlotPlayer>("titles", "/plot toggle titles", "Toggle titles for yourself", C.PERMISSION_PLOT_TOGGLE_TITLES.s()) {
@Override @Override
public boolean onCommand(final PlotPlayer player, final String[] args) { public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "disabletitles")) { 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()) { toggles.put("chatspy", new Command<PlotPlayer>("chatspy", "/plot toggle chatspy", "Toggle chat spying", C.PERMISSION_COMMANDS_CHAT.s()) {
@Override @Override
public boolean onCommand(final PlotPlayer player, final String[] args) { public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "chatspy")) { 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()) { toggles.put("chat", new Command<PlotPlayer>("chat", "/plot toggle chat", "Toggle plot chat for yourself", C.PERMISSION_PLOT_TOGGLE_CHAT.s()) {
@Override @Override
public boolean onCommand(final PlotPlayer player, final String[] args) { public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "chat")) { if (toggle(player, "chat")) {
@ -99,7 +86,7 @@ public class Toggle extends SubCommand {
}); });
if (PS.get() != null && PS.get().worldedit != null) { 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()) { toggles.put("worldedit", new Command<PlotPlayer>("worldedit", "/plot toggle worldedit", "Toggle worldedit bypass", C.PERMISSION_WORLDEDIT_BYPASS.s()) {
@Override @Override
public boolean onCommand(final PlotPlayer player, final String[] args) { public boolean onCommand(final PlotPlayer player, final String[] args) {
if (toggle(player, "worldedit")) { 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 @Override

View File

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

View File

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

View File

@ -20,15 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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;
import com.intellectualcrafters.plot.PS.SortType; import com.intellectualcrafters.plot.PS.SortType;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
@ -49,6 +40,15 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; 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( @CommandDeclaration(
command = "list", command = "list",
aliases = { "l", "find", "search" }, 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()); sendMessage(plr, C.DID_YOU_MEAN, new StringComparison<String>(args[0], new String[] { "mine", "shared", "world", "all" }).getBestMatch());
return false; return false;
} }
if (plots.size() == 0) { if (plots.isEmpty()) {
MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS); MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS);
return false; 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 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"); 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(), ","); String strFlags = StringMan.join(plot.getFlags().values(), ",");
if (strFlags.length() == 0) { if (strFlags.isEmpty()) {
strFlags = C.NONE.s(); strFlags = C.NONE.s();
} }
final PlotMessage flags = new PlotMessage().text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))).color("$1"); 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; 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.io.File;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.HashMap; import java.util.HashMap;
@ -28,13 +35,6 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; 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. * Captions class.
* *
@ -150,7 +150,7 @@ public enum C {
CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"), CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"),
CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"), CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"),
CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"), CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"),
CLUSTER_INFO("$1Current cluster: $2%id%&-$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 * Border
*/ */
@ -187,7 +187,7 @@ public enum C {
*/ */
SWAP_OVERLAP("$2The proposed areas are not allowed to overlap", "Swap"), SWAP_OVERLAP("$2The proposed areas are not allowed to overlap", "Swap"),
SWAP_DIMENSIONS("$2The proposed areas must have comparable dimensions", "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"), SWAP_SUCCESS("$4Successfully swapped plots", "Swap"),
STARTED_SWAP("$2Started plot swap task. You will be notified when it finishes", "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"), 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"), PASTE_FAILED("$2Failed to paste the selection. Reason: $2%s", "Clipboard"),
NO_CLIPBOARD("$2You don't have a selection in your clipboard", "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 * Toggle
*/ */
@ -298,8 +298,8 @@ public enum C {
*/ */
TITLE_ENTERED_PLOT("$1Plot: %world%;%x%;%z%", "Titles"), TITLE_ENTERED_PLOT("$1Plot: %world%;%x%;%z%", "Titles"),
TITLE_ENTERED_PLOT_SUB("$4Owned by %s", "Titles"), TITLE_ENTERED_PLOT_SUB("$4Owned by %s", "Titles"),
PREFIX_GREETING("$1%id%$2> ", "Titles"), PREFIX_GREETING("$1%type%$2> ", "Titles"),
PREFIX_FAREWELL("$1%id%$2> ", "Titles"), PREFIX_FAREWELL("$1%type%$2> ", "Titles"),
/* /*
* Core Stuff * Core Stuff
*/ */
@ -315,7 +315,7 @@ public enum C {
/* /*
* BarAPI * BarAPI
*/ */
BOSSBAR_CLEARING("$2Clearing plot: $1%id%", "Bar API"), BOSSBAR_CLEARING("$2Clearing plot: $1%type%", "Bar API"),
DESC_SET("$2Plot description set", "Desc"), DESC_SET("$2Plot description set", "Desc"),
DESC_UNSET("$2Plot description unset", "Desc"), DESC_UNSET("$2Plot description unset", "Desc"),
@ -443,12 +443,12 @@ public enum C {
/* /*
* Invalid * 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_VALID_BLOCK("$2That's not a valid block: %s", "Invalid"),
NOT_ALLOWED_BLOCK("$2That block is not allowed: %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_NUMBER("$2That's not a valid number within the range: %s", "Invalid"),
NOT_VALID_PLOT_ID("$2That's not a valid plot id.", "Invalid"), NOT_VALID_PLOT_ID("$2That's not a valid plot type.", "Invalid"),
PLOT_ID_FORM("$2The plot id must be in the form: $1X;Y $2e.g. $1-5;7", "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"), NOT_YOUR_PLOT("$2That is not your plot.", "Invalid"),
NO_SUCH_PLOT("$2There is no such 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"), 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_PLOT_NUMBER("$2You've got to specify a plot number or alias", "Need"),
NEED_BLOCK("$2You've got to specify a block", "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_PLOT_WORLD("$2You've got to specify a plot area.", "Need"),
NEED_USER("$2You need to specify a username", "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_UNOWNED("$2The current plot must have an owner to perform this action", "Info"),
PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"), PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"),
PLOT_INFO_HEADER("$3&m---------&r $1INFO $3&m---------", false, "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&-" + "$1Alias: $2%alias%$1&-"
+ "$1Owner: $2%owner%$1&-" + "$1Owner: $2%owner%$1&-"
+ "$1Biome: $2%biome%$1&-" + "$1Biome: $2%biome%$1&-"
@ -493,7 +493,7 @@ public enum C {
PLOT_INFO_BIOME("$1Biome:$2 %biome%", "Info"), PLOT_INFO_BIOME("$1Biome:$2 %biome%", "Info"),
PLOT_INFO_RATING("$1Rating:$2 %rating%", "Info"), PLOT_INFO_RATING("$1Rating:$2 %rating%", "Info"),
PLOT_INFO_OWNER("$1Owner:$2 %owner%", "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_ALIAS("$1Alias:$2 %alias%", "Info"),
PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"), PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"),
PLOT_USER_LIST(" $1%user%$2,", "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"), 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_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% plots", "List"),
PLOT_LIST_HEADER("$1List of %word% 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("$2>> $1%type$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_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"), PLOT_LIST_FOOTER("$2>> $1%word% a total of $2%num% $1claimed %plot%.", "List"),
/* /*
* Left * Left
@ -595,7 +595,7 @@ public enum C {
/* /*
* Signs * 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_2("$1Owner:", "Signs"),
OWNER_SIGN_LINE_3("$2%plr%", "Signs"), OWNER_SIGN_LINE_3("$2%plr%", "Signs"),
OWNER_SIGN_LINE_4("$3Claimed", "Signs"), OWNER_SIGN_LINE_4("$3Claimed", "Signs"),
@ -670,11 +670,6 @@ public enum C {
this(d, true, cat.toLowerCase()); this(d, true, cat.toLowerCase());
} }
@Override
public String toString() {
return s;
}
public static String format(String m, final Object... args) { public static String format(String m, final Object... args) {
if (args.length == 0) { if (args.length == 0) {
return m; return m;
@ -683,7 +678,7 @@ public enum C {
if (args.length > 0) { if (args.length > 0) {
for (int i = args.length - 1; i >= 0; i--) { for (int i = args.length - 1; i >= 0; i--) {
String arg = args[i].toString(); String arg = args[i].toString();
if (arg == null || arg.length() == 0) { if (arg == null || arg.isEmpty()) {
map.put("%s" + i, ""); map.put("%s" + i, "");
} else { } else {
arg = C.color(arg); arg = C.color(arg);
@ -784,6 +779,11 @@ public enum C {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override
public String toString() {
return s;
}
public String s() { public String s() {
return s; return s;

View File

@ -20,15 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.database; 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.flag.Flag;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea; 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.RunnableVal;
import com.intellectualcrafters.plot.object.comment.PlotComment; 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); 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 * @param cluster PlotCluster Object
* *
@ -193,15 +193,14 @@ public interface AbstractDB {
/** /**
* Purgle a plot * Purgle a plot
* *
* @param world World in which the plot is located * @param uniqueIds list of plot type (db) to be purged
* @param uniqueIds list of plot id (db) to be purged
*/ */
void purgeIds(final Set<Integer> uniqueIds); void purgeIds(final Set<Integer> uniqueIds);
/** /**
* Purge a whole world * 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); void purge(final PlotArea area, final Set<PlotId> plotIds);

View File

@ -20,6 +20,14 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.database; 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.ResultSet;
import java.sql.ResultSetMetaData; import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
@ -30,14 +38,6 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID; 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 * Database Functions
* - These functions do not update the local plot objects and only make changes to the DB * - 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 * @param plot Plot Object
* *
@ -250,10 +250,10 @@ public class DBFunc {
/* /*
* public static int getId(String plotId id2) { Statement stmt = * public static int getId(String plotId id2) { Statement stmt =
* null; try { stmt = connection.createStatement(); ResultSet r = * null; try { stmt = connection.createStatement(); ResultSet r =
* stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x * stmt.executeQuery("SELECT `type` FROM `plot` WHERE `plot_id_x` = '" + id2.x
* + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world +
* "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE; * "' ORDER BY `timestamp` ASC"); int type = Integer.MAX_VALUE;
* while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; } * while(r.next()) { type = r.getInt("type"); } stmt.close(); return type; }
* catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE; * 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 * Created 2014-09-23 for PlotSquared
* *
*/ */
public class AbstractFlag { public class AbstractFlag {
public final String key; public final String key;
@ -105,6 +107,6 @@ public class AbstractFlag {
return false; return false;
} }
final AbstractFlag otherObj = (AbstractFlag) other; final AbstractFlag otherObj = (AbstractFlag) other;
return (otherObj.key.equals(key)); return otherObj.key.equals(key);
} }
} }

View File

@ -20,10 +20,11 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.flag; package com.intellectualcrafters.plot.flag;
import java.lang.reflect.Method;
import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.StringMan;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Flag implements Cloneable { public class Flag implements Cloneable {
private AbstractFlag key; private AbstractFlag key;
private Object value; 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 * Warning: Unchecked
*/ */
@ -83,7 +77,14 @@ public class Flag implements Cloneable {
public String getKey() { public String getKey() {
return key.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 * Get the value
* *
@ -99,7 +100,7 @@ public class Flag implements Cloneable {
@Override @Override
public String toString() { public String toString() {
if (value.equals("")) { if ("".equals(value)) {
return key.getKey(); return key.getKey();
} }
return key + ":" + getValueString(); return key + ":" + getValueString();
@ -117,7 +118,7 @@ public class Flag implements Cloneable {
return false; return false;
} }
final Flag other = (Flag) obj; 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 @Override
@ -139,7 +140,22 @@ public class Flag implements Cloneable {
return new Flag(key, method.invoke(value)); return new Flag(key, method.invoke(value));
} }
return new Flag(key, key.parseValueRaw(value.toString())); 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(); e.printStackTrace();
return this; 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) { if (reserved) {
reserveFlag(af.getKey()); reserveFlag(af.getKey());
} }
@ -126,11 +126,11 @@ public class FlagManager {
public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) { public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) {
Flag flag; 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) { if (area == null) {
return null; return null;
} }
if (area.DEFAULT_FLAGS.size() == 0) { if (area.DEFAULT_FLAGS.isEmpty()) {
return null; return null;
} }
return area.DEFAULT_FLAGS.get(id); return area.DEFAULT_FLAGS.get(id);
@ -181,7 +181,7 @@ public class FlagManager {
return false; return false;
} }
final Flag flag = getPlotFlagRaw(plot, strFlag); 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) { public static boolean isPlotFlagFalse(final Plot plot, final String strFlag) {
@ -189,7 +189,7 @@ public class FlagManager {
return false; return false;
} }
final Flag flag = getPlotFlagRaw(plot, strFlag); final Flag flag = getPlotFlagRaw(plot, strFlag);
if ((flag == null) || ((Boolean) flag.getValue())) { if (flag == null || (Boolean) flag.getValue()) {
return false; return false;
} }
return false; return false;
@ -206,7 +206,7 @@ public class FlagManager {
} }
public static Flag getSettingFlagAbs(final PlotSettings settings, final String flag) { 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 null;
} }
return settings.flags.get(flag); 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) { public static HashMap<String, Flag> getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) {
final HashMap<String, Flag> flags = new HashMap<>(); 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); flags.putAll(area.DEFAULT_FLAGS);
} }
if (ignorePluginflags) { if (ignorePluginflags) {
@ -312,12 +312,12 @@ public class FlagManager {
public static void setPlotFlags(final Plot origin, final Set<Flag> flags) { public static void setPlotFlags(final Plot origin, final Set<Flag> flags) {
for (Plot plot : origin.getConnectedPlots()) { for (Plot plot : origin.getConnectedPlots()) {
if ((flags != null) && (flags.size() != 0)) { if (flags != null && !flags.isEmpty()) {
plot.getFlags().clear(); plot.getFlags().clear();
for (final Flag flag : flags) { for (final Flag flag : flags) {
plot.getFlags().put(flag.getKey(), flag); plot.getFlags().put(flag.getKey(), flag);
} }
} else if (plot.getFlags().size() == 0) { } else if (plot.getFlags().isEmpty()) {
return; return;
} else { } else {
plot.getFlags().clear(); plot.getFlags().clear();
@ -328,12 +328,12 @@ public class FlagManager {
} }
public static void setClusterFlags(final PlotCluster cluster, final Set<Flag> flags) { 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(); cluster.settings.flags.clear();
for (final Flag flag : flags) { for (final Flag flag : flags) {
cluster.settings.flags.put(flag.getKey(), flag); cluster.settings.flags.put(flag.getKey(), flag);
} }
} else if (cluster.settings.flags.size() == 0) { } else if (cluster.settings.flags.isEmpty()) {
return; return;
} else { } else {
cluster.settings.flags.clear(); cluster.settings.flags.clear();
@ -413,7 +413,7 @@ public class FlagManager {
* @return AbstractFlag * @return AbstractFlag
*/ */
public static AbstractFlag getFlag(final String string, final boolean create) { 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 new AbstractFlag(string);
} }
return getFlag(string); return getFlag(string);

View File

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

View File

@ -20,14 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.generator; 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.PS;
import com.intellectualcrafters.plot.commands.Template; import com.intellectualcrafters.plot.commands.Template;
import com.intellectualcrafters.plot.object.ChunkLoc; 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.SetQueue;
import com.intellectualcrafters.plot.util.WorldUtil; 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 { public class HybridPlotManager extends ClassicPlotManager {
@Override @Override
@ -66,7 +66,7 @@ public class HybridPlotManager extends ClassicPlotManager {
if (plot.exists()) { if (plot.exists()) {
files.add(new FileBytes(newDir + "plot.schematic", Files.readAllBytes(plot.toPath()))); files.add(new FileBytes(newDir + "plot.schematic", Files.readAllBytes(plot.toPath())));
} }
} catch (final Exception e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
Template.zipAll(plotworld.worldname, files); Template.zipAll(plotworld.worldname, files);

View File

@ -20,9 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.generator; package com.intellectualcrafters.plot.generator;
import java.util.HashMap;
import java.util.HashSet;
import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; 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.Dimension;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
public class HybridPlotWorld extends ClassicPlotWorld { import java.util.HashMap;
public HybridPlotWorld(String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) { import java.util.HashSet;
super(worldname, id, generator, min, max);
}
public class HybridPlotWorld extends ClassicPlotWorld {
public boolean ROAD_SCHEMATIC_ENABLED; public boolean ROAD_SCHEMATIC_ENABLED;
public short SCHEMATIC_HEIGHT; public short SCHEMATIC_HEIGHT;
public boolean PLOT_SCHEMATIC = false; public boolean PLOT_SCHEMATIC = false;
public short REQUIRED_CHANGES = 0; public short REQUIRED_CHANGES = 0;
public short PATH_WIDTH_LOWER; public short PATH_WIDTH_LOWER;
public short PATH_WIDTH_UPPER; public short PATH_WIDTH_UPPER;
public HashMap<Integer, HashMap<Integer, PlotBlock>> G_SCH; public HashMap<Integer, HashMap<Integer, PlotBlock>> G_SCH;
public HashMap<Integer, HashSet<PlotItem>> G_SCH_STATE; 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 * 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. * configuration section for that specific world.
@ -72,10 +181,10 @@ public class HybridPlotWorld extends ClassicPlotWorld {
@Override @Override
public boolean isCompatible(PlotArea plotworld) { public boolean isCompatible(PlotArea plotworld) {
if (plotworld == null || !(plotworld instanceof SquarePlotWorld)) { if (!(plotworld instanceof SquarePlotWorld)) {
return false; return false;
} }
return ((ClassicPlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH; return ((SquarePlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH;
} }
public void setupSchematics() { public void setupSchematics() {
@ -99,11 +208,11 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short w3 = (short) d3.getX(); final short w3 = (short) d3.getX();
final short l3 = (short) d3.getZ(); final short l3 = (short) d3.getZ();
final short h3 = (short) d3.getY(); final short h3 = (short) d3.getY();
int center_shift_x = 0;
int center_shift_z = 0; int center_shift_z = 0;
if (l3 < PLOT_WIDTH) { if (l3 < PLOT_WIDTH) {
center_shift_z = (PLOT_WIDTH - l3) / 2; center_shift_z = (PLOT_WIDTH - l3) / 2;
} }
int center_shift_x = 0;
if (w3 < PLOT_WIDTH) { if (w3 < PLOT_WIDTH) {
center_shift_x = (PLOT_WIDTH - w3) / 2; center_shift_x = (PLOT_WIDTH - w3) / 2;
} }
@ -114,7 +223,8 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short id = ids[index]; final short id = ids[index];
final byte data = datas[index]; final byte data = datas[index];
if (id != 0) { 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"); PS.debug(C.PREFIX.s() + "&3 - schematic: &7false");
return; return;
} }
ROAD_SCHEMATIC_ENABLED = true; ROAD_SCHEMATIC_ENABLED = true;
// Do not populate road if using schematic population // Do not populate road if using schematic population
ROAD_BLOCK = new PlotBlock(ROAD_BLOCK.id, (byte) 0); ROAD_BLOCK = new PlotBlock(ROAD_BLOCK.id, (byte) 0);
final short[] ids1 = schem1.getIds(); final short[] ids1 = schem1.getIds();
final byte[] datas1 = schem1.getDatas(); final byte[] datas1 = schem1.getDatas();
final short[] ids2 = schem2.getIds(); final short[] ids2 = schem2.getIds();
final byte[] datas2 = schem2.getDatas(); final byte[] datas2 = schem2.getDatas();
final Dimension d1 = schem1.getSchematicDimension(); final Dimension d1 = schem1.getSchematicDimension();
final short w1 = (short) d1.getX(); final short w1 = (short) d1.getX();
final short l1 = (short) d1.getZ(); final short l1 = (short) d1.getZ();
@ -166,8 +276,8 @@ public class HybridPlotWorld extends ClassicPlotWorld {
final short id = ids1[index]; final short id = ids1[index];
final byte data = datas1[index]; final byte data = datas1[index];
if (id != 0) { if (id != 0) {
addOverlayBlock((short) (x - (shift)), (y), (short) (z + shift + oddshift), id, data, false); 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) (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 short id = ids2[index];
final byte data = datas2[index]; final byte data = datas2[index];
if (id != 0) { 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) { public void addOverlayBlock(short x, final short y, short z, final short id, byte data, final boolean rotate) {
if (z < 0) { if (z < 0) {
z += SIZE; z += SIZE;
@ -312,7 +305,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
} }
if (rotate) { if (rotate) {
final byte newdata = rotate(id, data); final byte newdata = rotate(id, data);
if ((data == 0) && (newdata == 0)) { if (data == 0 && newdata == 0) {
return; return;
} }
data = newdata; data = newdata;

View File

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

View File

@ -29,8 +29,8 @@ public abstract class IndependentPlotGenerator {
* Return a new PlotArea object * Return a new PlotArea object
* @param world world name * @param world world name
* @param id (May be null) Area name * @param id (May be null) Area name
* @param min Min plot id (may be null) * @param min Min plot type (may be null)
* @param max Max plot id (may be null) * @param max Max plot type (may be null)
* @return * @return
*/ */
public abstract PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max); 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() { Runnable run = new Runnable() {
@Override @Override
public void run() { public void run() {
if (regions.size() == 0) { if (regions.isEmpty()) {
whenDone.run(); whenDone.run();
return; return;
} }

View File

@ -4,20 +4,15 @@ import com.intellectualcrafters.plot.PS;
/** /**
* Created 2015-02-11 for PlotSquared * Created 2015-02-11 for PlotSquared
* *
*/ */
public class Location implements Cloneable, Comparable<Location> { public class Location implements Cloneable, Comparable<Location> {
private int x, y, z; private int x, y, z;
private float yaw, pitch; private float yaw, pitch;
private String world; 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) { public Location(final String world, final int x, final int y, final int z, final float yaw, final float pitch) {
this.world = world; this.world = world;
this.x = x; this.x = x;
@ -26,7 +21,6 @@ public class Location implements Cloneable, Comparable<Location> {
this.yaw = yaw; this.yaw = yaw;
this.pitch = pitch; this.pitch = pitch;
built = false; built = false;
o = null;
} }
public Location() { 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) { public Location(final String world, final int x, final int y, final int z) {
this(world, x, y, z, 0f, 0f); this(world, x, y, z, 0f, 0f);
} }
@Override
public Location clone() {
return new Location(world, x, y, z, yaw, pitch);
}
public int getX() { public int getX() {
return x; return x;
} }
@ -67,7 +66,12 @@ public class Location implements Cloneable, Comparable<Location> {
public String getWorld() { public String getWorld() {
return world; return world;
} }
public void setWorld(final String world) {
this.world = world;
built = false;
}
public PlotArea getPlotArea() { public PlotArea getPlotArea() {
return PS.get().getPlotAreaAbs(this); return PS.get().getPlotAreaAbs(this);
} }
@ -76,7 +80,7 @@ public class Location implements Cloneable, Comparable<Location> {
PlotArea area = PS.get().getPlotAreaAbs(this); PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getOwnedPlot(this) : null; return area != null ? area.getOwnedPlot(this) : null;
} }
public Plot getOwnedPlotAbs() { public Plot getOwnedPlotAbs() {
PlotArea area = PS.get().getPlotAreaAbs(this); PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getOwnedPlotAbs(this) : null; return area != null ? area.getOwnedPlotAbs(this) : null;
@ -88,25 +92,19 @@ public class Location implements Cloneable, Comparable<Location> {
public boolean isPlotRoad() { public boolean isPlotRoad() {
PlotArea area = PS.get().getPlotAreaAbs(this); PlotArea area = PS.get().getPlotAreaAbs(this);
if (area == null) { return area != null && area.getPlotAbs(this) == null;
return false;
}
return area.getPlotAbs(this) == null;
} }
public boolean isUnownedPlotArea() { public boolean isUnownedPlotArea() {
PlotArea area = PS.get().getPlotAreaAbs(this); PlotArea area = PS.get().getPlotAreaAbs(this);
if (area == null) { return area != null && area.getOwnedPlotAbs(this) == null;
return false;
}
return area.getOwnedPlotAbs(this) == null;
} }
public PlotManager getPlotManager() { public PlotManager getPlotManager() {
PlotArea pa = getPlotArea(); PlotArea pa = getPlotArea();
return pa != null ? pa.getPlotManager() : null; return pa != null ? pa.getPlotManager() : null;
} }
public Plot getPlotAbs() { public Plot getPlotAbs() {
PlotArea area = PS.get().getPlotAreaAbs(this); PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getPlotAbs(this) : null; return area != null ? area.getPlotAbs(this) : null;
@ -116,15 +114,10 @@ public class Location implements Cloneable, Comparable<Location> {
PlotArea area = PS.get().getPlotAreaAbs(this); PlotArea area = PS.get().getPlotAreaAbs(this);
return area != null ? area.getPlot(this) : null; return area != null ? area.getPlot(this) : null;
} }
public ChunkLoc getChunkLoc() { public ChunkLoc getChunkLoc() {
return new ChunkLoc(x >> 4, z >> 4); return new ChunkLoc(x >> 4, z >> 4);
} }
public void setWorld(final String world) {
this.world = world;
built = false;
}
public float getYaw() { public float getYaw() {
return yaw; return yaw;
@ -156,7 +149,7 @@ public class Location implements Cloneable, Comparable<Location> {
final double x = getX() - l2.getX(); final double x = getX() - l2.getX();
final double y = getY() - l2.getY(); 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); return x * x + y * y + z * z;
} }
public double getEuclideanDistance(final Location l2) { 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); return getEuclideanDistanceSquared(origin) < radius * radius;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 127; int hash = 127;
hash = (hash * 31) + x; hash = hash * 31 + x;
hash = (hash * 31) + y; hash = hash * 31 + y;
hash = (hash * 31) + z; hash = hash * 31 + z;
hash = (int) ((hash * 31) + getYaw()); hash = (int) (hash * 31 + getYaw());
hash = (int) ((hash * 31) + getPitch()); hash = (int) (hash * 31 + getPitch());
return (hash * 31) + (world == null ? 127 : world.hashCode()); 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()); 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) { 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 + 0.0);
final double c = Math.sqrt((l * l) + (w * w)); if (Math.asin((double) 0 / c) / Math.PI * 180 > 90) {
if (((Math.asin(w / c) / Math.PI) * 180) > 90) { setYaw((float) (180 - -Math.asin(l / c) / Math.PI * 180));
setYaw((float) (180 - ((-Math.asin(l / c) / Math.PI) * 180)));
} else { } else {
setYaw((float) ((-Math.asin(l / c) / Math.PI) * 180)); setYaw((float) (-Math.asin(l / c) / Math.PI * 180));
} }
built = false; built = false;
} }
@ -211,7 +203,7 @@ public class Location implements Cloneable, Comparable<Location> {
return false; 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()); return x == l.getX() && y == l.getY() && z == l.getZ() && world.equals(l.getWorld()) && yaw == l.getY() && pitch == l.getPitch();
} }
@Override @Override
@ -219,10 +211,10 @@ public class Location implements Cloneable, Comparable<Location> {
if (o == null) { if (o == null) {
throw new NullPointerException("Specified object was null"); throw new NullPointerException("Specified object was null");
} }
if (((x == o.getX()) && (y == o.getY())) || (z == o.getZ())) { if (x == o.getX() && y == o.getY() || z == o.getZ()) {
return 0; return 0;
} }
if ((x < o.getX()) && (y < o.getY()) && (z < o.getZ())) { if (x < o.getX() && y < o.getY() && z < o.getZ()) {
return -1; return -1;
} }
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; 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.io.IOException;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.ArrayDeque; import java.util.ArrayDeque;
@ -9,31 +17,22 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; 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 class PlotAnalysis {
public static PlotAnalysis MODIFIERS = new PlotAnalysis();
public static boolean running = false;
public int changes; public int changes;
public int faces; public int faces;
public int data; public int data;
public int air; public int air;
public int variety; public int variety;
public int changes_sd; public int changes_sd;
public int faces_sd; public int faces_sd;
public int data_sd; public int data_sd;
public int air_sd; public int air_sd;
public int variety_sd; public int variety_sd;
private int complexity; private int complexity;
public static PlotAnalysis MODIFIERS = new PlotAnalysis();
public static PlotAnalysis getAnalysis(final Plot plot) { public static PlotAnalysis getAnalysis(final Plot plot) {
final Flag flag = FlagManager.getPlotFlagRaw(plot, "analysis"); final Flag flag = FlagManager.getPlotFlagRaw(plot, "analysis");
if (flag != null) { if (flag != null) {
@ -44,46 +43,23 @@ public class PlotAnalysis {
analysis.data = values.get(2); // 0 analysis.data = values.get(2); // 0
analysis.air = values.get(3); // 19100 analysis.air = values.get(3); // 19100
analysis.variety = values.get(4); // 266 analysis.variety = values.get(4); // 266
analysis.changes_sd = values.get(5); // 2104 analysis.changes_sd = values.get(5); // 2104
analysis.faces_sd = values.get(6); // 89 analysis.faces_sd = values.get(6); // 89
analysis.data_sd = values.get(7); // 0 analysis.data_sd = values.get(7); // 0
analysis.air_sd = values.get(8); // 18909 analysis.air_sd = values.get(8); // 18909
analysis.variety_sd = values.get(9); // 263 analysis.variety_sd = values.get(9); // 263
analysis.complexity = analysis.getComplexity(); analysis.complexity = analysis.getComplexity();
return analysis; return analysis;
} }
return null; 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) { public static void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone) {
HybridUtils.manager.analyzePlot(plot, 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> * 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 * - 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"); PS.debug(" - $1Reducing " + plots.size() + " plots to those with sufficient data");
while (iter.hasNext()) { while (iter.hasNext()) {
final Plot plot = iter.next(); 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(); iter.remove();
} else { } else {
plot.addRunning(); plot.addRunning();
} }
} }
PS.debug(" - | Reduced to " + plots.size() + " plots"); PS.debug(" - | Reduced to " + plots.size() + " plots");
if (plots.size() < 3) { if (plots.size() < 3) {
PS.debug("Calibration cancelled due to insufficient comparison data, please try again later"); PS.debug("Calibration cancelled due to insufficient comparison data, please try again later");
running = false; running = false;
@ -124,25 +100,25 @@ public class PlotAnalysis {
} }
return; return;
} }
PS.debug(" - $1Analyzing plot contents (this may take a while)"); PS.debug(" - $1Analyzing plot contents (this may take a while)");
final int[] changes = new int[plots.size()]; final int[] changes = new int[plots.size()];
final int[] faces = new int[plots.size()]; final int[] faces = new int[plots.size()];
final int[] data = new int[plots.size()]; final int[] data = new int[plots.size()];
final int[] air = new int[plots.size()]; final int[] air = new int[plots.size()];
final int[] variety = new int[plots.size()]; final int[] variety = new int[plots.size()];
final int[] changes_sd = new int[plots.size()]; final int[] changes_sd = new int[plots.size()];
final int[] faces_sd = new int[plots.size()]; final int[] faces_sd = new int[plots.size()];
final int[] data_sd = new int[plots.size()]; final int[] data_sd = new int[plots.size()];
final int[] air_sd = new int[plots.size()]; final int[] air_sd = new int[plots.size()];
final int[] variety_sd = new int[plots.size()]; final int[] variety_sd = new int[plots.size()];
final int[] ratings = new int[plots.size()]; final int[] ratings = new int[plots.size()];
final AtomicInteger mi = new AtomicInteger(0); final AtomicInteger mi = new AtomicInteger(0);
final Thread ratingAnalysis = new Thread(new Runnable() { final Thread ratingAnalysis = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -155,7 +131,7 @@ public class PlotAnalysis {
} }
}); });
ratingAnalysis.start(); ratingAnalysis.start();
final ArrayDeque<Plot> plotsQueue = new ArrayDeque<>(plots); final ArrayDeque<Plot> plotsQueue = new ArrayDeque<>(plots);
while (true) { while (true) {
final Plot queuePlot = plotsQueue.poll(); final Plot queuePlot = plotsQueue.poll();
@ -193,44 +169,44 @@ public class PlotAnalysis {
e.printStackTrace(); e.printStackTrace();
} }
} }
PS.debug(" - $1Waiting on plot rating thread: " + ((mi.intValue() * 100) / plots.size()) + "%"); PS.debug(" - $1Waiting on plot rating thread: " + ((mi.intValue() * 100) / plots.size()) + "%");
try { try {
ratingAnalysis.join(); ratingAnalysis.join();
} catch (final InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
PS.debug(" - $1Processing and grouping single plot analysis for bulk processing"); PS.debug(" - $1Processing and grouping single plot analysis for bulk processing");
for (int i = 0; i < plots.size(); i++) { for (int i = 0; i < plots.size(); i++) {
final Plot plot = plots.get(i); final Plot plot = plots.get(i);
PS.debug(" | " + plot); PS.debug(" | " + plot);
final PlotAnalysis analysis = plot.getComplexity(); final PlotAnalysis analysis = plot.getComplexity();
changes[i] = analysis.changes; changes[i] = analysis.changes;
faces[i] = analysis.faces; faces[i] = analysis.faces;
data[i] = analysis.data; data[i] = analysis.data;
air[i] = analysis.air; air[i] = analysis.air;
variety[i] = analysis.variety; variety[i] = analysis.variety;
changes_sd[i] = analysis.changes_sd; changes_sd[i] = analysis.changes_sd;
faces_sd[i] = analysis.faces_sd; faces_sd[i] = analysis.faces_sd;
data_sd[i] = analysis.data_sd; data_sd[i] = analysis.data_sd;
air_sd[i] = analysis.air_sd; air_sd[i] = analysis.air_sd;
variety_sd[i] = analysis.variety_sd; variety_sd[i] = analysis.variety_sd;
} }
PS.debug(" - $1Calculating rankings"); PS.debug(" - $1Calculating rankings");
final int[] rank_ratings = rank(ratings); final int[] rank_ratings = rank(ratings);
final int n = rank_ratings.length; final int n = rank_ratings.length;
final int optimal_index = (int) Math.round((1 - threshold) * (n - 1)); final int optimal_index = (int) Math.round((1 - threshold) * (n - 1));
PS.debug(" - $1Calculating rank correlation: "); 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 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"); 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[] rank_changes = rank(changes);
final int[] sd_changes = getSD(rank_changes, rank_ratings); final int[] sd_changes = getSD(rank_changes, rank_ratings);
final int[] variance_changes = square(sd_changes); final int[] variance_changes = square(sd_changes);
@ -238,7 +214,7 @@ public class PlotAnalysis {
final double factor_changes = getCC(n, sum_changes); final double factor_changes = getCC(n, sum_changes);
PlotAnalysis.MODIFIERS.changes = factor_changes == 1 ? 0 : (int) ((factor_changes * 1000) / MathMan.getMean(changes)); PlotAnalysis.MODIFIERS.changes = factor_changes == 1 ? 0 : (int) ((factor_changes * 1000) / MathMan.getMean(changes));
PS.debug(" - | changes " + factor_changes); PS.debug(" - | changes " + factor_changes);
final int[] rank_faces = rank(faces); final int[] rank_faces = rank(faces);
final int[] sd_faces = getSD(rank_faces, rank_ratings); final int[] sd_faces = getSD(rank_faces, rank_ratings);
final int[] variance_faces = square(sd_faces); final int[] variance_faces = square(sd_faces);
@ -246,7 +222,7 @@ public class PlotAnalysis {
final double factor_faces = getCC(n, sum_faces); final double factor_faces = getCC(n, sum_faces);
PlotAnalysis.MODIFIERS.faces = factor_faces == 1 ? 0 : (int) ((factor_faces * 1000) / MathMan.getMean(faces)); PlotAnalysis.MODIFIERS.faces = factor_faces == 1 ? 0 : (int) ((factor_faces * 1000) / MathMan.getMean(faces));
PS.debug(" - | faces " + factor_faces); PS.debug(" - | faces " + factor_faces);
final int[] rank_data = rank(data); final int[] rank_data = rank(data);
final int[] sd_data = getSD(rank_data, rank_ratings); final int[] sd_data = getSD(rank_data, rank_ratings);
final int[] variance_data = square(sd_data); final int[] variance_data = square(sd_data);
@ -254,7 +230,7 @@ public class PlotAnalysis {
final double factor_data = getCC(n, sum_data); final double factor_data = getCC(n, sum_data);
PlotAnalysis.MODIFIERS.data = factor_data == 1 ? 0 : (int) ((factor_data * 1000) / MathMan.getMean(data)); PlotAnalysis.MODIFIERS.data = factor_data == 1 ? 0 : (int) ((factor_data * 1000) / MathMan.getMean(data));
PS.debug(" - | data " + factor_data); PS.debug(" - | data " + factor_data);
final int[] rank_air = rank(air); final int[] rank_air = rank(air);
final int[] sd_air = getSD(rank_air, rank_ratings); final int[] sd_air = getSD(rank_air, rank_ratings);
final int[] variance_air = square(sd_air); final int[] variance_air = square(sd_air);
@ -262,7 +238,7 @@ public class PlotAnalysis {
final double factor_air = getCC(n, sum_air); final double factor_air = getCC(n, sum_air);
PlotAnalysis.MODIFIERS.air = factor_air == 1 ? 0 : (int) ((factor_air * 1000) / MathMan.getMean(air)); PlotAnalysis.MODIFIERS.air = factor_air == 1 ? 0 : (int) ((factor_air * 1000) / MathMan.getMean(air));
PS.debug(" - | air " + factor_air); PS.debug(" - | air " + factor_air);
final int[] rank_variety = rank(variety); final int[] rank_variety = rank(variety);
final int[] sd_variety = getSD(rank_variety, rank_ratings); final int[] sd_variety = getSD(rank_variety, rank_ratings);
final int[] variance_variety = square(sd_variety); final int[] variance_variety = square(sd_variety);
@ -270,7 +246,7 @@ public class PlotAnalysis {
final double factor_variety = getCC(n, sum_variety); final double factor_variety = getCC(n, sum_variety);
PlotAnalysis.MODIFIERS.variety = factor_variety == 1 ? 0 : (int) ((factor_variety * 1000) / MathMan.getMean(variety)); PlotAnalysis.MODIFIERS.variety = factor_variety == 1 ? 0 : (int) ((factor_variety * 1000) / MathMan.getMean(variety));
PS.debug(" - | variety " + factor_variety); PS.debug(" - | variety " + factor_variety);
final int[] rank_changes_sd = rank(changes_sd); final int[] rank_changes_sd = rank(changes_sd);
final int[] sd_changes_sd = getSD(rank_changes_sd, rank_ratings); final int[] sd_changes_sd = getSD(rank_changes_sd, rank_ratings);
final int[] variance_changes_sd = square(sd_changes_sd); 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); 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)); 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); PS.debug(" - | changes_sd " + factor_changes_sd);
final int[] rank_faces_sd = rank(faces_sd); final int[] rank_faces_sd = rank(faces_sd);
final int[] sd_faces_sd = getSD(rank_faces_sd, rank_ratings); final int[] sd_faces_sd = getSD(rank_faces_sd, rank_ratings);
final int[] variance_faces_sd = square(sd_faces_sd); 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); 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)); 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); PS.debug(" - | faces_sd " + factor_faces_sd);
final int[] rank_data_sd = rank(data_sd); final int[] rank_data_sd = rank(data_sd);
final int[] sd_data_sd = getSD(rank_data_sd, rank_ratings); final int[] sd_data_sd = getSD(rank_data_sd, rank_ratings);
final int[] variance_data_sd = square(sd_data_sd); 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); 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)); 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); PS.debug(" - | data_sd " + factor_data_sd);
final int[] rank_air_sd = rank(air_sd); final int[] rank_air_sd = rank(air_sd);
final int[] sd_air_sd = getSD(rank_air_sd, rank_ratings); final int[] sd_air_sd = getSD(rank_air_sd, rank_ratings);
final int[] variance_air_sd = square(sd_air_sd); 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); 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)); 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); PS.debug(" - | air_sd " + factor_air_sd);
final int[] rank_variety_sd = rank(variety_sd); final int[] rank_variety_sd = rank(variety_sd);
final int[] sd_variety_sd = getSD(rank_variety_sd, rank_ratings); final int[] sd_variety_sd = getSD(rank_variety_sd, rank_ratings);
final int[] variance_variety_sd = square(sd_variety_sd); 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); 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)); 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); PS.debug(" - | variety_sd " + factor_variety_sd);
final int[] complexity = new int[n]; final int[] complexity = new int[n];
PS.debug(" $1Calculating threshold"); PS.debug(" $1Calculating threshold");
int max = 0; int max = 0;
int min = 0; int min = 0;
@ -358,7 +334,7 @@ public class PlotAnalysis {
logln("Ratings: "); logln("Ratings: ");
logln(rank_ratings); logln(rank_ratings);
} }
// Save calibration // Save calibration
PS.debug(" $1Saving calibration"); PS.debug(" $1Saving calibration");
final YamlConfiguration config = PS.get().config; final YamlConfiguration config = PS.get().config;
@ -378,7 +354,7 @@ public class PlotAnalysis {
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
PS.debug("$1Done!"); PS.debug("$1Done!");
running = false; running = false;
for (final Plot plot : plots) { for (final Plot plot : plots) {
@ -397,7 +373,7 @@ public class PlotAnalysis {
String result = ""; String result = "";
if (obj.getClass().isArray()) { if (obj.getClass().isArray()) {
String prefix = ""; String prefix = "";
for (int i = 0; i < Array.getLength(obj); i++) { for (int i = 0; i < Array.getLength(obj); i++) {
result += prefix + log(Array.get(obj, i)); result += prefix + log(Array.get(obj, i));
prefix = ","; prefix = ",";
@ -520,7 +496,7 @@ public class PlotAnalysis {
} }
} }
} }
final int[] ranks = new int[input.length]; final int[] ranks = new int[input.length];
for (int i = 0; i < input.length; i++) { for (int i = 0; i < input.length; i++) {
final int index = input[i]; final int index = input[i];
@ -557,4 +533,25 @@ public class PlotAnalysis {
placement *= SIZE; 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; 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.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; 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.WorldUtil;
import com.intellectualcrafters.plot.util.area.QuadMap; 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 * @author Jesse Boyd
*/ */
public abstract class PlotArea { 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 int MAX_PLOT_MEMBERS = 128;
public boolean AUTO_MERGE = false; public boolean AUTO_MERGE = false;
public boolean ALLOW_SIGNS = true; public boolean ALLOW_SIGNS = true;
@ -80,33 +89,22 @@ public abstract class PlotArea {
public int MAX_BUILD_HEIGHT = 256; public int MAX_BUILD_HEIGHT = 256;
public int MIN_BUILD_HEIGHT = 1; public int MIN_BUILD_HEIGHT = 1;
public PlotGamemode GAMEMODE = PlotGamemode.CREATIVE; public PlotGamemode GAMEMODE = PlotGamemode.CREATIVE;
int hash;
public final String worldname;
public final String id;
public final PlotManager manager;
private final PlotId min;
private final PlotId max;
private RegionWrapper region; private RegionWrapper region;
/** /**
* Please ignore * Please ignore
*/ */
@Deprecated @Deprecated
private int compatibility_id; private int compatibility_id;
private ConcurrentHashMap<String, Object> meta; private ConcurrentHashMap<String, Object> meta;
private final ConcurrentHashMap<PlotId, Plot> plots = new ConcurrentHashMap<>();
private QuadMap<PlotCluster> clusters; private QuadMap<PlotCluster> clusters;
private final IndependentPlotGenerator generator;
public PlotArea(final String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) { public PlotArea(final String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) {
this.worldname = worldname; this.worldname = worldname;
this.id = id; this.id = id;
this.manager = generator != null ? generator.getNewPlotManager() : null; this.manager = generator != null ? generator.getNewPlotManager() : null;
this.generator = generator; this.generator = generator;
if ((min == null) || (max == null)) { if (min == null || max == null) {
if (min != max) { if (min != max) {
throw new IllegalArgumentException("None of the ids can be null for this constructor"); 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;} public ConfigurationNode[] getSettingNodes() {return null;}
}; };
} }
/** /**
* Returns the region for this PlotArea * Returns the region for this PlotArea
* @return * @return
@ -158,7 +156,7 @@ public abstract class PlotArea {
public PlotId getMin() { public PlotId getMin() {
return min == null ? new PlotId(Integer.MIN_VALUE, Integer.MIN_VALUE) : min; return min == null ? new PlotId(Integer.MIN_VALUE, Integer.MIN_VALUE) : min;
} }
/** /**
* Returns the max PlotId * Returns the max PlotId
* @return * @return
@ -171,8 +169,6 @@ public abstract class PlotArea {
return generator; return generator;
} }
public final int worldhash;
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
@ -187,7 +183,7 @@ public abstract class PlotArea {
final PlotArea plotarea = (PlotArea) obj; final PlotArea plotarea = (PlotArea) obj;
return this.worldhash == plotarea.worldhash && this.worldname.equals(plotarea.worldname) && StringMan.isEqual(this.id, plotarea.id); return this.worldhash == plotarea.worldhash && this.worldname.equals(plotarea.worldname) && StringMan.isEqual(this.id, plotarea.id);
} }
public Set<PlotCluster> getClusters() { public Set<PlotCluster> getClusters() {
return clusters == null ? new HashSet<PlotCluster>() : clusters.getAll(); return clusters == null ? new HashSet<PlotCluster>() : clusters.getAll();
} }
@ -238,7 +234,7 @@ public abstract class PlotArea {
SCHEMATIC_FILE = config.getString("schematic.file"); SCHEMATIC_FILE = config.getString("schematic.file");
SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim"); SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim");
SCHEMATICS = config.getStringList("schematic.schematics"); 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"); PLOT_PRICE = config.getDouble("economy.prices.claim");
MERGE_PRICE = config.getDouble("economy.prices.merge"); MERGE_PRICE = config.getDouble("economy.prices.merge");
SELL_PRICE = config.getDouble("economy.prices.sell"); SELL_PRICE = config.getDouble("economy.prices.sell");
@ -246,7 +242,7 @@ public abstract class PlotArea {
WORLD_BORDER = config.getBoolean("world.border"); WORLD_BORDER = config.getBoolean("world.border");
MAX_BUILD_HEIGHT = config.getInt("world.max_height"); MAX_BUILD_HEIGHT = config.getInt("world.max_height");
MIN_BUILD_HEIGHT = config.getInt("min.max_height"); MIN_BUILD_HEIGHT = config.getInt("min.max_height");
switch (config.getString("world.gamemode").toLowerCase()) { switch (config.getString("world.gamemode").toLowerCase()) {
case "survival": case "survival":
case "s": case "s":
@ -271,10 +267,10 @@ public abstract class PlotArea {
PS.debug("&cInvalid gamemode set for: " + worldname); PS.debug("&cInvalid gamemode set for: " + worldname);
break; break;
} }
HOME_ALLOW_NONMEMBER = config.getBoolean("home.allow-nonmembers"); HOME_ALLOW_NONMEMBER = config.getBoolean("home.allow-nonmembers");
final String homeDefault = config.getString("home.default"); final String homeDefault = config.getString("home.default");
if (homeDefault.equalsIgnoreCase("side")) { if ("side".equalsIgnoreCase(homeDefault)) {
DEFAULT_HOME = null; DEFAULT_HOME = null;
} else if (StringMan.isEqualIgnoreCaseToAny(homeDefault, "center", "middle")) { } else if (StringMan.isEqualIgnoreCaseToAny(homeDefault, "center", "middle")) {
DEFAULT_HOME = new PlotLoc(Integer.MAX_VALUE, Integer.MAX_VALUE); DEFAULT_HOME = new PlotLoc(Integer.MAX_VALUE, Integer.MAX_VALUE);
@ -282,20 +278,20 @@ public abstract class PlotArea {
try { try {
final String[] split = homeDefault.split(","); final String[] split = homeDefault.split(",");
DEFAULT_HOME = new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1])); DEFAULT_HOME = new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
} catch (final Exception e) { } catch (NumberFormatException e) {
DEFAULT_HOME = null; DEFAULT_HOME = null;
} }
} }
List<String> flags = config.getStringList("flags.default"); List<String> flags = config.getStringList("flags.default");
if ((flags == null) || (flags.size() == 0)) { if (flags == null || flags.isEmpty()) {
flags = config.getStringList("flags"); flags = config.getStringList("flags");
if ((flags == null) || (flags.size() == 0)) { if (flags == null || flags.isEmpty()) {
flags = new ArrayList<>(); flags = new ArrayList<>();
final ConfigurationSection section = config.getConfigurationSection("flags"); final ConfigurationSection section = config.getConfigurationSection("flags");
final Set<String> keys = section.getKeys(false); final Set<String> keys = section.getKeys(false);
for (final String key : keys) { for (final String key : keys) {
if (!key.equals("default")) { if (!"default".equals(key)) {
flags.add(key + ";" + section.get(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.max_height", MAX_BUILD_HEIGHT);
options.put("world.min_height", MIN_BUILD_HEIGHT); options.put("world.min_height", MIN_BUILD_HEIGHT);
options.put("world.gamemode", GAMEMODE.name().toLowerCase()); options.put("world.gamemode", GAMEMODE.name().toLowerCase());
if ((TYPE != 0)) { if (TYPE != 0) {
options.put("generator.terrain", TERRAIN); options.put("generator.terrain", TERRAIN);
options.put("generator.type", TYPE); options.put("generator.type", TYPE);
} }
@ -359,9 +355,9 @@ public abstract class PlotArea {
for (final ConfigurationNode setting : settings) { for (final ConfigurationNode setting : settings) {
options.put(setting.getConstant(), setting.getValue()); options.put(setting.getConstant(), setting.getValue());
} }
for (final String option : options.keySet()) { for (final Entry<String, Object> stringObjectEntry : options.entrySet()) {
if (!config.contains(option)) { if (!config.contains(stringObjectEntry.getKey())) {
config.set(option, options.get(option)); config.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
} }
} }
if (!config.contains("flags")) { if (!config.contains("flags")) {
@ -371,11 +367,9 @@ public abstract class PlotArea {
@Override @Override
public String toString() { public String toString() {
return (compatibility_id == 1 || id == null) ? worldname : worldname + ";" + id; return compatibility_id == 1 || id == null ? worldname : worldname + ";" + id;
} }
int hash;
@Override @Override
public int hashCode() { public int hashCode() {
if (hash != 0) { if (hash != 0) {
@ -559,7 +553,7 @@ public abstract class PlotArea {
*/ */
public void setMeta(final String key, final Object value) { public void setMeta(final String key, final Object value) {
if (meta == null) { if (meta == null) {
meta = new ConcurrentHashMap<String, Object>(); meta = new ConcurrentHashMap<>();
} }
meta.put(key, value); meta.put(key, value);
} }
@ -716,7 +710,7 @@ public abstract class PlotArea {
} }
public boolean mergePlots(final PlotPlayer player, final ArrayList<PlotId> plotIds) { 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; final double cost = plotIds.size() * MERGE_PRICE;
if (cost > 0d) { if (cost > 0d) {
if (EconHandler.manager.getMoney(player) < cost) { if (EconHandler.manager.getMoney(player) < cost) {
@ -746,10 +740,10 @@ public abstract class PlotArea {
if (!result) { if (!result) {
return false; return false;
} }
final HashSet<UUID> trusted = new HashSet<UUID>(); final HashSet<UUID> trusted = new HashSet<>();
final HashSet<UUID> members = new HashSet<UUID>(); final HashSet<UUID> members = new HashSet<>();
final HashSet<UUID> denied = new HashSet<UUID>(); final HashSet<UUID> denied = new HashSet<>();
manager.startPlotMerge(this, plotIds); manager.startPlotMerge(this, plotIds);
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.x; x <= pos2.x; x++) {
@ -767,7 +761,6 @@ public abstract class PlotArea {
members.removeAll(trusted); members.removeAll(trusted);
denied.removeAll(trusted); denied.removeAll(trusted);
denied.removeAll(members); denied.removeAll(members);
Plot plot2;
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.y; y <= pos2.y; y++) {
final boolean lx = x < pos2.x; final boolean lx = x < pos2.x;
@ -777,6 +770,7 @@ public abstract class PlotArea {
plot.setTrusted(trusted); plot.setTrusted(trusted);
plot.setMembers(members); plot.setMembers(members);
plot.setDenied(denied); plot.setDenied(denied);
Plot plot2;
if (lx) { if (lx) {
if (ly) { if (ly) {
if (!plot.getMerged(1) || !plot.getMerged(2)) { if (!plot.getMerged(1) || !plot.getMerged(2)) {
@ -810,20 +804,20 @@ public abstract class PlotArea {
* @return * @return
*/ */
public HashSet<Plot> getPlotSelectionOwned(final PlotId pos1, final PlotId pos2) { 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<>(); final HashSet<Plot> result = new HashSet<>();
if (size < 16 || size < getPlotCount()) { if (size < 16 || size < getPlotCount()) {
for (final PlotId pid : MainUtil.getPlotSelectionIds(pos1, pos2)) { for (final PlotId pid : MainUtil.getPlotSelectionIds(pos1, pos2)) {
final Plot plot = getPlotAbs(pid); final Plot plot = getPlotAbs(pid);
if (plot.hasOwner()) { 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); result.add(plot);
} }
} }
} }
} else { } else {
for (final Plot plot : getPlots()) { 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); result.add(plot);
} }
} }

View File

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

View File

@ -29,6 +29,7 @@ public class PlotId {
* y value * y value
*/ */
public Integer y; public Integer y;
private int hash;
/** /**
* PlotId class (PlotId x,y values do not correspond to Block locations) * 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 * 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 * @return null if the string is invalid
*/ */
@ -65,7 +66,11 @@ public class PlotId {
} }
return new PlotId(x, y); return new PlotId(x, y);
} }
public static PlotId unpair(int hash) {
return new PlotId(hash >> 16, hash & 0xFFFF);
}
public PlotId getRelative(final int direction) { public PlotId getRelative(final int direction) {
switch (direction) { switch (direction) {
case 0: case 0:
@ -104,12 +109,6 @@ public class PlotId {
return x + ";" + y; return x + ";" + y;
} }
public static PlotId unpair(int hash) {
return new PlotId(hash >> 16, hash & 0xFFFF);
}
private int hash;
public void recalculateHash() { public void recalculateHash() {
hash = 0; hash = 0;
hashCode(); hashCode();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,6 +11,7 @@ import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.StringTag; import com.intellectualcrafters.jnbt.StringTag;
import com.intellectualcrafters.jnbt.Tag; import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.json.JSONArray; import com.intellectualcrafters.json.JSONArray;
import com.intellectualcrafters.json.JSONException;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.generator.ClassicPlotWorld; import com.intellectualcrafters.plot.generator.ClassicPlotWorld;
@ -26,6 +27,7 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -61,7 +63,7 @@ public abstract class SchematicHandler {
if (exportAll) { if (exportAll) {
return false; return false;
} }
if (collection.size() == 0) { if (collection.isEmpty()) {
return false; return false;
} }
exportAll = true; exportAll = true;
@ -69,7 +71,7 @@ public abstract class SchematicHandler {
TaskManager.runTask(new Runnable() { TaskManager.runTask(new Runnable() {
@Override @Override
public void run() { public void run() {
if (plots.size() == 0) { if (plots.isEmpty()) {
exportAll = false; exportAll = false;
TaskManager.runTask(ifSuccess); TaskManager.runTask(ifSuccess);
return; return;
@ -162,7 +164,7 @@ public abstract class SchematicHandler {
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
return; return;
} }
// block id and data arrays // block type and data arrays
final short[] ids = schematic.ids; final short[] ids = schematic.ids;
final byte[] datas = schematic.datas; final byte[] datas = schematic.datas;
// Calculate the optimal height to paste the schematic at // Calculate the optimal height to paste the schematic at
@ -198,7 +200,7 @@ public abstract class SchematicHandler {
@Override @Override
public void run() { public void run() {
int count = 0; int count = 0;
while ((chunks.size() > 0) && (count < 256)) { while (!chunks.isEmpty() && count < 256) {
count++; count++;
final ChunkLoc chunk = chunks.remove(0); final ChunkLoc chunk = chunks.remove(0);
final int x = chunk.x; final int x = chunk.x;
@ -220,8 +222,7 @@ public abstract class SchematicHandler {
zzt = p2z; zzt = p2z;
} }
// Paste schematic here // Paste schematic here
int id;
for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) {
final int yy = y_offset + ry; final int yy = y_offset + ry;
if (yy > 255) { if (yy > 255) {
@ -235,9 +236,9 @@ public abstract class SchematicHandler {
final int xx = p1x + rx; final int xx = p1x + rx;
final int zz = p1z + rz; final int zz = p1z + rz;
id = ids[i]; int id = ids[i];
switch (id) { switch (id) {
case 0: case 0:
case 2: case 2:
@ -305,20 +306,18 @@ public abstract class SchematicHandler {
case 189: case 189:
case 190: case 190:
case 191: case 191:
case 192: { case 192:
SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, id); SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, id);
break; break;
} default:
default: {
SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, new PlotBlock((short) id, datas[i])); SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, new PlotBlock((short) id, datas[i]));
break; break;
}
} }
} }
} }
} }
} }
if (chunks.size() != 0) { if (!chunks.isEmpty()) {
final Runnable task = this; final Runnable task = this;
// Run when the queue is free // Run when the queue is free
SetQueue.IMP.addTask(new Runnable() { 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 int sy = MainUtil.getHeighestBlock(plot.getArea().worldname, l1.getX() + 1, l1.getZ() + 1);
final Dimension demensions = schematic.getSchematicDimension(); final Dimension demensions = schematic.getSchematicDimension();
final int HEIGHT = demensions.getY(); final int HEIGHT = demensions.getY();
if ((HEIGHT < 255)) { if (HEIGHT < 255) {
l1 = l1.add(0, sy - 1, 0); l1 = l1.add(0, sy - 1, 0);
} }
final int X = l1.getX() + x_offset; final int X = l1.getX() + x_offset;
@ -459,12 +458,10 @@ public abstract class SchematicHandler {
* @return schematic if found, else null * @return schematic if found, else null
*/ */
public Schematic getSchematic(final String name) { public Schematic getSchematic(final String name) {
{ final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics");
final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics"); if (!parent.exists()) {
if (!parent.exists()) { if (!parent.mkdir()) {
if (!parent.mkdir()) { throw new RuntimeException("Could not create schematic parent directory");
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")); 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 { try {
return getSchematic(new FileInputStream(file)); return getSchematic(new FileInputStream(file));
} catch (final Exception e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -495,7 +492,7 @@ public abstract class SchematicHandler {
final ReadableByteChannel rbc = Channels.newChannel(url.openStream()); final ReadableByteChannel rbc = Channels.newChannel(url.openStream());
final InputStream is = Channels.newInputStream(rbc); final InputStream is = Channels.newInputStream(rbc);
return getSchematic(is); return getSchematic(is);
} catch (final Exception e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -511,7 +508,7 @@ public abstract class SchematicHandler {
is.close(); is.close();
stream.close(); stream.close();
return getSchematic(tag); return getSchematic(tag);
} catch (final Exception e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
PS.debug(is.toString() + " | " + is.getClass().getCanonicalName() + " is not in GZIP format : " + e.getMessage()); 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); schematics.add(schematic);
} }
return Lists.reverse(schematics); return Lists.reverse(schematics);
} catch (final Exception e) { } catch (JSONException | IOException e) {
e.printStackTrace(); e.printStackTrace();
PS.debug("ERROR PARSING: " + rawJSON); PS.debug("ERROR PARSING: " + rawJSON);
} }
@ -559,17 +556,17 @@ public abstract class SchematicHandler {
} else { } else {
website = Settings.WEB_URL + "save.php?" + uuid; 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 boundary = Long.toHexString(System.currentTimeMillis());
final String CRLF = "\r\n";
final URLConnection con = new URL(website).openConnection(); final URLConnection con = new URL(website).openConnection();
con.setDoOutput(true); con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 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("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").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(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF); writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + file + ".schematic" + "\"").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(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush();
nos.close(); nos.close();
output.close();
} }
try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) { try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) {
final char[] buffer = new char[256]; 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.")) { if (!result.toString().equals("The file plot.schematic has been uploaded.")) {
PS.debug(result); PS.debug(result);
} }
} catch (final Exception e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
final int responseCode = ((HttpURLConnection) con).getResponseCode(); final int responseCode = ((HttpURLConnection) con).getResponseCode();
@ -608,7 +604,7 @@ public abstract class SchematicHandler {
return null; return null;
} }
return new URL(Settings.WEB_URL + "?key=" + uuid + "&ip=" + Settings.WEB_IP); return new URL(Settings.WEB_URL + "?key=" + uuid + "&ip=" + Settings.WEB_IP);
} catch (final Exception e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -630,11 +626,9 @@ public abstract class SchematicHandler {
try { try {
final File tmp = new File(path); final File tmp = new File(path);
tmp.getParentFile().mkdirs(); tmp.getParentFile().mkdirs();
final OutputStream stream = new FileOutputStream(path); try (OutputStream stream = new FileOutputStream(path); NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream))) {
final NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream)); output.writeTag(tag);
output.writeTag(tag); }
output.close();
stream.close();
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
@ -675,6 +669,36 @@ public abstract class SchematicHandler {
getCompoundTag(plot.getArea().worldname, plot.getRegions(), whenDone); 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 * Schematic Class
* *
@ -693,7 +717,7 @@ public abstract class SchematicHandler {
datas = b; datas = b;
schematicDimension = d; schematicDimension = d;
} }
/** /**
* Add an item to the schematic * Add an item to the schematic
* @param item * @param item
@ -704,7 +728,7 @@ public abstract class SchematicHandler {
} }
items.add(item); items.add(item);
} }
/** /**
* Get any items associated with this schematic * Get any items associated with this schematic
* @return * @return
@ -712,7 +736,7 @@ public abstract class SchematicHandler {
public HashSet<PlotItem> getItems() { public HashSet<PlotItem> getItems() {
return items; return items;
} }
/** /**
* Get the schematic dimensions * Get the schematic dimensions
* @return * @return
@ -720,15 +744,15 @@ public abstract class SchematicHandler {
public Dimension getSchematicDimension() { public Dimension getSchematicDimension() {
return schematicDimension; return schematicDimension;
} }
/** /**
* Get the block id array * Get the block type array
* @return * @return
*/ */
public short[] getIds() { public short[] getIds() {
return ids; return ids;
} }
/** /**
* Get the block data array * Get the block data array
* @return * @return
@ -741,24 +765,24 @@ public abstract class SchematicHandler {
int x1 = region.minX; int x1 = region.minX;
int x2 = region.maxX; int x2 = region.maxX;
int z1 = region.minZ; int z1 = region.minZ;
int z2 = region.maxZ; int z2 = region.maxZ;
int y1 = region.minY; int y1 = region.minY;
int y2 = Math.min(region.maxY, 255); int y2 = Math.min(region.maxY, 255);
int width = x2 - x1 + 1; int width = x2 - x1 + 1;
int length = z2 - z1 + 1; int length = z2 - z1 + 1;
int height = y2 - y1 + 1; int height = y2 - y1 + 1;
short[] ids2 = new short[width * length * height]; short[] ids2 = new short[width * length * height];
byte[] datas2 = new byte[width * length * height]; byte[] datas2 = new byte[width * length * height];
int dx = schematicDimension.getX(); int dx = schematicDimension.getX();
int dy = schematicDimension.getY(); int dy = schematicDimension.getY();
int dz = schematicDimension.getZ(); int dz = schematicDimension.getZ();
for (int y = y1; y <= y2; y++) { for (int y = y1; y <= y2; y++) {
int yy = y >= 0 ? (y < dy ? y : y - dy) : y + dy; int yy = y >= 0 ? (y < dy ? y : y - dy) : y + dy;
int i1 = yy * dx * dz; int i1 = yy * dx * dz;
@ -778,7 +802,7 @@ public abstract class SchematicHandler {
} }
return new Schematic(ids2, datas2, new Dimension(width, height, length)); return new Schematic(ids2, datas2, new Dimension(width, height, length));
} }
public void save(final File file) { public void save(final File file) {
byte[] ids2 = new byte[ids.length]; byte[] ids2 = new byte[ids.length];
for (int i = 0; i < ids.length; i++) { for (int i = 0; i < ids.length; i++) {
@ -788,34 +812,5 @@ public abstract class SchematicHandler {
SchematicHandler.this.save(tag, file.toString()); 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; package com.intellectualcrafters.plot.util;
import com.intellectualcrafters.plot.object.PlotBlock;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import com.intellectualcrafters.plot.object.PlotBlock;
public class SetQueue { public class SetQueue {
public static final SetQueue IMP = new SetQueue(); public static final SetQueue IMP = new SetQueue();
public PlotQueue<?> queue;
private final AtomicInteger time_waiting = new AtomicInteger(2); private final AtomicInteger time_waiting = new AtomicInteger(2);
private final AtomicInteger time_current = new AtomicInteger(0); private final AtomicInteger time_current = new AtomicInteger(0);
private final ArrayDeque<Runnable> runnables = new ArrayDeque<>(); private final ArrayDeque<Runnable> runnables = new ArrayDeque<>();
public PlotQueue<?> queue;
private long last; private long last;
private long last2; private long last2;
@ -72,7 +70,7 @@ public class SetQueue {
} }
public boolean tasks() { public boolean tasks() {
if (runnables.size() == 0) { if (runnables.isEmpty()) {
return false; return false;
} }
final ArrayDeque<Runnable> tmp = runnables.clone(); final ArrayDeque<Runnable> tmp = runnables.clone();
@ -106,8 +104,7 @@ public class SetQueue {
* @param x * @param x
* @param y * @param y
* @param z * @param z
* @param id * @param block
* @param data
* @return * @return
*/ */
public boolean setBlock(final String world, final int x, final int y, final int z, PlotBlock block) { 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; 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.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer; 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.object.StringWrapper;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
public class UUIDHandler { public class UUIDHandler {
public static UUIDHandlerImplementation implementation; public static UUIDHandlerImplementation implementation;
@ -61,7 +61,7 @@ public class UUIDHandler {
public static HashSet<UUID> getAllUUIDS() { public static HashSet<UUID> getAllUUIDS() {
final HashSet<UUID> uuids = new HashSet<>(); final HashSet<UUID> uuids = new HashSet<>();
for (final Plot plot : PS.get().getPlots()) { for (final Plot plot : PS.get().getPlots()) {
if (plot.owner != null) { if (plot.hasOwner()) {
uuids.add(plot.owner); uuids.add(plot.owner);
uuids.addAll(plot.getTrusted()); uuids.addAll(plot.getTrusted());
uuids.addAll(plot.getMembers()); 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.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 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; import java.util.concurrent.ConcurrentHashMap;
public abstract class UUIDHandlerImplementation { 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 boolean CACHED = false;
public UUIDWrapper uuidWrapper = null; 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) { public UUIDHandlerImplementation(final UUIDWrapper wrapper) {
uuidWrapper = wrapper; uuidWrapper = wrapper;
@ -57,7 +67,7 @@ public abstract class UUIDHandlerImplementation {
} }
public void add(final BiMap<StringWrapper, UUID> toAdd) { public void add(final BiMap<StringWrapper, UUID> toAdd) {
if (uuidMap.size() == 0) { if (uuidMap.isEmpty()) {
uuidMap = toAdd; uuidMap = toAdd;
} }
for (final Map.Entry<StringWrapper, UUID> entry : toAdd.entrySet()) { 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"); 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) { public boolean add(final StringWrapper name, final UUID uuid) {
if ((uuid == null)) { if ((uuid == null)) {
return false; return false;
@ -99,7 +107,7 @@ public abstract class UUIDHandlerImplementation {
* lazy UUID conversion: * lazy UUID conversion:
* - Useful if the person misconfigured the database, or settings before PlotMe 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() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -113,7 +121,7 @@ public abstract class UUIDHandlerImplementation {
if (offline != null && !offline.equals(uuid)) { if (offline != null && !offline.equals(uuid)) {
unknown.remove(offline); unknown.remove(offline);
final Set<Plot> plots = PS.get().getPlotsAbs(offline); final Set<Plot> plots = PS.get().getPlotsAbs(offline);
if (plots.size() > 0) { if (!plots.isEmpty()) {
for (final Plot plot : plots) { for (final Plot plot : plots) {
plot.owner = uuid; plot.owner = uuid;
} }
@ -131,7 +139,7 @@ public abstract class UUIDHandlerImplementation {
if (offline != null) { if (offline != null) {
if (!offline.equals(uuid)) { if (!offline.equals(uuid)) {
final Set<Plot> plots = PS.get().getPlots(offline); final Set<Plot> plots = PS.get().getPlots(offline);
if (plots.size() > 0) { if (!plots.isEmpty()) {
for (final Plot plot : plots) { for (final Plot plot : plots) {
plot.owner = uuid; plot.owner = uuid;
} }
@ -194,7 +202,7 @@ public abstract class UUIDHandlerImplementation {
} }
public UUID getUUID(final String name, final RunnableVal<UUID> ifFetch) { public UUID getUUID(final String name, final RunnableVal<UUID> ifFetch) {
if ((name == null) || (name.length() == 0)) { if ((name == null) || (name.isEmpty())) {
return null; return null;
} }
// check online // check online

View File

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

View File

@ -13,7 +13,8 @@ public class HelpObject {
public HelpObject(final Command command, final String label) { public HelpObject(final Command command, final String label) {
_command = command; _command = command;
_rendered = StringMan.replaceAll(C.HELP_ITEM.s(), "%usage%", _command.getUsage().replaceAll("\\{label\\}", label), "[%alias%]", _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); buildArgumentList(_command.getRequiredArguments()), "{label}", label);
} }

View File

@ -1,28 +1,5 @@
package com.plotsquared.bukkit; package com.plotsquared.bukkit;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.IPlotMain; import com.intellectualcrafters.plot.IPlotMain;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -96,6 +73,30 @@ import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler; import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@ -115,11 +116,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (split.length == 3) { if (split.length == 3) {
version[2] = Integer.parseInt(split[2]); version[2] = Integer.parseInt(split[2]);
} }
} catch (final Exception e) { } catch (NumberFormatException e) {
e.printStackTrace(); e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion())); PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\."))); PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
return new int[] { Integer.MAX_VALUE, 0, 0 }; return new int[]{Integer.MAX_VALUE, 0, 0};
} }
} }
return version; return version;
@ -261,7 +262,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
continue; continue;
} }
List<MetadataValue> meta = entity.getMetadata("plot"); List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.size() == 0) { if (meta.isEmpty()) {
continue; continue;
} }
Plot origin = (Plot) meta.get(0).value(); Plot origin = (Plot) meta.get(0).value();
@ -322,13 +323,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (BukkitUtil.getLocation(loc).isPlotRoad()) { if (BukkitUtil.getLocation(loc).isPlotRoad()) {
final Entity passenger = entity.getPassenger(); final Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player)) { if (!(passenger instanceof Player)) {
if (entity.getMetadata("keep").size() == 0) { if (entity.getMetadata("keep").isEmpty()) {
iter.remove(); iter.remove();
entity.remove(); entity.remove();
} }
} }
} }
continue;
} }
} }
} }
@ -412,7 +412,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (econ.init()) { if (econ.init()) {
return econ; return econ;
} }
} catch (final Throwable e) {} } catch (final Throwable ignored) {
}
return null; return null;
} }
@ -428,11 +429,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
try { try {
return new FastQueue_1_8_3(); return new FastQueue_1_8_3();
} catch (final Throwable e) { } catch (NoSuchMethodException e) {
e.printStackTrace(); e.printStackTrace();
try { try {
return new FastQueue_1_8(); return new FastQueue_1_8();
} catch (Throwable e2) { } catch (NoSuchMethodException e2) {
e2.printStackTrace(); e2.printStackTrace();
return new SlowQueue(); return new SlowQueue();
} }
@ -440,7 +441,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} }
try { try {
return new FastQueue_1_7(); return new FastQueue_1_7();
} catch (final Throwable e) { } catch (NoSuchMethodException e) {
return new SlowQueue(); return new SlowQueue();
} }
} }
@ -524,9 +525,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
FlagManager.removeFlag(FlagManager.getFlag("titles")); FlagManager.removeFlag(FlagManager.getFlag("titles"));
} else { } else {
AbstractTitle.TITLE_CLASS = new DefaultTitle(); AbstractTitle.TITLE_CLASS = new DefaultTitle();
if (wrapper instanceof DefaultUUIDWrapper) { if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
Settings.TWIN_MODE_UUID = true;
} else if ((wrapper.getClass() == OfflineUUIDWrapper.class) && !Bukkit.getOnlineMode()) {
Settings.TWIN_MODE_UUID = true; Settings.TWIN_MODE_UUID = true;
} }
} }
@ -579,7 +578,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
final Metrics metrics = new Metrics(this); final Metrics metrics = new Metrics(this);
metrics.start(); metrics.start();
log(C.PREFIX.s() + "&6Metrics enabled."); log(C.PREFIX.s() + "&6Metrics enabled.");
} catch (final Exception e) { } catch (IOException e) {
log(C.PREFIX.s() + "&cFailed to load up metrics."); log(C.PREFIX.s() + "&cFailed to load up metrics.");
} }
} }
@ -667,8 +666,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
final Class<?> bukkitServerClass = server.getClass(); final Class<?> bukkitServerClass = server.getClass();
String[] pas = bukkitServerClass.getName().split("\\."); String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5) { if (pas.length == 5) {
final String verB = pas[3]; return pas[3];
return verB;
} }
try { try {
final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
@ -676,10 +674,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
final Class handleServerClass = handle.getClass(); final Class handleServerClass = handle.getClass();
pas = handleServerClass.getName().split("\\."); pas = handleServerClass.getName().split("\\.");
if (pas.length == 5) { if (pas.length == 5) {
final String verM = pas[3]; return pas[3];
return verM;
} }
} catch (final Exception e) { } catch (IllegalAccessException | InvocationTargetException | SecurityException | NoSuchMethodException | IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
} }
PS.debug("Unknown NMS package: " + StringMan.getString(pas)); PS.debug("Unknown NMS package: " + StringMan.getString(pas));

View File

@ -1,25 +1,55 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
/** /**
* Internal class: Represents a component of a JSON-serializable {@link FancyMessage}. * Internal class: Represents a component of a JSON-serializable {@link FancyMessage}.
*/ */
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable { final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
static final BiMap<ChatColor, String> stylesToNames;
static {
final ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (final ChatColor style : ChatColor.values()) {
if (!style.isFormat()) {
continue;
}
String styleName;
switch (style) {
case MAGIC:
styleName = "obfuscated";
break;
case UNDERLINE:
styleName = "underlined";
break;
default:
styleName = style.name().toLowerCase();
break;
}
builder.put(style, styleName);
}
stylesToNames = builder.build();
}
static {
ConfigurationSerialization.registerClass(MessagePart.class);
}
ChatColor color = ChatColor.WHITE; ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<ChatColor>(); ArrayList<ChatColor> styles = new ArrayList<ChatColor>();
String clickActionName = null, clickActionData = null, hoverActionName = null; String clickActionName = null, clickActionData = null, hoverActionName = null;
@ -35,7 +65,21 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
MessagePart() { MessagePart() {
text = null; text = null;
} }
@SuppressWarnings("unchecked")
public static MessagePart deserialize(final Map<String, Object> serialized) {
final MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String) serialized.get("hoverActionName");
part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
part.clickActionName = (String) serialized.get("clickActionName");
part.clickActionData = (String) serialized.get("clickActionData");
part.insertionData = (String) serialized.get("insertion");
part.translationReplacements = (ArrayList<JsonRepresentedObject>) serialized.get("translationReplacements");
return part;
}
boolean hasText() { boolean hasText() {
return text != null; return text != null;
} }
@ -52,34 +96,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
} }
obj.translationReplacements = (ArrayList<JsonRepresentedObject>) translationReplacements.clone(); obj.translationReplacements = (ArrayList<JsonRepresentedObject>) translationReplacements.clone();
return obj; return obj;
}
static final BiMap<ChatColor, String> stylesToNames;
static {
final ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (final ChatColor style : ChatColor.values()) {
if (!style.isFormat()) {
continue;
}
String styleName;
switch (style) {
case MAGIC:
styleName = "obfuscated";
break;
case UNDERLINE:
styleName = "underlined";
break;
default:
styleName = style.name().toLowerCase();
break;
}
builder.put(style, styleName);
}
stylesToNames = builder.build();
} }
@Override @Override
@ -102,7 +119,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
if (insertionData != null) { if (insertionData != null) {
json.name("insertion").value(insertionData); json.name("insertion").value(insertionData);
} }
if ((translationReplacements.size() > 0) && (text != null) && TextualComponent.isTranslatableText(text)) { if ((!translationReplacements.isEmpty()) && (text != null) && TextualComponent.isTranslatableText(text)) {
json.name("with").beginArray(); json.name("with").beginArray();
for (final JsonRepresentedObject obj : translationReplacements) { for (final JsonRepresentedObject obj : translationReplacements) {
obj.writeJson(json); obj.writeJson(json);
@ -130,22 +147,4 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
return map; return map;
} }
@SuppressWarnings("unchecked")
public static MessagePart deserialize(final Map<String, Object> serialized) {
final MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String) serialized.get("hoverActionName");
part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
part.clickActionName = (String) serialized.get("clickActionName");
part.clickActionData = (String) serialized.get("clickActionData");
part.insertionData = (String) serialized.get("insertion");
part.translationReplacements = (ArrayList<JsonRepresentedObject>) serialized.get("translationReplacements");
return part;
}
static {
ConfigurationSerialization.registerClass(MessagePart.class);
}
} }

View File

@ -1,23 +1,38 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import org.bukkit.Bukkit;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.bukkit.Bukkit;
/** /**
* A class containing static utility methods and caches which are intended as reflective conveniences. * A class containing static utility methods and caches which are intended as reflective conveniences.
* Unless otherwise noted, upon failure methods will return {@code null}. * Unless otherwise noted, upon failure methods will return {@code null}.
*/ */
public final class Reflection { public final class Reflection {
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
private static final Map<String, Class<?>> _loadedNMSClasses = new HashMap<>();
/**
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<>();
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<>();
/**
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<>();
private static String _versionString; private static String _versionString;
private Reflection() { private Reflection() {
} }
/** /**
@ -34,19 +49,10 @@ public final class Reflection {
final String name = Bukkit.getServer().getClass().getPackage().getName(); final String name = Bukkit.getServer().getClass().getPackage().getName();
_versionString = name.substring(name.lastIndexOf('.') + 1) + "."; _versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
} }
return _versionString; return _versionString;
} }
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
private static final Map<String, Class<?>> _loadedNMSClasses = new HashMap<String, Class<?>>();
/**
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<String, Class<?>>();
/** /**
* Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package. * Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously). * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
@ -57,12 +63,12 @@ public final class Reflection {
if (_loadedNMSClasses.containsKey(className)) { if (_loadedNMSClasses.containsKey(className)) {
return _loadedNMSClasses.get(className); return _loadedNMSClasses.get(className);
} }
final String fullName = "net.minecraft.server." + getVersion() + className; final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null; Class<?> clazz;
try { try {
clazz = Class.forName(fullName); clazz = Class.forName(fullName);
} catch (final Exception e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
_loadedNMSClasses.put(className, null); _loadedNMSClasses.put(className, null);
return null; return null;
@ -73,20 +79,22 @@ public final class Reflection {
/** /**
* Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package. * Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously). * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}. * method simultaneously).
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory
* .CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded. * @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/ */
public synchronized static Class<?> getOBCClass(final String className) { public synchronized static Class<?> getOBCClass(final String className) {
if (_loadedOBCClasses.containsKey(className)) { if (_loadedOBCClasses.containsKey(className)) {
return _loadedOBCClasses.get(className); return _loadedOBCClasses.get(className);
} }
final String fullName = "org.bukkit.craftbukkit." + getVersion() + className; final String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null; Class<?> clazz;
try { try {
clazz = Class.forName(fullName); clazz = Class.forName(fullName);
} catch (final Exception e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
_loadedOBCClasses.put(className, null); _loadedOBCClasses.put(className, null);
return null; return null;
@ -98,7 +106,8 @@ public final class Reflection {
/** /**
* Attempts to get the NMS handle of a CraftBukkit object. * Attempts to get the NMS handle of a CraftBukkit object.
* <p> * <p>
* The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the runtime type of the specified object. * The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the
* runtime type of the specified object.
* </p> * </p>
* @param obj The object for which to retrieve an NMS handle. * @param obj The object for which to retrieve an NMS handle.
* @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}. * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
@ -106,14 +115,18 @@ public final class Reflection {
public synchronized static Object getHandle(final Object obj) { public synchronized static Object getHandle(final Object obj) {
try { try {
return getMethod(obj.getClass(), "getHandle").invoke(obj); return getMethod(obj.getClass(), "getHandle").invoke(obj);
} catch (final Exception e) { } catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<Class<?>, Map<String, Field>>();
/** /**
* Retrieves a {@link Field} instance declared by the specified class with the specified name. * Retrieves a {@link Field} instance declared by the specified class with the specified name.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
@ -123,7 +136,8 @@ public final class Reflection {
* no field will be reflectively looked up twice. * no field will be reflectively looked up twice.
* </p> * </p>
* <p> * <p>
* If a field is deemed suitable for return, {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned. * If a field is deemed suitable for return,
* {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance. * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p> * </p>
* @param clazz The class which contains the field to retrieve. * @param clazz The class which contains the field to retrieve.
@ -134,7 +148,7 @@ public final class Reflection {
public synchronized static Field getField(final Class<?> clazz, final String name) { public synchronized static Field getField(final Class<?> clazz, final String name) {
Map<String, Field> loaded; Map<String, Field> loaded;
if (!_loadedFields.containsKey(clazz)) { if (!_loadedFields.containsKey(clazz)) {
loaded = new HashMap<String, Field>(); loaded = new HashMap<>();
_loadedFields.put(clazz, loaded); _loadedFields.put(clazz, loaded);
} else { } else {
loaded = _loadedFields.get(clazz); loaded = _loadedFields.get(clazz);
@ -148,7 +162,13 @@ public final class Reflection {
field.setAccessible(true); field.setAccessible(true);
loaded.put(name, field); loaded.put(name, field);
return field; return field;
} catch (final Exception e) { } catch (NoSuchFieldException e) {
// Error loading
e.printStackTrace();
// Cache field as not existing
loaded.put(name, null);
return null;
} catch (SecurityException e) {
// Error loading // Error loading
e.printStackTrace(); e.printStackTrace();
// Cache field as not existing // Cache field as not existing
@ -157,12 +177,6 @@ public final class Reflection {
} }
} }
/**
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>>();
/** /**
* Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types. * Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
@ -194,7 +208,7 @@ public final class Reflection {
} }
final Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name); final Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
final ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<Class<?>>(args); final ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args);
if (loadedSignatures.containsKey(wrappedArg)) { if (loadedSignatures.containsKey(wrappedArg)) {
return loadedSignatures.get(wrappedArg); return loadedSignatures.get(wrappedArg);
} }

View File

@ -1,15 +1,15 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/** /**
* Represents a textual component of a message part. * Represents a textual component of a message part.
* This can be used to not only represent string literals in a JSON message, * This can be used to not only represent string literals in a JSON message,
@ -23,41 +23,21 @@ public abstract class TextualComponent implements Cloneable {
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class); ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
} }
@Override
public String toString() {
return getReadableString();
}
/**
* @return The JSON key used to represent text components of this type.
*/
public abstract String getKey();
/**
* @return A readable String
*/
public abstract String getReadableString();
/**
* Clones a textual component instance.
* The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
* A new object within the writer is not started.
* @param writer The object to which to write the JSON data.
* @throws IOException If an error occurs while writing to the stream.
*/
public abstract void writeJson(final JsonWriter writer) throws IOException;
static TextualComponent deserialize(final Map<String, Object> map) { static TextualComponent deserialize(final Map<String, Object> map) {
if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) { if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
// Arbitrary text component // Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map); return ArbitraryTextTypeComponent.deserialize(map);
} else if ((map.size() >= 2) && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) { } else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
// Complex JSON object // Complex JSON object
return ComplexTextTypeComponent.deserialize(map); return ComplexTextTypeComponent.deserialize(map);
} }
@ -66,161 +46,27 @@ public abstract class TextualComponent implements Cloneable {
} }
static boolean isTextKey(final String key) { static boolean isTextKey(final String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); return "translate".equals(key) || "text".equals(key) || "score".equals(key) || "selector".equals(key);
} }
static boolean isTranslatableText(final TextualComponent component) { static boolean isTranslatableText(final TextualComponent component) {
return (component instanceof ComplexTextTypeComponent) && ((ComplexTextTypeComponent) component).getKey().equals("translate"); return component instanceof ComplexTextTypeComponent && "translate".equals(component.getKey());
} }
/** /**
* Internal class used to represent all types of text components.
* Exception validating done is on keys and values. @Override public String toString() {
return getReadableString();
}te a t
/**
* @return The JSON key used to represent text components of this type.
*/ */
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable { public abstract String getKey();
public ArbitraryTextTypeComponent(final String key, final String value) { extual component
setKey(key); representing a
setValue(value); string literal
} .
@Override
public String getKey() {
return _key;
}
public void setKey(final String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public String getValue() {
return _value;
}
public void setValue(final String value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
private String _key;
private String _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException {
writer.name(getKey()).value(getValue());
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new HashMap<String, Object>() {
{
put("key", getKey());
put("value", getValue());
}
};
}
public static ArbitraryTextTypeComponent deserialize(final Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
@Override
public String getReadableString() {
return getValue();
}
}
/**
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
public ComplexTextTypeComponent(final String key, final Map<String, String> values) {
setKey(key);
setValue(values);
}
@Override
public String getKey() {
return _key;
}
public void setKey(final String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public Map<String, String> getValue() {
return _value;
}
public void setValue(final Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
private String _key;
private Map<String, String> _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for (final Map.Entry<String, String> jsonPair : _value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>() {
{
put("key", getKey());
for (final Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue());
}
}
};
}
public static ComplexTextTypeComponent deserialize(final Map<String, Object> map) {
String key = null;
final Map<String, String> value = new HashMap<String, String>();
for (final Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getReadableString() {
return getKey();
}
}
/**
* Create a textual component representing a string literal.
* This is the default type of textual component when a single string literal is given to a method. * This is the default type of textual component when a single string literal is given to a method.
* @param textValue The text which will be represented. * @param textValue The text which will be represented.
* @return The text component representing the specified literal text. * @return The text component representing the specified literal text.
@ -230,7 +76,16 @@ public abstract class TextualComponent implements Cloneable {
} }
/** /**
* Create a textual component representing a localized string. * Create a t
/**
* @return A readable String
*/
public abstract String getReadableString();
extual component
representing a
localized string
.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack. * The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack.
* <p> * <p>
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client. * If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client.
@ -241,13 +96,34 @@ public abstract class TextualComponent implements Cloneable {
public static TextualComponent localizedText(final String translateKey) { public static TextualComponent localizedText(final String translateKey) {
return new ArbitraryTextTypeComponent("translate", translateKey); return new ArbitraryTextTypeComponent("translate", translateKey);
} }
private static void throwUnsupportedSnapshot() { private static void t
/**
* Clones a textual component instance.
* The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
hrowUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
} }
/** /**
* Create a textual component representing a scoreboard value. * Create a t
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
* A new object within the writer is not started.
* @param writer The object to which to write the JSON data.
* @throws IOException If an error occurs while writing to the stream.
*/
public abstract void writeJson(final JsonWriter writer) throws IOException;
extual component
representing a
scoreboard value
.
* The client will see their own score for the specified objective as the text represented by this component. * The client will see their own score for the specified objective as the text represented by this component.
* <p> * <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b> * <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
@ -260,7 +136,76 @@ public abstract class TextualComponent implements Cloneable {
} }
/** /**
* Create a textual component representing a scoreboard value. * Create a t
/**
* Internal class used to represent all types of text components.
* Exception validating done is on keys and values.
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private String _key;
private String _value;
public ArbitraryTextTypeComponent(final String key, final String value) {
setKey(key);
setValue(value);
}
public static ArbitraryTextTypeComponent deserialize(final Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
@Override
public String getKey() {
return _key;
}
public void setKey(final String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public String getValue() {
return _value;
}
public void setValue(final String value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
@Override
public TextualComponent clone() {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException {
writer.name(getKey()).value(getValue());
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new HashMap<String, Object>() {
{
put("key", getKey());
put("value", getValue());
}
};
}
@Override
public String getReadableString() {
return getValue();
}
}
extual component
representing a
scoreboard value
.
* The client will see the score of the specified player for the specified objective as the text represented by this component. * The client will see the score of the specified player for the specified objective as the text represented by this component.
* <p> * <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b> * <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
@ -271,13 +216,97 @@ public abstract class TextualComponent implements Cloneable {
* @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization. * @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization.
*/ */
public static TextualComponent objectiveScore(final String playerName, final String scoreboardObjective) { public static TextualComponent objectiveScore(final String playerName, final String scoreboardObjective) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
// OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String> builder().put("name", playerName).put("objective", scoreboardObjective).build());
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder().put("name", playerName).put("objective",
scoreboardObjective).build());
} }
/** /**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector. * Create a t
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private private String _key;
Map<String, String> _value;
public ComplexTextTypeComponent(final String key, final Map<String, String> values) {
setKey(key);
setValue(values);
}
public static ComplexTextTypeComponent deserialize(final Map<String, Object> map) {
String key = null;
final Map<String, String> value = new HashMap<String, String>();
for (final Map.Entry<String, Object> valEntry : map.entrySet()) {
if ("key".equals(valEntry.getKey())) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getKey() {
return _key;
}
public void setKey(final String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public Map<String, String> getValue() {
return _value;
}
public void setValue(final Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
@Override
public TextualComponent clone() {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for (final Map.Entry<String, String> jsonPair : _value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>() {
{
put("key", getKey());
for (final Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue());
}
}
};
}
@Override
public String getReadableString() {
return getKey();
}
}
/**
* Creaextual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector as the text represented by this component. * The client will see the players or entities captured by the specified selector as the text represented by this component.
* <p> * <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b> * <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>

View File

@ -74,30 +74,26 @@ public class DebugUUID extends SubCommand {
final UUIDWrapper newWrapper; final UUIDWrapper newWrapper;
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "lower": { case "lower":
newWrapper = new LowerOfflineUUIDWrapper(); newWrapper = new LowerOfflineUUIDWrapper();
break; break;
} case "offline":
case "offline": {
newWrapper = new OfflineUUIDWrapper(); newWrapper = new OfflineUUIDWrapper();
break; break;
} case "online":
case "online": {
newWrapper = new DefaultUUIDWrapper(); newWrapper = new DefaultUUIDWrapper();
break; break;
} default:
default: {
try { try {
final Class<?> clazz = Class.forName(args[0]); final Class<?> clazz = Class.forName(args[0]);
newWrapper = (UUIDWrapper) clazz.newInstance(); newWrapper = (UUIDWrapper) clazz.newInstance();
} catch (final Exception e) { } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>"); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>");
return false; return false;
} }
}
} }
if ((args.length != 2) || !args[1].equals("-o")) { if (args.length != 2 || !"-o".equals(args[1])) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o"); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o");
MainUtil.sendMessage(player, "&cBe aware of the following!"); MainUtil.sendMessage(player, "&cBe aware of the following!");
MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand"); MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand");
@ -120,9 +116,9 @@ public class DebugUUID extends SubCommand {
} }
MainUtil.sendMessage(player, "&7 - Initializing map"); MainUtil.sendMessage(player, "&7 - Initializing map");
final HashMap<UUID, UUID> uCMap = new HashMap<UUID, UUID>(); final HashMap<UUID, UUID> uCMap = new HashMap<>();
final HashMap<UUID, UUID> uCReverse = new HashMap<UUID, UUID>(); final HashMap<UUID, UUID> uCReverse = new HashMap<>();
MainUtil.sendMessage(player, "&7 - Collecting playerdata"); MainUtil.sendMessage(player, "&7 - Collecting playerdata");
@ -187,7 +183,7 @@ public class DebugUUID extends SubCommand {
uCReverse.put(uuid2, uuid); uCReverse.put(uuid2, uuid);
} }
} }
if (uCMap.size() == 0) { if (uCMap.isEmpty()) {
MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate"); MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate");
for (final OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) { for (final OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) {
if (op.getLastPlayed() != 0) { if (op.getLastPlayed() != 0) {
@ -201,7 +197,7 @@ public class DebugUUID extends SubCommand {
} }
} }
} }
if (uCMap.size() == 0) { if (uCMap.isEmpty()) {
MainUtil.sendMessage(player, "&cError. Failed to collect UUIDs!"); MainUtil.sendMessage(player, "&cError. Failed to collect UUIDs!");
return false; return false;
} else { } else {
@ -229,13 +225,13 @@ public class DebugUUID extends SubCommand {
for (String line : lines) { for (String line : lines) {
try { try {
line = line.trim(); line = line.trim();
if (line.length() == 0) { if (line.isEmpty()) {
continue; continue;
} }
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
final String[] split = line.split("\\|"); final String[] split = line.split("\\|");
final String name = split[0]; final String name = split[0];
if ((name.length() == 0) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) { if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) {
continue; continue;
} }
final UUID old = currentUUIDWrapper.getUUID(name); final UUID old = currentUUIDWrapper.getUUID(name);
@ -302,16 +298,13 @@ public class DebugUUID extends SubCommand {
if (newWrapper instanceof OfflineUUIDWrapper) { if (newWrapper instanceof OfflineUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", true); PS.get().config.set("UUID.offline", true);
} else if (newWrapper instanceof LowerOfflineUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", true);
PS.get().config.set("UUID.offline", true);
} else if (newWrapper instanceof DefaultUUIDWrapper) { } else if (newWrapper instanceof DefaultUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", false); PS.get().config.set("UUID.offline", false);
} }
try { try {
PS.get().config.save(PS.get().configFile); PS.get().config.save(PS.get().configFile);
} catch (final Exception e) { } catch (IOException e) {
MainUtil.sendMessage(player, "Could not save configuration. It will need to be manuall set!"); MainUtil.sendMessage(player, "Could not save configuration. It will need to be manuall set!");
} }

View File

@ -1,16 +1,5 @@
package com.plotsquared.bukkit.database.plotme; package com.plotsquared.bukkit.database.plotme;
import java.io.File;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.intellectualcrafters.configuration.file.FileConfiguration; import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -24,6 +13,17 @@ import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import java.io.File;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
public class ClassicPlotMeConnector extends APlotMeConnector { public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin; private String plugin;
@ -46,20 +46,19 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} else { } else {
return new SQLite(dataFolder + File.separator + "plots.db").openConnection(); return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
} }
} catch (SQLException | ClassNotFoundException e) {} } catch (SQLException | ClassNotFoundException ignored) {
}
return null; return null;
} }
@Override @Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException { public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException {
ResultSet r;
PreparedStatement stmt;
final HashMap<String, Integer> plotWidth = new HashMap<>(); final HashMap<String, Integer> plotWidth = new HashMap<>();
final HashMap<String, Integer> roadWidth = new HashMap<>(); final HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<String, HashMap<PlotId, Plot>> plots = new HashMap<>(); final HashMap<String, HashMap<PlotId, Plot>> plots = new HashMap<>();
final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>(); final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
stmt = connection.prepareStatement("SELECT * FROM `" + prefix + "Plots`"); PreparedStatement stmt = connection.prepareStatement("SELECT * FROM `" + prefix + "Plots`");
r = stmt.executeQuery(); ResultSet r = stmt.executeQuery();
String column = null; String column = null;
final boolean checkUUID = DBFunc.hasColumn(r, "ownerid"); final boolean checkUUID = DBFunc.hasColumn(r, "ownerid");
final boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId"); final boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId");
@ -68,7 +67,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} else if (checkUUID2) { } else if (checkUUID2) {
column = "ownerId"; column = "ownerId";
} }
final boolean merge = !plugin.equalsIgnoreCase("plotme") && Settings.CONVERT_PLOTME; final boolean merge = !"plotme".equalsIgnoreCase(plugin) && Settings.CONVERT_PLOTME;
int missing = 0; int missing = 0;
while (r.next()) { while (r.next()) {
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ")); final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
@ -108,7 +107,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} }
UUID owner = UUIDHandler.getUUID(name, null); UUID owner = UUIDHandler.getUUID(name, null);
if (owner == null) { if (owner == null) {
if (name.equals("*")) { if ("*".equals(name)) {
owner = DBFunc.everyone; owner = DBFunc.everyone;
} else { } else {
if (checkUUID || checkUUID2) { if (checkUUID || checkUUID2) {
@ -126,12 +125,12 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} }
UUIDHandler.add(new StringWrapper(name), owner); UUIDHandler.add(new StringWrapper(name), owner);
} }
} catch (final Exception e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (owner == null) { if (owner == null) {
if (name.length() > 0) { if (!name.isEmpty()) {
owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
} }
PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + "'"); PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
@ -178,7 +177,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
final String world = LikePlotMeConverter.getWorld(r.getString("world")); final String world = LikePlotMeConverter.getWorld(r.getString("world"));
UUID denied = UUIDHandler.getUUID(name, null); UUID denied = UUIDHandler.getUUID(name, null);
if (denied == null) { if (denied == null) {
if (name.equals("*")) { if ("*".equals(name)) {
denied = DBFunc.everyone; denied = DBFunc.everyone;
} else { } else {
if (DBFunc.hasColumn(r, "playerid")) { if (DBFunc.hasColumn(r, "playerid")) {
@ -196,7 +195,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} }
UUIDHandler.add(new StringWrapper(name), denied); UUIDHandler.add(new StringWrapper(name), denied);
} }
} catch (final Exception e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -220,7 +219,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
final String world = LikePlotMeConverter.getWorld(r.getString("world")); final String world = LikePlotMeConverter.getWorld(r.getString("world"));
UUID helper = UUIDHandler.getUUID(name, null); UUID helper = UUIDHandler.getUUID(name, null);
if (helper == null) { if (helper == null) {
if (name.equals("*")) { if ("*".equals(name)) {
helper = DBFunc.everyone; helper = DBFunc.everyone;
} else { } else {
if (DBFunc.hasColumn(r, "playerid")) { if (DBFunc.hasColumn(r, "playerid")) {
@ -238,7 +237,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} }
UUIDHandler.add(new StringWrapper(name), helper); UUIDHandler.add(new StringWrapper(name), helper);
} }
} catch (final Exception e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -263,9 +262,6 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
@Override @Override
public boolean accepts(final String version) { public boolean accepts(final String version) {
if (version == null) { return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version);
return true;
}
return PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version);
} }
} }

View File

@ -20,17 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.generator; package com.plotsquared.bukkit.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.GeneratorWrapper; import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen; import com.intellectualcrafters.plot.generator.HybridGen;
@ -47,18 +36,27 @@ import com.intellectualcrafters.plot.util.SetQueue;
import com.plotsquared.bukkit.listeners.WorldEvents; import com.plotsquared.bukkit.listeners.WorldEvents;
import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk; import com.plotsquared.bukkit.util.block.GenChunk;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> { public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
private boolean loaded = false;
private final PlotChunk<Chunk> chunkSetter; private final PlotChunk<Chunk> chunkSetter;
private final PseudoRandom random = new PseudoRandom(); private final PseudoRandom random = new PseudoRandom();
private PlotManager manager;
private final IndependentPlotGenerator plotGenerator; private final IndependentPlotGenerator plotGenerator;
private final List<BlockPopulator> populators = new ArrayList<>();
private boolean loaded = false;
private PlotManager manager;
private ChunkGenerator platformGenerator; private ChunkGenerator platformGenerator;
private boolean full; private boolean full;
private final List<BlockPopulator> populators = new ArrayList<>();
public BukkitPlotGenerator(final String world, IndependentPlotGenerator generator) { public BukkitPlotGenerator(final String world, IndependentPlotGenerator generator) {
WorldEvents.lastWorld = world; WorldEvents.lastWorld = world;
@ -211,7 +209,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
final String name = WorldEvents.getName(world); final String name = WorldEvents.getName(world);
PS.get().loadWorld(name, this); PS.get().loadWorld(name, this);
Set<PlotArea> areas = PS.get().getPlotAreas(name); Set<PlotArea> areas = PS.get().getPlotAreas(name);
if (areas.size() != 0) { if (!areas.isEmpty()) {
PlotArea area = areas.iterator().next(); PlotArea area = areas.iterator().next();
if (!area.MOB_SPAWNING) { if (!area.MOB_SPAWNING) {
if (!area.SPAWN_EGGS) { if (!area.SPAWN_EGGS) {

View File

@ -2,10 +2,17 @@ package com.plotsquared.bukkit.listeners;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.ArrayDeque; import com.intellectualcrafters.plot.PS;
import java.util.HashMap; import com.intellectualcrafters.plot.config.Settings;
import java.util.Map.Entry; import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Material; import org.bukkit.Material;
@ -24,26 +31,17 @@ import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.ChunkUnloadEvent;
import com.intellectualcrafters.plot.PS; import java.util.ArrayDeque;
import com.intellectualcrafters.plot.config.Settings; import java.util.HashMap;
import com.intellectualcrafters.plot.object.ChunkLoc; import java.util.Map.Entry;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
public class ChunkListener implements Listener { public class ChunkListener implements Listener {
private Chunk lastChunk = null;
private final RefClass classChunk = getRefClass("{nms}.Chunk"); private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
private RefMethod methodGetHandleChunk;
private final RefField mustSave = classChunk.getField("mustSave"); private final RefField mustSave = classChunk.getField("mustSave");
private Chunk lastChunk = null;
private RefMethod methodGetHandleChunk;
public ChunkListener() { public ChunkListener() {
@ -62,7 +60,6 @@ public class ChunkListener implements Listener {
TaskManager.runTask(new Runnable() { TaskManager.runTask(new Runnable() {
@Override @Override
public void run() { public void run() {
int time = 300;
final int distance = Bukkit.getViewDistance() + 2; final int distance = Bukkit.getViewDistance() + 2;
final HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>(); final HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>();
for (final Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) { for (final Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
@ -90,23 +87,24 @@ public class ChunkListener implements Listener {
map.put(origin, distance); map.put(origin, distance);
} }
for (int x = -distance; x <= distance; x++) { for (int x = -distance; x <= distance; x++) {
if ((x >= check) || (-x >= check)) { if (x >= check || -x >= check) {
continue; continue;
} }
for (int z = -distance; z <= distance; z++) { for (int z = -distance; z <= distance; z++) {
if ((z >= check) || (-z >= check)) { if (z >= check || -z >= check) {
continue; continue;
} }
final int weight = distance - Math.max(Math.abs(x), Math.abs(z)); final int weight = distance - Math.max(Math.abs(x), Math.abs(z));
final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z); final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z);
val = map.get(chunk); val = map.get(chunk);
if ((val == null) || (val < weight)) { if (val == null || val < weight) {
map.put(chunk, weight); map.put(chunk, weight);
} }
} }
} }
} }
int time = 300;
for (final World world : Bukkit.getWorlds()) { for (final World world : Bukkit.getWorlds()) {
final String name = world.getName(); final String name = world.getName();
if (!PS.get().hasPlotArea(name)) { if (!PS.get().hasPlotArea(name)) {
@ -117,11 +115,11 @@ public class ChunkListener implements Listener {
world.setAutoSave(false); world.setAutoSave(false);
} }
final HashMap<ChunkLoc, Integer> map = players.get(name); final HashMap<ChunkLoc, Integer> map = players.get(name);
if ((map == null) || (map.size() == 0)) { if (map == null || map.isEmpty()) {
continue; continue;
} }
Chunk[] chunks = world.getLoadedChunks(); Chunk[] chunks = world.getLoadedChunks();
ArrayDeque<Chunk> toUnload = new ArrayDeque<Chunk>(); ArrayDeque<Chunk> toUnload = new ArrayDeque<>();
for (final Chunk chunk : chunks) { for (final Chunk chunk : chunks) {
final int x = chunk.getX(); final int x = chunk.getX();
final int z = chunk.getZ(); final int z = chunk.getZ();
@ -129,17 +127,17 @@ public class ChunkListener implements Listener {
toUnload.add(chunk); toUnload.add(chunk);
} }
} }
if (toUnload.size() > 0) { if (!toUnload.isEmpty()) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Chunk chunk; Chunk chunk;
while ((chunk = toUnload.poll()) != null && (System.currentTimeMillis() - start < 5)) { while ((chunk = toUnload.poll()) != null && System.currentTimeMillis() - start < 5) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk)) { if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk)) {
if (chunk.isLoaded()) { if (chunk.isLoaded()) {
chunk.unload(true, false); chunk.unload(true, false);
} }
} }
} }
if (toUnload.size() > 0) { if (!toUnload.isEmpty()) {
time = 1; time = 1;
} }
} }
@ -159,26 +157,25 @@ public class ChunkListener implements Listener {
final int z = Z << 4; final int z = Z << 4;
final int x2 = x + 15; final int x2 = x + 15;
final int z2 = z + 15; final int z2 = z + 15;
Plot plot;
Thread thread = new Thread(); Thread thread = new Thread();
plot = new Location(world, x, 1, z).getOwnedPlotAbs(); Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
if ((plot != null) && (plot.owner != null)) { if (plot != null && plot.hasOwner()) {
return false; return false;
} }
plot = new Location(world, x2, 1, z2).getOwnedPlotAbs(); plot = new Location(world, x2, 1, z2).getOwnedPlotAbs();
if ((plot != null) && (plot.owner != null)) { if (plot != null && plot.hasOwner()) {
return false; return false;
} }
plot = new Location(world, x2, 1, z).getOwnedPlotAbs(); plot = new Location(world, x2, 1, z).getOwnedPlotAbs();
if ((plot != null) && (plot.owner != null)) { if (plot != null && plot.hasOwner()) {
return false; return false;
} }
plot = new Location(world, x, 1, z2).getOwnedPlotAbs(); plot = new Location(world, x, 1, z2).getOwnedPlotAbs();
if ((plot != null) && (plot.owner != null)) { if (plot != null && plot.hasOwner()) {
return false; return false;
} }
plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs(); plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs();
if ((plot != null) && (plot.owner != null)) { if (plot != null && plot.hasOwner()) {
return false; return false;
} }
final Object c = methodGetHandleChunk.of(chunk).call(); final Object c = methodGetHandleChunk.of(chunk).call();
@ -284,7 +281,7 @@ public class ChunkListener implements Listener {
} }
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
int i = 0; int i = 0;
while ((System.currentTimeMillis() - start) < 250) { while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) { if (i >= tiles.length) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex); TaskManager.tasks.remove(currentIndex);

View File

@ -1,16 +1,33 @@
package com.plotsquared.bukkit.listeners; package com.plotsquared.bukkit.listeners;
import java.util.ArrayList; import com.intellectualcrafters.plot.PS;
import java.util.Arrays; import com.intellectualcrafters.plot.config.C;
import java.util.HashSet; import com.intellectualcrafters.plot.config.Settings;
import java.util.Iterator; import com.intellectualcrafters.plot.flag.Flag;
import java.util.List; import com.intellectualcrafters.plot.flag.FlagManager;
import java.util.Map.Entry; import com.intellectualcrafters.plot.object.Location;
import java.util.Objects; import com.intellectualcrafters.plot.object.Plot;
import java.util.Set; import com.intellectualcrafters.plot.object.PlotArea;
import java.util.UUID; import com.intellectualcrafters.plot.object.PlotBlock;
import java.util.regex.Pattern; import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotInventory;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.ExpireManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.RegExUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.BukkitMain;
import com.plotsquared.bukkit.object.BukkitLazyBlock;
import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlayerBlockEventType;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
@ -89,34 +106,16 @@ import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import com.intellectualcrafters.plot.PS; import java.util.ArrayList;
import com.intellectualcrafters.plot.config.C; import java.util.Arrays;
import com.intellectualcrafters.plot.config.Settings; import java.util.HashSet;
import com.intellectualcrafters.plot.flag.Flag; import java.util.Iterator;
import com.intellectualcrafters.plot.flag.FlagManager; import java.util.List;
import com.intellectualcrafters.plot.object.Location; import java.util.Map.Entry;
import com.intellectualcrafters.plot.object.Plot; import java.util.Objects;
import com.intellectualcrafters.plot.object.PlotArea; import java.util.Set;
import com.intellectualcrafters.plot.object.PlotBlock; import java.util.UUID;
import com.intellectualcrafters.plot.object.PlotHandler; import java.util.regex.Pattern;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotInventory;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.ExpireManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.RegExUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.BukkitMain;
import com.plotsquared.bukkit.object.BukkitLazyBlock;
import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlayerBlockEventType;
/** /**
* Player Events involving plots * Player Events involving plots
@ -126,6 +125,9 @@ import com.plotsquared.listener.PlayerBlockEventType;
public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener { public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener {
private boolean pistonBlocks = true; private boolean pistonBlocks = true;
private float lastRadius;
// To prevent recursion
private boolean tmp_teleport = true;
public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) { public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) {
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(new Runnable() {
@ -139,10 +141,10 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
PlotPlayer player = entry.getValue(); PlotPlayer player = entry.getValue();
final Location loc = player.getLocation(); final Location loc = player.getLocation();
if (loc.getWorld().equals(world)) { if (loc.getWorld().equals(world)) {
if ((16 * (Math.abs(loc.getX() - x) / 16)) > distance) { if (16 * Math.abs(loc.getX() - x) / 16 > distance) {
continue; continue;
} }
if ((16 * (Math.abs(loc.getZ() - z) / 16)) > distance) { if (16 * Math.abs(loc.getZ() - z) / 16 > distance) {
continue; continue;
} }
((BukkitPlayer) player).player.sendBlockChange(bloc, type, data); ((BukkitPlayer) player).player.sendBlockChange(bloc, type, data);
@ -182,10 +184,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case JUNGLE_FENCE_GATE: case JUNGLE_FENCE_GATE:
case ACACIA_FENCE_GATE: case ACACIA_FENCE_GATE:
case DARK_OAK_FENCE_GATE: case DARK_OAK_FENCE_GATE:
case POWERED_RAIL: { case POWERED_RAIL:
return; return;
} default:
default: {
final Location loc = BukkitUtil.getLocation(block.getLocation()); final Location loc = BukkitUtil.getLocation(block.getLocation());
PlotArea area = loc.getPlotArea(); PlotArea area = loc.getPlotArea();
if (area == null) { if (area == null) {
@ -227,7 +228,6 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} }
event.setNewCurrent(0); event.setNewCurrent(0);
} }
}
} }
} }
@ -254,7 +254,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case 122: case 122:
case 145: case 145:
case 12: case 12:
case 13: { case 13:
final Block block = event.getBlock(); final Block block = event.getBlock();
final Location loc = BukkitUtil.getLocation(block.getLocation()); final Location loc = BukkitUtil.getLocation(block.getLocation());
PlotArea area = loc.getPlotArea(); PlotArea area = loc.getPlotArea();
@ -262,15 +262,13 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return; return;
} }
final Plot plot = area.getOwnedPlotAbs(loc); final Plot plot = area.getOwnedPlotAbs(loc);
if ((plot != null) && FlagManager.isPlotFlagTrue(plot, "disable-physics")) { if (plot != null && FlagManager.isPlotFlagTrue(plot, "disable-physics")) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
return; return;
} default:
default: {
break; break;
}
} }
} }
@ -286,9 +284,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return; return;
} }
Plot plot = area.getPlotAbs(loc); Plot plot = area.getPlotAbs(loc);
// //
final ProjectileSource shooter = entity.getShooter(); final ProjectileSource shooter = entity.getShooter();
if ((shooter instanceof Player)) { if (shooter instanceof Player) {
final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter);
if (plot == null) { if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) {
@ -314,7 +312,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return; return;
} }
final Plot sPlot = area.getOwnedPlotAbs(sLoc); final Plot sPlot = area.getOwnedPlotAbs(sLoc);
if ((sPlot == null) || !PlotHandler.sameOwners(plot, sPlot)) { if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) {
entity.remove(); entity.remove();
} }
} }
@ -323,7 +321,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void PlayerCommand(final PlayerCommandPreprocessEvent event) { public void PlayerCommand(final PlayerCommandPreprocessEvent event) {
String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim();
if (msg.length() == 0) { if (msg.isEmpty()) {
return; return;
} }
final String[] split = msg.split(" "); final String[] split = msg.split(" ");
@ -388,7 +386,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
for (final String s : v) { for (final String s : v) {
Pattern pattern; Pattern pattern;
if (!RegExUtil.compiledPatterns.containsKey(s)) { if (!RegExUtil.compiledPatterns.containsKey(s)) {
RegExUtil.compiledPatterns.put(s, ((pattern = Pattern.compile(s)))); RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s));
} else { } else {
pattern = RegExUtil.compiledPatterns.get(s); pattern = RegExUtil.compiledPatterns.get(s);
} }
@ -418,7 +416,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
StringWrapper sw = new StringWrapper(name); StringWrapper sw = new StringWrapper(name);
final UUID uuid = pp.getUUID(); final UUID uuid = pp.getUUID();
UUIDHandler.add(sw, uuid); UUIDHandler.add(sw, uuid);
Location loc = pp.getLocation(); Location loc = pp.getLocation();
PlotArea area = loc.getPlotArea(); PlotArea area = loc.getPlotArea();
final Plot plot; final Plot plot;
@ -431,9 +429,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
plot = null; plot = null;
} }
// Delayed // Delayed
{
}
// Async // Async
TaskManager.runTaskLaterAsync(new Runnable() { TaskManager.runTaskLaterAsync(new Runnable() {
@Override @Override
@ -447,7 +443,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASSED); MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASSED);
} }
} }
if ((PS.get().update != null) && Permissions.hasPermission(pp, C.PERMISSION_ADMIN_UPDATE) && Settings.UPDATE_NOTIFICATIONS) { if (PS.get().update != null && Permissions.hasPermission(pp, C.PERMISSION_ADMIN_UPDATE) && Settings.UPDATE_NOTIFICATIONS) {
MainUtil.sendMessage(pp, "&6An update for PlotSquared is available: &7/plot update"); MainUtil.sendMessage(pp, "&6An update for PlotSquared is available: &7/plot update");
} }
if (Settings.TELEPORT_ON_LOGIN && plot != null) { if (Settings.TELEPORT_ON_LOGIN && plot != null) {
@ -471,7 +467,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player); final PlotPlayer pp = BukkitUtil.getPlayer(player);
// Cancel teleport // Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName()); TaskManager.TELEPORT_QUEUE.remove(pp.getName());
@ -486,9 +482,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
Plot now = area.getPlotAbs(loc); Plot now = area.getPlotAbs(loc);
final Plot lastPlot = pp.getMeta("lastplot"); final Plot lastPlot = pp.getMeta("lastplot");
if (now == null) { if (now == null) {
if ((lastPlot != null) && !plotExit(pp, lastPlot)) { if (lastPlot != null && !plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals((BukkitUtil.getLocation(from).getPlot()))) { if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) {
player.teleport(from); player.teleport(from);
} else { } else {
player.teleport(player.getWorld().getSpawnLocation()); player.teleport(player.getWorld().getSpawnLocation());
@ -496,7 +492,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} else if ((lastPlot != null) && now.equals(lastPlot)) { } else if (lastPlot != null && now.equals(lastPlot)) {
return; return;
} else { } else {
if (!plotEntry(pp, now)) { if (!plotEntry(pp, now)) {
@ -528,14 +524,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player); final PlotPlayer pp = BukkitUtil.getPlayer(player);
// Cancel teleport // Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName()); TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location // Set last location
Location loc = BukkitUtil.getLocation(to); Location loc = BukkitUtil.getLocation(to);
pp.setMeta("location", loc); pp.setMeta("location", loc);
PlotArea area = loc.getPlotArea(); PlotArea area = loc.getPlotArea();
if (area == null) { if (area == null) {
pp.deleteMeta("lastplot"); pp.deleteMeta("lastplot");
@ -544,9 +540,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
Plot now = area.getPlotAbs(loc); Plot now = area.getPlotAbs(loc);
final Plot lastPlot = pp.getMeta("lastplot"); final Plot lastPlot = pp.getMeta("lastplot");
if (now == null) { if (now == null) {
if ((lastPlot != null) && !plotExit(pp, lastPlot)) { if (lastPlot != null && !plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals((BukkitUtil.getLocation(from).getPlot()))) { if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) {
player.teleport(from); player.teleport(from);
} else { } else {
player.teleport(player.getWorld().getSpawnLocation()); player.teleport(player.getWorld().getSpawnLocation());
@ -554,7 +550,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} else if ((lastPlot != null) && now.equals(lastPlot)) { } else if (lastPlot != null && now.equals(lastPlot)) {
return; return;
} else { } else {
if (!plotEntry(pp, now)) { if (!plotEntry(pp, now)) {
@ -587,7 +583,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
final PlotPlayer plr = BukkitUtil.getPlayer(player); final PlotPlayer plr = BukkitUtil.getPlayer(player);
Location loc = plr.getLocation(); Location loc = plr.getLocation();
PlotArea area = loc.getPlotArea(); PlotArea area = loc.getPlotArea();
if (area == null || (!area.PLOT_CHAT && !plr.getAttribute("chat"))) { if (area == null || !area.PLOT_CHAT && !plr.getAttribute("chat")) {
return; return;
} }
final Plot plot = area.getPlotAbs(loc); final Plot plot = area.getPlotAbs(loc);
@ -640,7 +636,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} else if (!plot.isAdded(pp.getUUID())) { } else if (!plot.isAdded(pp.getUUID())) {
final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break");
final Block block = event.getBlock(); final Block block = event.getBlock();
if ((destroy != null) && ((HashSet<PlotBlock>) destroy.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { if (destroy != null && ((HashSet<PlotBlock>) destroy.getValue())
.contains(new PlotBlock((short) block.getTypeId(), block.getData()))) {
return; return;
} }
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) {
@ -686,7 +683,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (FlagManager.isPlotFlagTrue(plot, "explosion")) { if (FlagManager.isPlotFlagTrue(plot, "explosion")) {
List<MetadataValue> meta = event.getEntity().getMetadata("plot"); List<MetadataValue> meta = event.getEntity().getMetadata("plot");
Plot origin; Plot origin;
if (meta.size() == 0) { if (meta.isEmpty()) {
origin = plot; origin = plot;
} else { } else {
origin = (Plot) meta.get(0).value(); origin = (Plot) meta.get(0).value();
@ -694,7 +691,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (lastRadius != 0) { if (lastRadius != 0) {
final List<Entity> nearby = event.getEntity().getNearbyEntities(lastRadius, lastRadius, lastRadius); final List<Entity> nearby = event.getEntity().getNearbyEntities(lastRadius, lastRadius, lastRadius);
for (final Entity near : nearby) { for (final Entity near : nearby) {
if ((near instanceof TNTPrimed) || (near.getType() == EntityType.MINECART_TNT)) { if (near instanceof TNTPrimed || near.getType() == EntityType.MINECART_TNT) {
if (!near.hasMetadata("plot")) { if (!near.hasMetadata("plot")) {
near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot));
} }
@ -721,7 +718,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
public void onWorldChanged(final PlayerChangedWorldEvent event) { public void onWorldChanged(final PlayerChangedWorldEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player); final PlotPlayer pp = BukkitUtil.getPlayer(player);
// Delete last location // Delete last location
pp.deleteMeta("location"); pp.deleteMeta("location");
@ -729,7 +726,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (plot != null) { if (plot != null) {
plotExit(pp, plot); plotExit(pp, plot);
} }
if (BukkitMain.worldEdit != null) { if (BukkitMain.worldEdit != null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) {
if (pp.getAttribute("worldedit")) { if (pp.getAttribute("worldedit")) {
@ -815,7 +812,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (!plot.isAdded(pp.getUUID())) { if (!plot.isAdded(pp.getUUID())) {
final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break");
final Block block = event.getBlock(); final Block block = event.getBlock();
if ((destroy != null) && ((HashSet<PlotBlock>) destroy.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { if (destroy != null && ((HashSet<PlotBlock>) destroy.getValue())
.contains(new PlotBlock((short) block.getTypeId(), block.getData()))) {
return; return;
} }
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) {
@ -928,7 +926,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
pistonBlocks = false; pistonBlocks = false;
} }
} }
if (!pistonBlocks && (block.getType() != Material.PISTON_BASE)) { if (!pistonBlocks && block.getType() != Material.PISTON_BASE) {
final BlockFace dir = event.getDirection(); final BlockFace dir = event.getDirection();
loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2));
if (loc.getPlotArea() != null) { if (loc.getPlotArea() != null) {
@ -957,7 +955,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
pistonBlocks = false; pistonBlocks = false;
} }
} }
if (!pistonBlocks && (block.getType() != Material.PISTON_BASE)) { if (!pistonBlocks && block.getType() != Material.PISTON_BASE) {
final BlockFace dir = event.getDirection(); final BlockFace dir = event.getDirection();
loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2));
if (!area.contains(loc)) { if (!area.contains(loc)) {
@ -989,7 +987,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return; return;
} }
final List<BlockState> blocks = e.getBlocks(); final List<BlockState> blocks = e.getBlocks();
if (blocks.size() == 0) { if (blocks.isEmpty()) {
return; return;
} }
Location loc = BukkitUtil.getLocation(blocks.get(0).getLocation()); Location loc = BukkitUtil.getLocation(blocks.get(0).getLocation());
@ -1106,24 +1104,21 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case HOPPER: case HOPPER:
case NOTE_BLOCK: case NOTE_BLOCK:
case JUKEBOX: case JUKEBOX:
case WORKBENCH: { case WORKBENCH:
eventType = PlayerBlockEventType.INTERACT_BLOCK; eventType = PlayerBlockEventType.INTERACT_BLOCK;
break; break;
} case DRAGON_EGG:
case DRAGON_EGG: {
eventType = PlayerBlockEventType.TELEPORT_OBJECT; eventType = PlayerBlockEventType.TELEPORT_OBJECT;
break; break;
} default:
default: {
if (blockId > 197) { if (blockId > 197) {
eventType = PlayerBlockEventType.INTERACT_BLOCK; eventType = PlayerBlockEventType.INTERACT_BLOCK;
} }
break; break;
}
} }
lb = new BukkitLazyBlock(blockId, block); lb = new BukkitLazyBlock(blockId, block);
final ItemStack hand = player.getItemInHand(); final ItemStack hand = player.getItemInHand();
if ((eventType != null) && !player.isSneaking()) { if (eventType != null && !player.isSneaking()) {
break; break;
} }
Material type = hand == null ? null : hand.getType(); Material type = hand == null ? null : hand.getType();
@ -1141,23 +1136,20 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
lb = new BukkitLazyBlock(new PlotBlock((short) handType.getId(), (byte) 0)); lb = new BukkitLazyBlock(new PlotBlock((short) handType.getId(), (byte) 0));
switch (handType) { switch (handType) {
case MONSTER_EGG: case MONSTER_EGG:
case MONSTER_EGGS: { case MONSTER_EGGS:
eventType = PlayerBlockEventType.SPAWN_MOB; eventType = PlayerBlockEventType.SPAWN_MOB;
break; break;
}
case ARMOR_STAND:
case ARMOR_STAND: {
eventType = PlayerBlockEventType.PLACE_MISC; eventType = PlayerBlockEventType.PLACE_MISC;
break; break;
}
case WRITTEN_BOOK: case WRITTEN_BOOK:
case BOOK_AND_QUILL: case BOOK_AND_QUILL:
case BOOK: { case BOOK:
eventType = PlayerBlockEventType.READ; eventType = PlayerBlockEventType.READ;
break; break;
}
case APPLE: case APPLE:
case BAKED_POTATO: case BAKED_POTATO:
case MUSHROOM_SOUP: case MUSHROOM_SOUP:
@ -1178,42 +1170,36 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case RABBIT_STEW: case RABBIT_STEW:
case RAW_BEEF: case RAW_BEEF:
case RAW_FISH: case RAW_FISH:
case RAW_CHICKEN: { case RAW_CHICKEN:
eventType = PlayerBlockEventType.EAT; eventType = PlayerBlockEventType.EAT;
break; break;
}
case MINECART: case MINECART:
case STORAGE_MINECART: case STORAGE_MINECART:
case POWERED_MINECART: case POWERED_MINECART:
case HOPPER_MINECART: case HOPPER_MINECART:
case EXPLOSIVE_MINECART: case EXPLOSIVE_MINECART:
case COMMAND_MINECART: case COMMAND_MINECART:
case BOAT: { case BOAT:
eventType = PlayerBlockEventType.PLACE_VEHICLE; eventType = PlayerBlockEventType.PLACE_VEHICLE;
break; break;
}
case PAINTING: case PAINTING:
case ITEM_FRAME: { case ITEM_FRAME:
eventType = PlayerBlockEventType.PLACE_HANGING; eventType = PlayerBlockEventType.PLACE_HANGING;
break; break;
} default:
default: {
eventType = PlayerBlockEventType.INTERACT_BLOCK; eventType = PlayerBlockEventType.INTERACT_BLOCK;
break; break;
}
} }
break; break;
} }
case LEFT_CLICK_BLOCK: { case LEFT_CLICK_BLOCK:
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
loc = BukkitUtil.getLocation(block.getLocation()); loc = BukkitUtil.getLocation(block.getLocation());
eventType = PlayerBlockEventType.BREAK_BLOCK; eventType = PlayerBlockEventType.BREAK_BLOCK;
lb = new BukkitLazyBlock(block); lb = new BukkitLazyBlock(block);
break; break;
} default:
default: {
return; return;
}
} }
if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, loc, lb, true)) { if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, loc, lb, true)) {
event.setCancelled(true); event.setCancelled(true);
@ -1293,7 +1279,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (event.getTo().hasGravity()) { if (event.getTo().hasGravity()) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
List<MetadataValue> meta = entity.getMetadata("plot"); List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.size() == 0) { if (meta.isEmpty()) {
return; return;
} }
Plot origin = (Plot) meta.get(0).value(); Plot origin = (Plot) meta.get(0).value();
@ -1307,13 +1293,11 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} }
} }
private float lastRadius;
@EventHandler @EventHandler
public void onPrime(final ExplosionPrimeEvent event) { public void onPrime(final ExplosionPrimeEvent event) {
lastRadius = event.getRadius() + 1; lastRadius = event.getRadius() + 1;
} }
public boolean checkEntity(Plot plot, String... flags) { public boolean checkEntity(Plot plot, String... flags) {
int[] mobs = null; int[] mobs = null;
for (String flag : flags) { for (String flag : flags) {
@ -1337,9 +1321,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case "misc-cap": case "misc-cap":
i = 5; i = 5;
break; break;
default: { default:
i = 0; i = 0;
}
} }
final Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag); final Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag);
if (plotFlag == null) { if (plotFlag == null) {
@ -1348,7 +1331,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (mobs == null) { if (mobs == null) {
mobs = plot.countEntities(); mobs = plot.countEntities();
} }
if (mobs[i] >= ((Integer) plotFlag.getValue())) { if (mobs[i] >= (Integer) plotFlag.getValue()) {
return true; return true;
} }
} }
@ -1356,13 +1339,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} }
public boolean checkEntity(final Entity entity, final Plot plot) { public boolean checkEntity(final Entity entity, final Plot plot) {
if (plot == null || plot.owner == null || plot.settings == null || (plot.settings.flags.size() == 0 && plot.getArea().DEFAULT_FLAGS.size() == 0)) { if (plot == null || plot.owner == null || plot.settings == null || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS
.isEmpty
()) {
return false; return false;
} }
switch (entity.getType()) { switch (entity.getType()) {
case PLAYER: { case PLAYER:
return false; return false;
}
case SMALL_FIREBALL: case SMALL_FIREBALL:
case FIREBALL: case FIREBALL:
case DROPPED_ITEM: case DROPPED_ITEM:
@ -1371,13 +1355,11 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case SPLASH_POTION: case SPLASH_POTION:
case SNOWBALL: case SNOWBALL:
case ENDER_PEARL: case ENDER_PEARL:
case ARROW: { case ARROW:
// projectile // projectile
}
case PRIMED_TNT: case PRIMED_TNT:
case FALLING_BLOCK: { case FALLING_BLOCK:
// Block entities // Block entities
}
case ENDER_CRYSTAL: case ENDER_CRYSTAL:
case COMPLEX_PART: case COMPLEX_PART:
case FISHING_HOOK: case FISHING_HOOK:
@ -1388,16 +1370,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case WEATHER: case WEATHER:
case LIGHTNING: case LIGHTNING:
case WITHER_SKULL: case WITHER_SKULL:
case UNKNOWN: { case UNKNOWN:
// non moving / unremovable // non moving / unremovable
return checkEntity(plot, "entity-cap"); return checkEntity(plot, "entity-cap");
}
case ITEM_FRAME: case ITEM_FRAME:
case PAINTING: case PAINTING:
case ARMOR_STAND: { case ARMOR_STAND:
return checkEntity(plot, "entity-cap", "misc-cap"); return checkEntity(plot, "entity-cap", "misc-cap");
// misc // misc
}
case MINECART: case MINECART:
case MINECART_CHEST: case MINECART_CHEST:
case MINECART_COMMAND: case MINECART_COMMAND:
@ -1405,9 +1385,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case MINECART_HOPPER: case MINECART_HOPPER:
case MINECART_MOB_SPAWNER: case MINECART_MOB_SPAWNER:
case MINECART_TNT: case MINECART_TNT:
case BOAT: { case BOAT:
return checkEntity(plot, "entity-cap", "vehicle-cap"); return checkEntity(plot, "entity-cap", "vehicle-cap");
}
case RABBIT: case RABBIT:
case SHEEP: case SHEEP:
case MUSHROOM_COW: case MUSHROOM_COW:
@ -1421,10 +1400,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case CHICKEN: case CHICKEN:
case COW: case COW:
case SNOWMAN: case SNOWMAN:
case BAT: { case BAT:
// animal // animal
return checkEntity(plot, "entity-cap", "mob-cap", "animal-cap"); return checkEntity(plot, "entity-cap", "mob-cap", "animal-cap");
}
case BLAZE: case BLAZE:
case CAVE_SPIDER: case CAVE_SPIDER:
case CREEPER: case CREEPER:
@ -1442,11 +1420,10 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
case SPIDER: case SPIDER:
case WITCH: case WITCH:
case WITHER: case WITHER:
case ZOMBIE: { case ZOMBIE:
// monster // monster
return checkEntity(plot, "entity-cap", "mob-cap", "hostile-cap"); return checkEntity(plot, "entity-cap", "mob-cap", "hostile-cap");
} default:
default: {
String[] types; String[] types;
if (entity instanceof LivingEntity) { if (entity instanceof LivingEntity) {
if (entity instanceof Animals) { if (entity instanceof Animals) {
@ -1464,7 +1441,6 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
types = new String[] { "entity-cap" }; types = new String[] { "entity-cap" };
} }
return checkEntity(plot, types); return checkEntity(plot, types);
}
} }
} }
@ -1526,12 +1502,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} }
} }
// To prevent recursion
private boolean tmp_teleport = true;
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onTeleport(final PlayerTeleportEvent event) { public void onTeleport(final PlayerTeleportEvent event) {
if ((event.getTo() == null) || (event.getFrom() == null)) { if (event.getTo() == null || event.getFrom() == null) {
BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location"); BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location");
BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot"); BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot");
return; return;
@ -1551,7 +1524,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
Plot now = area.getPlotAbs(loc); Plot now = area.getPlotAbs(loc);
final Plot lastPlot = pp.getMeta("lastplot"); final Plot lastPlot = pp.getMeta("lastplot");
if (now == null) { if (now == null) {
if ((lastPlot != null) && !plotExit(pp, lastPlot) && tmp_teleport) { if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) {
tmp_teleport = false; tmp_teleport = false;
@ -1568,7 +1541,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} else if ((lastPlot != null) && now.equals(lastPlot)) { } else if (lastPlot != null && now.equals(lastPlot)) {
return; return;
} else { } else {
if (!plotEntry(pp, now) && tmp_teleport) { if (!plotEntry(pp, now) && tmp_teleport) {
@ -1623,7 +1596,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
Plot now = area.getPlotAbs(loc); Plot now = area.getPlotAbs(loc);
final Plot lastPlot = pp.getMeta("lastplot"); final Plot lastPlot = pp.getMeta("lastplot");
if (now == null) { if (now == null) {
if ((lastPlot != null) && !plotExit(pp, lastPlot) && tmp_teleport) { if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) {
tmp_teleport = false; tmp_teleport = false;
@ -1640,7 +1613,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} else if ((lastPlot != null) && now.equals(lastPlot)) { } else if (lastPlot != null && now.equals(lastPlot)) {
return; return;
} else { } else {
if (!plotEntry(pp, now) && tmp_teleport) { if (!plotEntry(pp, now) && tmp_teleport) {
@ -1706,7 +1679,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
e.setCancelled(true); e.setCancelled(true);
} else if (!plot.isAdded(pp.getUUID())) { } else if (!plot.isAdded(pp.getUUID())) {
final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s());
if ((use != null) && ((HashSet<PlotBlock>) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) { if (use != null && ((HashSet<PlotBlock>) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) {
return; return;
} }
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
@ -1727,7 +1700,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
final Player player = (Player) clicker; final Player player = (Player) clicker;
final PlotPlayer pp = BukkitUtil.getPlayer(player); final PlotPlayer pp = BukkitUtil.getPlayer(player);
final PlotInventory inv = pp.getMeta("inventory"); final PlotInventory inv = pp.getMeta("inventory");
if ((inv != null) && (event.getRawSlot() == event.getSlot())) { if (inv != null && event.getRawSlot() == event.getSlot()) {
if (!inv.onClick(event.getSlot())) { if (!inv.onClick(event.getSlot())) {
event.setCancelled(true); event.setCancelled(true);
inv.close(); inv.close();
@ -1778,7 +1751,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} else if (!plot.isAdded(pp.getUUID())) { } else if (!plot.isAdded(pp.getUUID())) {
final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s());
final Block block = e.getBlockClicked(); final Block block = e.getBlockClicked();
if ((use != null) && ((HashSet<PlotBlock>) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { if (use != null && ((HashSet<PlotBlock>) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) {
return; return;
} }
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
@ -1939,19 +1912,19 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} }
} else if (!plot.isAdded(pp.getUUID())) { } else if (!plot.isAdded(pp.getUUID())) {
final Entity entity = e.getRightClicked(); final Entity entity = e.getRightClicked();
if ((entity instanceof Monster) && FlagManager.isPlotFlagTrue(plot, C.FLAG_HOSTILE_INTERACT.s())) { if (entity instanceof Monster && FlagManager.isPlotFlagTrue(plot, C.FLAG_HOSTILE_INTERACT.s())) {
return; return;
} }
if ((entity instanceof Animals) && FlagManager.isPlotFlagTrue(plot, C.FLAG_ANIMAL_INTERACT.s())) { if (entity instanceof Animals && FlagManager.isPlotFlagTrue(plot, C.FLAG_ANIMAL_INTERACT.s())) {
return; return;
} }
if ((entity instanceof Tameable) && ((Tameable) entity).isTamed() && FlagManager.isPlotFlagTrue(plot, C.FLAG_TAMED_INTERACT.s())) { if (entity instanceof Tameable && ((Tameable) entity).isTamed() && FlagManager.isPlotFlagTrue(plot, C.FLAG_TAMED_INTERACT.s())) {
return; return;
} }
if ((entity instanceof Vehicle) && FlagManager.isPlotFlagTrue(plot, C.FLAG_VEHICLE_USE.s())) { if (entity instanceof Vehicle && FlagManager.isPlotFlagTrue(plot, C.FLAG_VEHICLE_USE.s())) {
return; return;
} }
if ((entity instanceof Player) && FlagManager.isPlotFlagTrue(plot, C.FLAG_PLAYER_INTERACT.s())) { if (entity instanceof Player && FlagManager.isPlotFlagTrue(plot, C.FLAG_PLAYER_INTERACT.s())) {
return; return;
} }
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) {
@ -2032,7 +2005,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
final Location dloc = BukkitUtil.getLocation(damager); final Location dloc = BukkitUtil.getLocation(damager);
final Location vloc = BukkitUtil.getLocation(victim); final Location vloc = BukkitUtil.getLocation(victim);
PlotArea dArea = dloc.getPlotArea(); PlotArea dArea = dloc.getPlotArea();
PlotArea vArea = (dArea != null && dArea.contains(vloc.getX(), vloc.getZ())) ? dArea : vloc.getPlotArea(); PlotArea vArea = dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea();
if (dArea == null && vArea == null) { if (dArea == null && vArea == null) {
return true; return true;
} }
@ -2042,7 +2015,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
Plot plot; Plot plot;
String stub; String stub;
if ((dplot == null) && (vplot == null)) { if (dplot == null && vplot == null) {
if (dArea == null) { if (dArea == null) {
return true; return true;
} }
@ -2050,7 +2023,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
stub = "road"; stub = "road";
} else { } else {
// Priorize plots for close to seamless pvp zones // Priorize plots for close to seamless pvp zones
plot = vplot == null ? dplot : (((dplot == null) || !(victim instanceof Player)) ? vplot : (victim.getTicksLived() > damager.getTicksLived() ? dplot : vplot)); plot = vplot == null ? dplot : dplot == null || !(victim instanceof Player) ? vplot :
victim.getTicksLived() > damager.getTicksLived() ? dplot : vplot;
stub = plot.hasOwner() ? "other" : "unowned"; stub = plot.hasOwner() ? "other" : "unowned";
} }
@ -2071,7 +2045,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (player != null) { if (player != null) {
final PlotPlayer pp = BukkitUtil.getPlayer(player); final PlotPlayer pp = BukkitUtil.getPlayer(player);
if (victim instanceof Hanging) { // hanging if (victim instanceof Hanging) { // hanging
if ((plot != null) && ((FlagManager.isPlotFlagTrue(plot, "hanging-break") || plot.isAdded(pp.getUUID())))) { if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hanging-break") || plot.isAdded(pp.getUUID()))) {
return true; return true;
} }
if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) {
@ -2079,15 +2053,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return false; return false;
} }
} else if (victim.getEntityId() == 30) { } else if (victim.getEntityId() == 30) {
if ((plot != null) && ((FlagManager.isPlotFlagTrue(plot, "misc-break") || plot.isAdded(pp.getUUID())))) { if (plot != null && (FlagManager.isPlotFlagTrue(plot, "misc-break") || plot.isAdded(pp.getUUID()))) {
return true; return true;
} }
if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub);
return false; return false;
} }
} else if ((victim instanceof Monster) || (victim instanceof EnderDragon)) { // victim is monster } else if (victim instanceof Monster || victim instanceof EnderDragon) { // victim is monster
if ((plot != null) && ((FlagManager.isPlotFlagTrue(plot, "hostile-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID())))) { if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hostile-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot
.isAdded(pp.getUUID()))) {
return true; return true;
} }
if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) {
@ -2095,7 +2070,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return false; return false;
} }
} else if (victim instanceof Tameable) { // victim is tameable } else if (victim instanceof Tameable) { // victim is tameable
if ((plot != null) && ((FlagManager.isPlotFlagTrue(plot, "tamed-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID())))) { if (plot != null && (FlagManager.isPlotFlagTrue(plot, "tamed-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot
.isAdded(pp.getUUID()))) {
return true; return true;
} }
if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) {
@ -2121,7 +2097,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return false; return false;
} }
} else if (victim instanceof Creature) { // victim is animal } else if (victim instanceof Creature) { // victim is animal
if ((plot != null) && ((FlagManager.isPlotFlagTrue(plot, "animal-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID())))) { if (plot != null && (FlagManager.isPlotFlagTrue(plot, "animal-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot
.isAdded(pp.getUUID()))) {
return true; return true;
} }
if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) {
@ -2131,7 +2108,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event } else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event
return true; return true;
} else { // victim is something else } else { // victim is something else
if ((plot != null) && ((FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID())))) { if (plot != null && (FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID()))) {
return true; return true;
} }
if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) {
@ -2142,7 +2119,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return true; return true;
} }
// player is null // player is null
return !((damager instanceof Arrow) && (!(victim instanceof Creature))); return !(damager instanceof Arrow && !(victim instanceof Creature));
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@ -2195,7 +2172,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
} else if (!plot.isAdded(pp.getUUID())) { } else if (!plot.isAdded(pp.getUUID())) {
final Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s()); final Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s());
final Block block = event.getBlock(); final Block block = event.getBlock();
if (((place == null) || !((HashSet<PlotBlock>) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) if ((place == null || !((HashSet<PlotBlock>) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData())))
&& !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
event.setCancelled(true); event.setCancelled(true);
@ -2214,7 +2191,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
sendBlockChange(block.getLocation(), block.getType(), block.getData()); sendBlockChange(block.getLocation(), block.getType(), block.getData());
} }
} }
if (((loc.getY() > area.MAX_BUILD_HEIGHT) && (loc.getY() < area.MIN_BUILD_HEIGHT)) && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { if (loc.getY() > area.MAX_BUILD_HEIGHT && loc.getY() < area.MIN_BUILD_HEIGHT && !Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) {
event.setCancelled(true); event.setCancelled(true);
MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", "" + area.MAX_BUILD_HEIGHT)); MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", "" + area.MAX_BUILD_HEIGHT));
} }

View File

@ -20,13 +20,14 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners; package com.plotsquared.bukkit.listeners;
import java.util.ArrayList; import com.intellectualcrafters.plot.flag.Flag;
import java.util.HashMap; import com.intellectualcrafters.plot.flag.FlagManager;
import java.util.Iterator; import com.intellectualcrafters.plot.object.Plot;
import java.util.List; import com.intellectualcrafters.plot.object.PlotPlayer;
import java.util.Map.Entry; import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import java.util.UUID; import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material; import org.bukkit.Material;
@ -42,18 +43,17 @@ import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.plot.flag.Flag; import java.util.ArrayList;
import com.intellectualcrafters.plot.flag.FlagManager; import java.util.HashMap;
import com.intellectualcrafters.plot.object.Plot; import java.util.Iterator;
import com.intellectualcrafters.plot.object.PlotPlayer; import java.util.List;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; import java.util.Map.Entry;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; import java.util.UUID;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
/** /**
* Created 2014-10-30 for PlotSquared * Created 2014-10-30 for PlotSquared
* *
*/ */
@SuppressWarnings({ "deprecation" }) @SuppressWarnings({ "deprecation" })
public class PlotPlusListener extends PlotListener implements Listener { public class PlotPlusListener extends PlotListener implements Listener {
@ -64,7 +64,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
if (healRunnable.size() > 0) { if (!healRunnable.isEmpty()) {
for (final Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext();) { for (final Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext();) {
final Entry<String, Interval> entry = iter.next(); final Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue(); final Interval value = entry.getValue();
@ -83,7 +83,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
} }
} }
} }
if (feedRunnable.size() > 0) { if (!feedRunnable.isEmpty()) {
for (final Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) { for (final Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) {
final Entry<String, Interval> entry = iter.next(); final Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue(); final Interval value = entry.getValue();
@ -216,7 +216,8 @@ public class PlotPlusListener extends PlotListener implements Listener {
/** /**
* Record Meta Class * Record Meta Class
* *
*/ */
public static class RecordMeta { public static class RecordMeta {
public final static List<RecordMeta> metaList = new ArrayList<>(); public final static List<RecordMeta> metaList = new ArrayList<>();

View File

@ -3,7 +3,11 @@ package com.plotsquared.bukkit.object;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotGamemode;
import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Effect; import org.bukkit.Effect;
@ -12,7 +16,6 @@ import org.bukkit.WeatherType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.permissions.Permission; import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import java.util.UUID; import java.util.UUID;
@ -20,10 +23,10 @@ import java.util.UUID;
public class BukkitPlayer extends PlotPlayer { public class BukkitPlayer extends PlotPlayer {
public final Player player; public final Player player;
public boolean offline;
private UUID uuid; private UUID uuid;
private String name; private String name;
private long last = 0; private long last = 0;
public boolean offline;
/** /**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects. * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
@ -64,7 +67,7 @@ public class BukkitPlayer extends PlotPlayer {
@Override @Override
public boolean hasPermission(final String node) { public boolean hasPermission(final String node) {
if (offline && (EconHandler.manager != null)) { if (offline && EconHandler.manager != null) {
return EconHandler.manager.hasPermission(getName(), node); return EconHandler.manager.hasPermission(getName(), node);
} }
return player.hasPermission(node); return player.hasPermission(node);
@ -77,8 +80,8 @@ public class BukkitPlayer extends PlotPlayer {
final String[] nodes = node.split("\\."); final String[] nodes = node.split("\\.");
perm = new Permission(node); perm = new Permission(node);
final StringBuilder n = new StringBuilder(); final StringBuilder n = new StringBuilder();
for (int i = 0; i < (nodes.length - 1); i++) { for (int i = 0; i < nodes.length - 1; i++) {
n.append(nodes[i] + (".")); n.append(nodes[i]).append(".");
if (!node.equals(n + C.PERMISSION_STAR.s())) { if (!node.equals(n + C.PERMISSION_STAR.s())) {
final Permission parent = getPermission(n + C.PERMISSION_STAR.s()); final Permission parent = getPermission(n + C.PERMISSION_STAR.s());
if (parent != null) { if (parent != null) {
@ -105,7 +108,7 @@ public class BukkitPlayer extends PlotPlayer {
@Override @Override
public void teleport(final Location loc) { public void teleport(final Location loc) {
if ((Math.abs(loc.getX()) >= 30000000) || (Math.abs(loc.getZ()) >= 30000000)) { if (Math.abs(loc.getX()) >= 30000000 || Math.abs(loc.getZ()) >= 30000000) {
return; return;
} }
player.teleport(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX() + 0.5, loc.getY(), loc.getZ() + 0.5, loc.getYaw(), loc.getPitch()), TeleportCause.COMMAND); player.teleport(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX() + 0.5, loc.getY(), loc.getZ() + 0.5, loc.getYaw(), loc.getPitch()), TeleportCause.COMMAND);
@ -142,6 +145,7 @@ public class BukkitPlayer extends PlotPlayer {
@Override @Override
public boolean getAttribute(String key) { public boolean getAttribute(String key) {
if (!hasPersistentMeta(key)) { if (!hasPersistentMeta(key)) {
return false; return false;
} }
@ -171,10 +175,9 @@ public class BukkitPlayer extends PlotPlayer {
case CLEAR: case CLEAR:
player.setPlayerWeather(WeatherType.CLEAR); player.setPlayerWeather(WeatherType.CLEAR);
return; return;
case RAIN: { case RAIN:
player.setPlayerWeather(WeatherType.DOWNFALL); player.setPlayerWeather(WeatherType.DOWNFALL);
return; return;
}
case RESET: case RESET:
player.resetPlayerWeather(); player.resetPlayerWeather();
return; return;

View File

@ -33,7 +33,8 @@ import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
public class EntityWrapper { public class EntityWrapper {
public short id;
public EntityType type;
public float yaw; public float yaw;
public float pitch; public float pitch;
public double x; public double x;
@ -55,110 +56,6 @@ public class EntityWrapper {
private int hash; private int hash;
@Override
public boolean equals(final Object obj) {
return hash == obj.hashCode();
}
@Override
public int hashCode() {
return hash;
}
public void storeInventory(final InventoryHolder held) {
inventory = held.getInventory().getContents().clone();
}
private void restoreLiving(final LivingEntity entity) {
entity.setCanPickupItems(lived.loot);
if (lived.name != null) {
entity.setCustomName(lived.name);
entity.setCustomNameVisible(lived.visible);
}
if ((lived.potions != null) && (lived.potions.size() > 0)) {
entity.addPotionEffects(lived.potions);
}
entity.setRemainingAir(lived.air);
entity.setRemoveWhenFarAway(lived.persistent);
if (lived.equipped) {
final EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(lived.hands);
equipment.setHelmet(lived.helmet);
equipment.setChestplate(lived.chestplate);
equipment.setLeggings(lived.leggings);
equipment.setBoots(lived.boots);
}
if (lived.leashed) {
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math.floor(z) + lived.leash_z), EntityType.LEASH_HITCH);
// entity.setLeashHolder(leash);
}
}
private void restoreInventory(final InventoryHolder entity) {
entity.getInventory().setContents(inventory);
}
public void storeLiving(final LivingEntity lived) {
this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems();
this.lived.name = lived.getCustomName();
this.lived.visible = lived.isCustomNameVisible();
this.lived.health = (float) lived.getHealth();
this.lived.air = (short) lived.getRemainingAir();
this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) {
final Location loc = lived.getLeashHolder().getLocation();
this.lived.leash_x = (short) (x - loc.getBlockX());
this.lived.leash_y = (short) (y - loc.getBlockY());
this.lived.leash_z = (short) (z - loc.getBlockZ());
}
final EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null;
if (this.lived.equipped) {
this.lived.hands = equipment.getItemInHand().clone();
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
this.lived.chestplate = equipment.getChestplate().clone();
this.lived.helmet = equipment.getHelmet().clone();
}
}
private void restoreTameable(final Tameable entity) {
if (tamed.tamed) {
if (tamed.owner != null) {
entity.setTamed(true);
entity.setOwner(tamed.owner);
}
}
}
private void restoreAgeable(final Ageable entity) {
if (!aged.adult) {
entity.setBaby();
}
entity.setAgeLock(aged.locked);
if (aged.age > 0) {
entity.setAge(aged.age);
}
}
public void storeAgeable(final Ageable aged) {
this.aged = new AgeableStats();
this.aged.age = aged.getAge();
this.aged.locked = aged.getAgeLock();
this.aged.adult = aged.isAdult();
}
public void storeTameable(final Tameable tamed) {
this.tamed = new TameableStats();
this.tamed.owner = tamed.getOwner();
this.tamed.tamed = tamed.isTamed();
}
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) { public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) {
hash = entity.getEntityId(); hash = entity.getEntityId();
@ -169,7 +66,7 @@ public class EntityWrapper {
x = loc.getX(); x = loc.getX();
y = loc.getY(); y = loc.getY();
z = loc.getZ(); z = loc.getZ();
id = entity.getType().getTypeId(); type = entity.getType();
if (depth == 0) { if (depth == 0) {
return; return;
} }
@ -330,37 +227,37 @@ public class EntityWrapper {
inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() }; inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() };
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
this.stand = new ArmorStandStats(); this.stand = new ArmorStandStats();
final EulerAngle head = stand.getHeadPose(); final EulerAngle head = stand.getHeadPose();
this.stand.head[0] = (float) head.getX(); this.stand.head[0] = (float) head.getX();
this.stand.head[1] = (float) head.getY(); this.stand.head[1] = (float) head.getY();
this.stand.head[2] = (float) head.getZ(); this.stand.head[2] = (float) head.getZ();
final EulerAngle body = stand.getBodyPose(); final EulerAngle body = stand.getBodyPose();
this.stand.body[0] = (float) body.getX(); this.stand.body[0] = (float) body.getX();
this.stand.body[1] = (float) body.getY(); this.stand.body[1] = (float) body.getY();
this.stand.body[2] = (float) body.getZ(); this.stand.body[2] = (float) body.getZ();
final EulerAngle leftLeg = stand.getLeftLegPose(); final EulerAngle leftLeg = stand.getLeftLegPose();
this.stand.leftLeg[0] = (float) leftLeg.getX(); this.stand.leftLeg[0] = (float) leftLeg.getX();
this.stand.leftLeg[1] = (float) leftLeg.getY(); this.stand.leftLeg[1] = (float) leftLeg.getY();
this.stand.leftLeg[2] = (float) leftLeg.getZ(); this.stand.leftLeg[2] = (float) leftLeg.getZ();
final EulerAngle rightLeg = stand.getRightLegPose(); final EulerAngle rightLeg = stand.getRightLegPose();
this.stand.rightLeg[0] = (float) rightLeg.getX(); this.stand.rightLeg[0] = (float) rightLeg.getX();
this.stand.rightLeg[1] = (float) rightLeg.getY(); this.stand.rightLeg[1] = (float) rightLeg.getY();
this.stand.rightLeg[2] = (float) rightLeg.getZ(); this.stand.rightLeg[2] = (float) rightLeg.getZ();
final EulerAngle leftArm = stand.getLeftArmPose(); final EulerAngle leftArm = stand.getLeftArmPose();
this.stand.leftArm[0] = (float) leftArm.getX(); this.stand.leftArm[0] = (float) leftArm.getX();
this.stand.leftArm[1] = (float) leftArm.getY(); this.stand.leftArm[1] = (float) leftArm.getY();
this.stand.leftArm[2] = (float) leftArm.getZ(); this.stand.leftArm[2] = (float) leftArm.getZ();
final EulerAngle rightArm = stand.getRightArmPose(); final EulerAngle rightArm = stand.getRightArmPose();
this.stand.rightArm[0] = (float) rightArm.getX(); this.stand.rightArm[0] = (float) rightArm.getX();
this.stand.rightArm[1] = (float) rightArm.getY(); this.stand.rightArm[1] = (float) rightArm.getY();
this.stand.rightArm[2] = (float) rightArm.getZ(); this.stand.rightArm[2] = (float) rightArm.getZ();
if (stand.hasArms()) { if (stand.hasArms()) {
this.stand.arms = true; this.stand.arms = true;
} }
@ -403,16 +300,120 @@ public class EntityWrapper {
// END LIVING // // END LIVING //
} }
} }
@Override
public boolean equals(final Object obj) {
return hash == obj.hashCode();
}
@Override
public int hashCode() {
return hash;
}
public void storeInventory(final InventoryHolder held) {
inventory = held.getInventory().getContents().clone();
}
private void restoreLiving(final LivingEntity entity) {
entity.setCanPickupItems(lived.loot);
if (lived.name != null) {
entity.setCustomName(lived.name);
entity.setCustomNameVisible(lived.visible);
}
if ((lived.potions != null) && (!lived.potions.isEmpty())) {
entity.addPotionEffects(lived.potions);
}
entity.setRemainingAir(lived.air);
entity.setRemoveWhenFarAway(lived.persistent);
if (lived.equipped) {
final EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(lived.hands);
equipment.setHelmet(lived.helmet);
equipment.setChestplate(lived.chestplate);
equipment.setLeggings(lived.leggings);
equipment.setBoots(lived.boots);
}
if (lived.leashed) {
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math
// .floor(z) + lived.leash_z), EntityType.LEASH_HITCH);
// entity.setLeashHolder(leash);
}
}
private void restoreInventory(final InventoryHolder entity) {
entity.getInventory().setContents(inventory);
}
public void storeLiving(final LivingEntity lived) {
this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems();
this.lived.name = lived.getCustomName();
this.lived.visible = lived.isCustomNameVisible();
this.lived.health = (float) lived.getHealth();
this.lived.air = (short) lived.getRemainingAir();
this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) {
final Location loc = lived.getLeashHolder().getLocation();
this.lived.leash_x = (short) (x - loc.getBlockX());
this.lived.leash_y = (short) (y - loc.getBlockY());
this.lived.leash_z = (short) (z - loc.getBlockZ());
}
final EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null;
if (this.lived.equipped) {
this.lived.hands = equipment.getItemInHand().clone();
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
this.lived.chestplate = equipment.getChestplate().clone();
this.lived.helmet = equipment.getHelmet().clone();
}
}
private void restoreTameable(final Tameable entity) {
if (tamed.tamed) {
if (tamed.owner != null) {
entity.setTamed(true);
entity.setOwner(tamed.owner);
}
}
}
private void restoreAgeable(final Ageable entity) {
if (!aged.adult) {
entity.setBaby();
}
entity.setAgeLock(aged.locked);
if (aged.age > 0) {
entity.setAge(aged.age);
}
}
public void storeAgeable(final Ageable aged) {
this.aged = new AgeableStats();
this.aged.age = aged.getAge();
this.aged.locked = aged.getAgeLock();
this.aged.adult = aged.isAdult();
}
public void storeTameable(final Tameable tamed) {
this.tamed = new TameableStats();
this.tamed.owner = tamed.getOwner();
this.tamed.tamed = tamed.isTamed();
}
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Entity spawn(final World world, final int x_offset, final int z_offset) { public Entity spawn(final World world, final int x_offset, final int z_offset) {
final Location loc = new Location(world, x + x_offset, y, z + z_offset); final Location loc = new Location(world, x + x_offset, y, z + z_offset);
loc.setYaw(yaw); loc.setYaw(yaw);
loc.setPitch(pitch); loc.setPitch(pitch);
if (id == -1) { if (type.isSpawnable()) {
return null; return null;
} }
final EntityType type = EntityType.fromId(id);
Entity entity; Entity entity;
switch (type) { switch (type) {
case DROPPED_ITEM: { case DROPPED_ITEM: {

View File

@ -1,16 +1,5 @@
package com.plotsquared.bukkit.object.schematic; package com.plotsquared.bukkit.object.schematic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import com.intellectualcrafters.jnbt.ByteTag; import com.intellectualcrafters.jnbt.ByteTag;
import com.intellectualcrafters.jnbt.CompoundTag; import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.ListTag; import com.intellectualcrafters.jnbt.ListTag;
@ -20,6 +9,16 @@ import com.intellectualcrafters.plot.object.schematic.ItemType;
import com.intellectualcrafters.plot.object.schematic.PlotItem; import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class StateWrapper { public class StateWrapper {
@ -46,9 +45,9 @@ public class StateWrapper {
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
final Tag itemTag = itemsTag.get(i); final Tag itemTag = itemsTag.get(i);
final CompoundTag itemComp = (CompoundTag) itemTag; final CompoundTag itemComp = (CompoundTag) itemTag;
short id = itemComp.getShort("id"); short id = itemComp.getShort("type");
String idStr = itemComp.getString("id"); String idStr = itemComp.getString("type");
if ((idStr != null) && !MathMan.isInteger(idStr)) { if (idStr != null && !MathMan.isInteger(idStr)) {
idStr = idStr.split(":")[0].toLowerCase(); idStr = idStr.split(":")[0].toLowerCase();
id = (short) ItemType.getId(idStr); id = (short) ItemType.getId(idStr);
} }
@ -69,7 +68,7 @@ public class StateWrapper {
if (state instanceof InventoryHolder) { if (state instanceof InventoryHolder) {
final InventoryHolder inv = (InventoryHolder) state; final InventoryHolder inv = (InventoryHolder) state;
final ItemStack[] contents = inv.getInventory().getContents(); final ItemStack[] contents = inv.getInventory().getContents();
final Map<String, Tag> values = new HashMap<String, Tag>(); final Map<String, Tag> values = new HashMap<>();
values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents))); values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents)));
return new CompoundTag(values); return new CompoundTag(values);
} }
@ -81,7 +80,7 @@ public class StateWrapper {
} }
public List<CompoundTag> serializeInventory(final ItemStack[] items) { public List<CompoundTag> serializeInventory(final ItemStack[] items) {
final List<CompoundTag> tags = new ArrayList<CompoundTag>(); final List<CompoundTag> tags = new ArrayList<>();
for (int i = 0; i < items.length; ++i) { for (int i = 0; i < items.length; ++i) {
if (items[i] != null) { if (items[i] != null) {
final Map<String, Tag> tagData = serializeItem(items[i]); final Map<String, Tag> tagData = serializeItem(items[i]);
@ -105,19 +104,19 @@ public class StateWrapper {
*/ */
public Map<String, Tag> serializeItem(final ItemStack item) { public Map<String, Tag> serializeItem(final ItemStack item) {
final Map<String, Tag> data = new HashMap<String, Tag>(); final Map<String, Tag> data = new HashMap<>();
data.put("id", new ShortTag("id", (short) item.getTypeId())); data.put("type", new ShortTag("type", (short) item.getTypeId()));
data.put("Damage", new ShortTag("Damage", item.getDurability())); data.put("Damage", new ShortTag("Damage", item.getDurability()));
data.put("Count", new ByteTag("Count", (byte) item.getAmount())); data.put("Count", new ByteTag("Count", (byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) { if (!item.getEnchantments().isEmpty()) {
final List<CompoundTag> enchantmentList = new ArrayList<CompoundTag>(); final List<CompoundTag> enchantmentList = new ArrayList<>();
for (final Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) { for (final Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
final Map<String, Tag> enchantment = new HashMap<String, Tag>(); final Map<String, Tag> enchantment = new HashMap<>();
enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId())); enchantment.put("type", new ShortTag("type", (short) entry.getKey().getId()));
enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue())); enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue()));
enchantmentList.add(new CompoundTag(enchantment)); enchantmentList.add(new CompoundTag(enchantment));
} }
final Map<String, Tag> auxData = new HashMap<String, Tag>(); final Map<String, Tag> auxData = new HashMap<>();
auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList)); auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList));
data.put("tag", new CompoundTag("tag", auxData)); data.put("tag", new CompoundTag("tag", auxData));
} }

View File

@ -10,7 +10,7 @@ public class DefaultTitle extends AbstractTitle {
try { try {
final DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out); final DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player); title.send(((BukkitPlayer) player).player);
} catch (final Throwable e) { } catch (Exception e) {
AbstractTitle.TITLE_CLASS = new DefaultTitle_183(); AbstractTitle.TITLE_CLASS = new DefaultTitle_183();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
} }

View File

@ -1,15 +1,15 @@
package com.plotsquared.bukkit.titles; package com.plotsquared.bukkit.titles;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/** /**
* [ PlotSquared DefaultTitleManager by Maxim Van de Wynckel ] * [ PlotSquared DefaultTitleManager by Maxim Van de Wynckel ]
* *
@ -18,6 +18,8 @@ import org.bukkit.entity.Player;
* *
*/ */
public class DefaultTitleManager { public class DefaultTitleManager {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */ /* Title packet */
private Class<?> packetTitle; private Class<?> packetTitle;
/* Title packet actions ENUM */ /* Title packet actions ENUM */
@ -36,8 +38,7 @@ public class DefaultTitleManager {
private int stayTime = -1; private int stayTime = -1;
private int fadeOutTime = -1; private int fadeOutTime = -1;
private boolean ticks = false; private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<Class<?>, Class<?>>();
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
@ -49,7 +50,7 @@ public class DefaultTitleManager {
this.title = title; this.title = title;
loadClasses(); loadClasses();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
@ -64,7 +65,7 @@ public class DefaultTitleManager {
this.subtitle = subtitle; this.subtitle = subtitle;
loadClasses(); loadClasses();
} }
/** /**
* Copy 1.8 title * Copy 1.8 title
* *
@ -84,7 +85,7 @@ public class DefaultTitleManager {
ticks = title.ticks; ticks = title.ticks;
loadClasses(); loadClasses();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
@ -108,216 +109,7 @@ public class DefaultTitleManager {
this.fadeOutTime = fadeOutTime; this.fadeOutTime = fadeOutTime;
loadClasses(); loadClasses();
} }
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
packetTitle = getNMSClass("PacketPlayOutTitle");
packetActions = getNMSClass("EnumTitleAction");
chatBaseComponent = getNMSClass("IChatBaseComponent");
nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(final String title) {
this.title = title;
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle() {
return title;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle) {
this.subtitle = subtitle;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle() {
return subtitle;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(final int time) {
fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(final int time) {
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
ticks = false;
}
/**
* Send the title to a player
*
* @param player
* Player
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player) throws Exception {
if (packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (subtitle != "") {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
/**
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
* @param player
* Player
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings
*
* @param player
* Player
*/
public void resetTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) { private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) { if (a.length != o.length) {
return false; return false;
@ -329,16 +121,239 @@ public class DefaultTitleManager {
} }
return true; return true;
} }
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
packetTitle = getNMSClass("PacketPlayOutTitle");
packetActions = getNMSClass("EnumTitleAction");
chatBaseComponent = getNMSClass("IChatBaseComponent");
nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle() {
return title;
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(final String title) {
this.title = title;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle() {
return subtitle;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle) {
this.subtitle = subtitle;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(final int time) {
fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(final int time) {
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
ticks = false;
}
/**
* Send the title to a player
*
* @param player
* Player
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player)
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
if (packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!subtitle.isEmpty()) {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
/**
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast()
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
* @param player
* Player
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player)
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings
*
* @param player
* Player
*/
public void resetTitle(final Player player)
throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
SecurityException {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private Object getHandle(final Object obj) { private Object getHandle(final Object obj) {
try { try {
return getMethod("getHandle", obj.getClass()).invoke(obj); return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (final Exception e) { } catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) { private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes); final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) { for (final Method m : clazz.getMethods()) {
@ -349,46 +364,46 @@ public class DefaultTitleManager {
} }
return null; return null;
} }
private String getVersion() { private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName(); final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + "."; return name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
} }
private Class<?> getNMSClass(final String className) throws ClassNotFoundException { private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
final String fullName = "net.minecraft.server." + getVersion() + className; final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null; return Class.forName(fullName);
clazz = Class.forName(fullName);
return clazz;
} }
private Field getField(final Class<?> clazz, final String name) { private Field getField(final Class<?> clazz, final String name) {
try { try {
final Field field = clazz.getDeclaredField(name); final Field field = clazz.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
return field; return field;
} catch (final Exception e) { } catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
} catch (SecurityException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) { private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) { for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) { if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true); m.setAccessible(true);
return m; return m;
} }
} }
return null; return null;
} }
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) { private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) { if (l1.length != l2.length) {
return false; return false;
} }
boolean equal = true;
for (int i = 0; i < l1.length; i++) { for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) { if (l1[i] != l2[i]) {
equal = false; equal = false;

View File

@ -1,10 +1,5 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.ConsolePlayer; import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotMessage; import com.intellectualcrafters.plot.object.PlotMessage;
@ -12,19 +7,23 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChatManager; import com.intellectualcrafters.plot.util.ChatManager;
import com.plotsquared.bukkit.chat.FancyMessage; import com.plotsquared.bukkit.chat.FancyMessage;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class BukkitChatManager extends ChatManager<FancyMessage> { public class BukkitChatManager extends ChatManager<FancyMessage> {
@Override @Override
public FancyMessage builder() { public FancyMessage builder() {
return new FancyMessage(""); return new FancyMessage("");
} }
@Override @Override
public void color(final PlotMessage m, final String color) { public void color(final PlotMessage m, final String color) {
m.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); m.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
} }
@Override @Override
public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { public void tooltip(final PlotMessage m, final PlotMessage... tooltips) {
final List<FancyMessage> lines = new ArrayList<>(); final List<FancyMessage> lines = new ArrayList<>();
@ -33,17 +32,17 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
} }
m.$(this).formattedTooltip(lines); m.$(this).formattedTooltip(lines);
} }
@Override @Override
public void command(final PlotMessage m, final String command) { public void command(final PlotMessage m, final String command) {
m.$(this).command(command); m.$(this).command(command);
} }
@Override @Override
public void text(final PlotMessage m, final String text) { public void text(final PlotMessage m, final String text) {
m.$(this).then(ChatColor.stripColor(text)); m.$(this).then(ChatColor.stripColor(text));
} }
@Override @Override
public void send(final PlotMessage m, final PlotPlayer player) { public void send(final PlotMessage m, final PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) { if (ConsolePlayer.isConsole(player)) {
@ -52,10 +51,10 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
m.$(this).send(((BukkitPlayer) player).player); m.$(this).send(((BukkitPlayer) player).player);
} }
} }
@Override @Override
public void suggest(final PlotMessage m, final String command) { public void suggest(final PlotMessage m, final String command) {
m.$(this).suggest(command); m.$(this).suggest(command);
} }
} }

View File

@ -1,17 +1,5 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.commands.MainCommand; import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer; import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
@ -19,19 +7,32 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringComparison; import com.intellectualcrafters.plot.util.StringComparison;
import com.plotsquared.bukkit.commands.DebugUUID; import com.plotsquared.bukkit.commands.DebugUUID;
import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.Command;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** /**
* Created 2015-02-20 for PlotSquared * Created 2015-02-20 for PlotSquared
* *
*/ */
public class BukkitCommand implements CommandExecutor, TabCompleter { public class BukkitCommand implements CommandExecutor, TabCompleter {
public BukkitCommand() { public BukkitCommand() {
MainCommand.getInstance().addCommand(new DebugUUID()); MainCommand.getInstance().addCommand(new DebugUUID());
} }
@Override @Override
public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, final String[] args) { public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel,
final String[] args) {
if (commandSender instanceof Player) { if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args); return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args);
} }
@ -44,12 +45,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
public void sendMessage(String message) { public void sendMessage(String message) {
commandSender.sendMessage(commandLabel); commandSender.sendMessage(commandLabel);
} }
@Override @Override
public boolean hasPermission(String perm) { public boolean hasPermission(String perm) {
return commandSender.hasPermission(commandLabel); return commandSender.hasPermission(commandLabel);
} }
@Override @Override
public String getName() { public String getName() {
if (commandSender.getName().equals("CONSOLE")) { if (commandSender.getName().equals("CONSOLE")) {
@ -63,9 +64,10 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
ConsolePlayer.getConsole().teleport(sender.getLocationFull()); ConsolePlayer.getConsole().teleport(sender.getLocationFull());
return result; return result;
} }
@Override @Override
public List<String> onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, final String[] strings) { public List<String> onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s,
final String[] strings) {
if (!(commandSender instanceof Player)) { if (!(commandSender instanceof Player)) {
return null; return null;
} }
@ -98,7 +100,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
} }
String best = new StringComparison<>(arg, labels).getBestMatch(); String best = new StringComparison<>(arg, labels).getBestMatch();
tabOptions.add(best); tabOptions.add(best);
if (tabOptions.size() > 0) { if (!tabOptions.isEmpty()) {
return new ArrayList<>(tabOptions); return new ArrayList<>(tabOptions);
} }
return null; return null;

View File

@ -1,80 +1,80 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer; import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
public class BukkitEconHandler extends EconHandler { public class BukkitEconHandler extends EconHandler {
private Economy econ; private Economy econ;
private Permission perms; private Permission perms;
public Economy getEconomy() { public Economy getEconomy() {
init(); init();
return econ; return econ;
} }
public Permission getPermissions() { public Permission getPermissions() {
init(); init();
return perms; return perms;
} }
public boolean init() { public boolean init() {
if ((econ == null) || (perms == null)) { if (econ == null || perms == null) {
setupPermissions(); setupPermissions();
setupEconomy(); setupEconomy();
} }
return (econ != null) && (perms != null); return econ != null && perms != null;
} }
private boolean setupPermissions() { private boolean setupPermissions() {
final RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); final RegisteredServiceProvider<Permission> permissionProvider =
Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) { if (permissionProvider != null) {
perms = permissionProvider.getProvider(); perms = permissionProvider.getProvider();
} }
return (perms != null); return perms != null;
} }
private boolean setupEconomy() { private boolean setupEconomy() {
final RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); final RegisteredServiceProvider<Economy> economyProvider =
Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) { if (economyProvider != null) {
econ = economyProvider.getProvider(); econ = economyProvider.getProvider();
} }
return (econ != null); return econ != null;
} }
@Override @Override
public double getMoney(final PlotPlayer player) { public double getMoney(final PlotPlayer player) {
final double bal = super.getMoney(player); final double bal = super.getMoney(player);
if (Double.isNaN(bal)) { if (Double.isNaN(bal)) {
return econ.getBalance(((BukkitPlayer)player).player); return econ.getBalance(((BukkitPlayer) player).player);
} }
return bal; return bal;
} }
@Override @Override
public void withdrawMoney(final PlotPlayer player, final double amount) { public void withdrawMoney(final PlotPlayer player, final double amount) {
econ.withdrawPlayer(((BukkitPlayer)player).player, amount); econ.withdrawPlayer(((BukkitPlayer) player).player, amount);
} }
@Override @Override
public void depositMoney(final PlotPlayer player, final double amount) { public void depositMoney(final PlotPlayer player, final double amount) {
econ.depositPlayer(((BukkitPlayer)player).player, amount); econ.depositPlayer(((BukkitPlayer) player).player, amount);
} }
@Override @Override
public void depositMoney(final OfflinePlotPlayer player, final double amount) { public void depositMoney(final OfflinePlotPlayer player, final double amount) {
econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
} }
@Override @Override
public void setPermission(final String world, final String player, final String perm, final boolean value) { public void setPermission(final String world, final String player, final String perm, final boolean value) {
if (value) { if (value) {
@ -83,7 +83,7 @@ public class BukkitEconHandler extends EconHandler {
perms.playerRemove(world, player, perm); perms.playerRemove(world, player, perm);
} }
} }
@Override @Override
public boolean hasPermission(final String world, final String player, final String perm) { public boolean hasPermission(final String world, final String player, final String perm) {
return perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); return perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);

View File

@ -34,97 +34,94 @@ import java.util.ArrayList;
import java.util.UUID; import java.util.UUID;
public class BukkitEventUtil extends EventUtil { public class BukkitEventUtil extends EventUtil {
public Player getPlayer(final PlotPlayer player) { public Player getPlayer(final PlotPlayer player) {
if (player instanceof BukkitPlayer) { if (player instanceof BukkitPlayer) {
return ((BukkitPlayer) player).player; return ((BukkitPlayer) player).player;
} }
return null; return null;
} }
public boolean callEvent(final Event event) { public boolean callEvent(final Event event) {
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (event instanceof Cancellable) { return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled();
return !((Cancellable) event).isCancelled();
}
return true;
} }
@Override @Override
public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto) { public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto) {
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
} }
@Override @Override
public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot) { public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
} }
@Override @Override
public boolean callClear(final Plot plot) { public boolean callClear(final Plot plot) {
return callEvent(new PlotClearEvent(plot)); return callEvent(new PlotClearEvent(plot));
} }
@Override @Override
public void callDelete(final Plot plot) { public void callDelete(final Plot plot) {
callEvent(new PlotDeleteEvent(plot)); callEvent(new PlotDeleteEvent(plot));
} }
@Override @Override
public boolean callFlagAdd(final Flag flag, final Plot plot) { public boolean callFlagAdd(final Flag flag, final Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot)); return callEvent(new PlotFlagAddEvent(flag, plot));
} }
@Override @Override
public boolean callFlagRemove(final Flag flag, final Plot plot) { public boolean callFlagRemove(final Flag flag, final Plot plot) {
return callEvent(new PlotFlagRemoveEvent(flag, plot)); return callEvent(new PlotFlagRemoveEvent(flag, plot));
} }
@Override @Override
public boolean callMerge(final Plot plot, final ArrayList<PlotId> plots) { public boolean callMerge(final Plot plot, final ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getArea().worldname), plot, plots)); return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getArea().worldname), plot, plots));
} }
@Override @Override
public boolean callUnlink(final PlotArea area, final ArrayList<PlotId> plots) { public boolean callUnlink(final PlotArea area, final ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots));
} }
@Override @Override
public void callEntry(final PlotPlayer player, final Plot plot) { public void callEntry(final PlotPlayer player, final Plot plot) {
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
} }
@Override @Override
public void callLeave(final PlotPlayer player, final Plot plot) { public void callLeave(final PlotPlayer player, final Plot plot) {
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
} }
@Override @Override
public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) {
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
} }
@Override @Override
public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
} }
@Override @Override
public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
} }
@Override @Override
public boolean callFlagRemove(final Flag flag, final PlotCluster cluster) { public boolean callFlagRemove(final Flag flag, final PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
} }
@Override @Override
public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating) { public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating) {
final PlotRateEvent event = new PlotRateEvent(player, rating, plot); final PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
return event.getRating(); return event.getRating();
} }
} }

View File

@ -1,18 +1,5 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.HashSet;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.material.Directional;
import org.bukkit.material.MaterialData;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotAnalysis;
@ -23,9 +10,21 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.material.Directional;
import org.bukkit.material.MaterialData;
import java.util.HashSet;
import java.util.Random;
public class BukkitHybridUtils extends HybridUtils { public class BukkitHybridUtils extends HybridUtils {
@Override @Override
public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal<PlotAnalysis> whenDone) { public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal<PlotAnalysis> whenDone) {
// int diff, int variety, int vertices, int rotation, int height_sd // int diff, int variety, int vertices, int rotation, int height_sd
@ -50,20 +49,21 @@ public class BukkitHybridUtils extends HybridUtils {
} }
final BiomeGrid nullBiomeGrid = new BiomeGrid() { final BiomeGrid nullBiomeGrid = new BiomeGrid() {
@Override @Override
public void setBiome(final int a, final int b, final Biome c) {} public void setBiome(final int a, final int b, final Biome c) {
}
@Override @Override
public Biome getBiome(final int a, final int b) { public Biome getBiome(final int a, final int b) {
return null; return null;
} }
}; };
final Location bot = new Location(world, region.minX, region.minY, region.minZ); final Location bot = new Location(world, region.minX, region.minY, region.minZ);
final Location top = new Location(world, region.maxX, region.maxY, region.maxZ); final Location top = new Location(world, region.maxX, region.maxY, region.maxZ);
// final Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1); // final Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.type).add(1, 0, 1);
// final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id); // final Location top = MainUtil.getPlotTopLoc(plot.world, plot.type);
final int bx = bot.getX(); final int bx = bot.getX();
final int bz = bot.getZ(); final int bz = bot.getZ();
final int tx = top.getX(); final int tx = top.getX();
@ -76,12 +76,12 @@ public class BukkitHybridUtils extends HybridUtils {
MainUtil.initCache(); MainUtil.initCache();
final int width = (tx - bx) + 1; final int width = (tx - bx) + 1;
final int length = (tz - bz) + 1; final int length = (tz - bz) + 1;
System.gc(); System.gc();
System.gc(); System.gc();
final short[][][] oldblocks = new short[256][width][length]; final short[][][] oldblocks = new short[256][width][length];
final short[][][] newblocks = new short[256][width][length]; final short[][][] newblocks = new short[256][width][length];
final Runnable run = new Runnable() { final Runnable run = new Runnable() {
@Override @Override
public void run() { public void run() {
@ -123,7 +123,7 @@ public class BukkitHybridUtils extends HybridUtils {
oldblocks[y][x][z] = result[i][j]; oldblocks[y][x][z] = result[i][j];
} }
} }
} }
}, new Runnable() { }, new Runnable() {
@Override @Override
@ -172,7 +172,7 @@ public class BukkitHybridUtils extends HybridUtils {
faces[i]++; faces[i]++;
} }
} }
final Material material = Material.getMaterial(now); final Material material = Material.getMaterial(now);
final Class<? extends MaterialData> md = material.getData(); final Class<? extends MaterialData> md = material.getData();
if (md.equals(Directional.class)) { if (md.equals(Directional.class)) {
@ -189,7 +189,7 @@ public class BukkitHybridUtils extends HybridUtils {
} }
// analyze plot // analyze plot
// put in analysis obj // put in analysis obj
// run whenDone // run whenDone
final PlotAnalysis analysis = new PlotAnalysis(); final PlotAnalysis analysis = new PlotAnalysis();
analysis.changes = (int) (MathMan.getMean(changes) * 100); analysis.changes = (int) (MathMan.getMean(changes) * 100);
@ -197,7 +197,7 @@ public class BukkitHybridUtils extends HybridUtils {
analysis.data = (int) (MathMan.getMean(data) * 100); analysis.data = (int) (MathMan.getMean(data) * 100);
analysis.air = (int) (MathMan.getMean(air) * 100); analysis.air = (int) (MathMan.getMean(air) * 100);
analysis.variety = (int) (MathMan.getMean(variety) * 100); analysis.variety = (int) (MathMan.getMean(variety) * 100);
analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes)); analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes));
analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces)); analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces));
analysis.data_sd = (int) (MathMan.getSD(data, analysis.data)); analysis.data_sd = (int) (MathMan.getSD(data, analysis.data));
@ -211,13 +211,13 @@ public class BukkitHybridUtils extends HybridUtils {
}); });
} }
}, 5); }, 5);
} }
}; };
System.gc(); System.gc();
MainUtil.initCache(); MainUtil.initCache();
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() { ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override @Override
public void run(int[] value) { public void run(int[] value) {
final int X = value[0]; final int X = value[0];
@ -247,10 +247,10 @@ public class BukkitHybridUtils extends HybridUtils {
} else { } else {
maxZ = 16; maxZ = 16;
} }
final int cbx = X << 4; final int cbx = X << 4;
final int cbz = Z << 4; final int cbz = Z << 4;
final int xb = (cbx) - bx; final int xb = (cbx) - bx;
final int zb = (cbz) - bz; final int zb = (cbz) - bz;
for (int x = minX; x <= maxX; x++) { for (int x = minX; x <= maxX; x++) {
@ -276,9 +276,10 @@ public class BukkitHybridUtils extends HybridUtils {
} }
}); });
} }
@Override @Override
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks) { public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2,
final PlotBlock[] blocks) {
final World world = BukkitUtil.getWorld(worldname); final World world = BukkitUtil.getWorld(worldname);
int count = 0; int count = 0;
for (int y = y1; y <= y2; y++) { for (int y = y1; y <= y2; y++) {
@ -301,7 +302,7 @@ public class BukkitHybridUtils extends HybridUtils {
} }
return count; return count;
} }
@Override @Override
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) { public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) {
final World world = BukkitUtil.getWorld(worldname); final World world = BukkitUtil.getWorld(worldname);

View File

@ -1,8 +1,10 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.ArrayList; import com.intellectualcrafters.plot.object.PlotInventory;
import java.util.List; import com.intellectualcrafters.plot.object.PlotItemStack;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
@ -12,72 +14,11 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import com.intellectualcrafters.plot.object.PlotInventory; import java.util.ArrayList;
import com.intellectualcrafters.plot.object.PlotItemStack; import java.util.List;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitInventoryUtil extends InventoryUtil { public class BukkitInventoryUtil extends InventoryUtil {
@Override
public void open(final PlotInventory inv) {
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < (inv.size * 9); i++) {
final PlotItemStack item = items[i];
if (item != null) {
inventory.setItem(i, getItem(item));
}
}
inv.player.setMeta("inventory", inv);
bp.player.openInventory(inventory);
}
@Override
public void close(final PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
inv.player.deleteMeta("inventory");
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
bp.player.closeInventory();
}
@Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) {
return;
}
opened.setItem(index, getItem(item));
bp.player.updateInventory();
}
public PlotItemStack getItem(final ItemStack item) {
if (item == null) {
return null;
}
final int id = item.getTypeId();
final short data = item.getDurability();
final int amount = item.getAmount();
String name = null;
String[] lore = null;
if (item.hasItemMeta()) {
final ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) {
name = meta.getDisplayName();
}
if (meta.hasLore()) {
final List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]);
}
}
return new PlotItemStack(id, data, amount, name, lore);
}
public static ItemStack getItem(final PlotItemStack item) { public static ItemStack getItem(final PlotItemStack item) {
if (item == null) { if (item == null) {
return null; return null;
@ -103,10 +44,68 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
return stack; return stack;
} }
@Override
public void open(final PlotInventory inv) {
final BukkitPlayer bp = (BukkitPlayer) inv.player;
final Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < inv.size * 9; i++) {
final PlotItemStack item = items[i];
if (item != null) {
inventory.setItem(i, getItem(item));
}
}
inv.player.setMeta("inventory", inv);
bp.player.openInventory(inventory);
}
@Override
public void close(final PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
inv.player.deleteMeta("inventory");
final BukkitPlayer bp = (BukkitPlayer) inv.player;
bp.player.closeInventory();
}
@Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
final BukkitPlayer bp = (BukkitPlayer) inv.player;
final InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) {
return;
}
opened.setItem(index, getItem(item));
bp.player.updateInventory();
}
public PlotItemStack getItem(final ItemStack item) {
if (item == null) {
return null;
}
final int id = item.getTypeId();
final short data = item.getDurability();
final int amount = item.getAmount();
String name = null;
String[] lore = null;
if (item.hasItemMeta()) {
final ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) {
name = meta.getDisplayName();
}
if (meta.hasLore()) {
final List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]);
}
}
return new PlotItemStack(id, data, amount, name, lore);
}
@Override @Override
public PlotItemStack[] getItems(final PlotPlayer player) { public PlotItemStack[] getItems(final PlotPlayer player) {
final BukkitPlayer bp = ((BukkitPlayer) player); final BukkitPlayer bp = (BukkitPlayer) player;
final PlayerInventory inv = bp.player.getInventory(); final PlayerInventory inv = bp.player.getInventory();
final PlotItemStack[] items = new PlotItemStack[36]; final PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++) { for (int i = 0; i < 36; i++) {
@ -114,14 +113,14 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
return items; return items;
} }
@Override @Override
public boolean isOpen(final PlotInventory inv) { public boolean isOpen(final PlotInventory inv) {
if (!inv.isOpen()) { if (!inv.isOpen()) {
return false; return false;
} }
final BukkitPlayer bp = ((BukkitPlayer) inv.player); final BukkitPlayer bp = (BukkitPlayer) inv.player;
final InventoryView opened = bp.player.getOpenInventory(); final InventoryView opened = bp.player.getOpenInventory();
return (inv.isOpen() && (opened.getType() == InventoryType.CRAFTING) && (opened.getTitle() == null)); return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null;
} }
} }

View File

@ -1,38 +1,39 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import com.intellectualcrafters.plot.object.PlotMessage; import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChatManager; import com.intellectualcrafters.plot.util.ChatManager;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> { public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
@Override @Override
public List<StringBuilder> builder() { public List<StringBuilder> builder() {
return new ArrayList<StringBuilder>(); return new ArrayList<>();
} }
@Override @Override
public void color(final PlotMessage m, final String color) { public void color(final PlotMessage m, final String color) {
final List<StringBuilder> parts = m.$(this); final List<StringBuilder> parts = m.$(this);
parts.get(parts.size() - 1).insert(0, color); parts.get(parts.size() - 1).insert(0, color);
} }
@Override @Override
public void tooltip(final PlotMessage m, final PlotMessage... tooltips) {} public void tooltip(final PlotMessage m, final PlotMessage... tooltips) {
}
@Override @Override
public void command(final PlotMessage m, final String command) {} public void command(final PlotMessage m, final String command) {
}
@Override @Override
public void text(final PlotMessage m, final String text) { public void text(final PlotMessage m, final String text) {
m.$(this).add(new StringBuilder(ChatColor.stripColor(text))); m.$(this).add(new StringBuilder(ChatColor.stripColor(text)));
} }
@Override @Override
public void send(final PlotMessage m, final PlotPlayer player) { public void send(final PlotMessage m, final PlotPlayer player) {
final StringBuilder built = new StringBuilder(); final StringBuilder built = new StringBuilder();
@ -41,8 +42,9 @@ public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
} }
player.sendMessage(built.toString()); player.sendMessage(built.toString());
} }
@Override @Override
public void suggest(final PlotMessage m, final String command) {} public void suggest(final PlotMessage m, final String command) {
}
} }

View File

@ -20,20 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.intellectualcrafters.jnbt.ByteArrayTag; import com.intellectualcrafters.jnbt.ByteArrayTag;
import com.intellectualcrafters.jnbt.CompoundTag; import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.IntTag; import com.intellectualcrafters.jnbt.IntTag;
@ -49,13 +35,28 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.object.schematic.StateWrapper; import com.plotsquared.bukkit.object.schematic.StateWrapper;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/** /**
* Schematic Handler * Schematic Handler
* *
*/ */
public class BukkitSchematicHandler extends SchematicHandler { public class BukkitSchematicHandler extends SchematicHandler {
@Override @Override
public void getCompoundTag(final String world, final Set<RegionWrapper> regions, final RunnableVal<CompoundTag> whenDone) { public void getCompoundTag(final String world, final Set<RegionWrapper> regions, final RunnableVal<CompoundTag> whenDone) {
// async // async
@ -66,7 +67,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
Location[] corners = MainUtil.getCorners(world, regions); Location[] corners = MainUtil.getCorners(world, regions);
final Location bot = corners[0]; final Location bot = corners[0];
final Location top = corners[1]; final Location top = corners[1];
final int width = (top.getX() - bot.getX()) + 1; final int width = (top.getX() - bot.getX()) + 1;
final int height = (top.getY() - bot.getY()) + 1; final int height = (top.getY() - bot.getY()) + 1;
final int length = (top.getZ() - bot.getZ()) + 1; final int length = (top.getZ() - bot.getZ()) + 1;
@ -83,7 +84,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types // Arrays of data types
final List<Tag> tileEntities = new ArrayList<Tag>(); final List<Tag> tileEntities = new ArrayList<>();
final byte[] blocks = new byte[width * height * length]; final byte[] blocks = new byte[width * height * length];
final byte[] blockData = new byte[width * height * length]; final byte[] blockData = new byte[width * height * length];
// Queue // Queue
@ -91,7 +92,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
TaskManager.runTask(new Runnable() { TaskManager.runTask(new Runnable() {
@Override @Override
public void run() { public void run() {
if (queue.size() == 0) { if (queue.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -124,7 +125,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
final int sy = pos1.getY(); final int sy = pos1.getY();
final int ey = pos2.getY(); final int ey = pos2.getY();
// Generate list of chunks // Generate list of chunks
final ArrayList<ChunkLoc> chunks = new ArrayList<ChunkLoc>(); final ArrayList<ChunkLoc> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) { for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) { for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z)); chunks.add(new ChunkLoc(x, z));
@ -136,7 +137,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
@Override @Override
public void run() { public void run() {
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < 20)) { while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < 20)) {
// save schematics // save schematics
final ChunkLoc chunk = chunks.remove(0); final ChunkLoc chunk = chunks.remove(0);
final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
@ -149,7 +150,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
int zzb = Z << 4; int zzb = Z << 4;
int xxt = xxb + 15; int xxt = xxb + 15;
int zzt = zzb + 15; int zzt = zzb + 15;
if (X == bcx) { if (X == bcx) {
xxb = p1x; xxb = p1x;
} }
@ -289,7 +290,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
for (final Entry<String, Tag> entry : rawTag.getValue().entrySet()) { for (final Entry<String, Tag> entry : rawTag.getValue().entrySet()) {
values.put(entry.getKey(), entry.getValue()); values.put(entry.getKey(), entry.getValue());
} }
values.put("id", new StringTag("id", wrapper.getId())); values.put("type", new StringTag("type", wrapper.getId()));
values.put("x", new IntTag("x", x)); values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y)); values.put("y", new IntTag("y", y));
values.put("z", new IntTag("z", z)); values.put("z", new IntTag("z", z));
@ -303,19 +304,22 @@ public class BukkitSchematicHandler extends SchematicHandler {
} }
} }
// For optimization reasons, we are not supporting custom data types // For optimization reasons, we are not supporting custom data types
// Especially since the most likely reason beyond this range is modded servers in which the blocks have NBT // Especially since the most likely reason beyond this range is modded servers in which the blocks
// if (id > 255) { // have NBT
// if (type > 255) {
// if (addBlocks == null) { // if (addBlocks == null) {
// addBlocks = new byte[(blocks.length >> 1) + 1]; // addBlocks = new byte[(blocks.length >> 1) + 1];
// } // }
// addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? (addBlocks[index >> 1] & 0xF0) | ((id >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((id >> 8) & 0xF) << 4)); // addBlocks[index >> 1] = (byte) (((index & 1) == 0) ?
// (addBlocks[index >> 1] & 0xF0) | ((type >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((type
// >> 8) & 0xF) << 4));
// } // }
blocks[index] = (byte) id; blocks[index] = (byte) id;
} }
} }
} }
} }
if (chunks.size() != 0) { if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1); TaskManager.runTaskLater(this, 1);
} else { } else {
regionTask.run(); regionTask.run();
@ -327,7 +331,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
} }
}); });
} }
@Override @Override
public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) { public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) {
new StateWrapper(ct).restoreTag(x, y, z, schem); new StateWrapper(ct).restoreTag(x, y, z, schem);

View File

@ -1,18 +1,5 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.file.YamlConfiguration; import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -22,12 +9,24 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.SetupObject; import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.SetupUtils;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
public class BukkitSetupUtils extends SetupUtils { public class BukkitSetupUtils extends SetupUtils {
@Override @Override
public void updateGenerators() { public void updateGenerators() {
if (SetupUtils.generators.size() > 0) { if (!SetupUtils.generators.isEmpty()) {
return; return;
} }
final String testWorld = "CheckingPlotSquaredGenerator"; final String testWorld = "CheckingPlotSquaredGenerator";
@ -48,7 +47,7 @@ public class BukkitSetupUtils extends SetupUtils {
} }
} }
} }
@Override @Override
public String setupWorld(final SetupObject object) { public String setupWorld(final SetupObject object) {
SetupUtils.manager.updateGenerators(); SetupUtils.manager.updateGenerators();
@ -127,8 +126,10 @@ public class BukkitSetupUtils extends SetupUtils {
e.printStackTrace(); e.printStackTrace();
} }
if (object.setupGenerator != null) { if (object.setupGenerator != null) {
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); .isEnabled()) {
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator);
setGenerator(world, object.setupGenerator); setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) { if (Bukkit.getWorld(world) != null) {
return world; return world;
@ -147,7 +148,8 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.createWorld(wc); Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator); setGenerator(world, object.setupGenerator);
} else { } else {
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal"); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) { if (Bukkit.getWorld(world) != null) {
return world; return world;
@ -163,9 +165,9 @@ public class BukkitSetupUtils extends SetupUtils {
} }
return object.world; return object.world;
} }
public void setGenerator(final String world, final String generator) { public void setGenerator(final String world, final String generator) {
if ((Bukkit.getWorlds().size() == 0) || !Bukkit.getWorlds().get(0).getName().equals(world)) { if ((Bukkit.getWorlds().isEmpty()) || !Bukkit.getWorlds().get(0).getName().equals(world)) {
return; return;
} }
final File file = new File("bukkit.yml").getAbsoluteFile(); final File file = new File("bukkit.yml").getAbsoluteFile();
@ -177,10 +179,10 @@ public class BukkitSetupUtils extends SetupUtils {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
public String getGenerator(final PlotArea plotworld) { public String getGenerator(final PlotArea plotworld) {
if (SetupUtils.generators.size() == 0) { if (SetupUtils.generators.isEmpty()) {
updateGenerators(); updateGenerators();
} }
final World world = Bukkit.getWorld(plotworld.worldname); final World world = Bukkit.getWorld(plotworld.worldname);

View File

@ -1,41 +1,41 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import org.bukkit.Bukkit;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.BukkitMain; import com.plotsquared.bukkit.BukkitMain;
import org.bukkit.Bukkit;
public class BukkitTaskManager extends TaskManager { public class BukkitTaskManager extends TaskManager {
@Override @Override
public int taskRepeat(final Runnable r, final int interval) { public int taskRepeat(final Runnable r, final int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval); return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
} }
@SuppressWarnings("deprecation") @Override @SuppressWarnings("deprecation") @Override
public int taskRepeatAsync(final Runnable r, final int interval) { public int taskRepeatAsync(final Runnable r, final int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval); return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
} }
@Override @Override
public void taskAsync(final Runnable r) { public void taskAsync(final Runnable r) {
BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId(); BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId();
} }
@Override @Override
public void task(final Runnable r) { public void task(final Runnable r) {
BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId(); BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId();
} }
@Override @Override
public void taskLater(final Runnable r, final int delay) { public void taskLater(final Runnable r, final int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId(); BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId();
} }
@Override @Override
public void taskLaterAsync(final Runnable r, final int delay) { public void taskLaterAsync(final Runnable r, final int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay); BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay);
} }
@Override @Override
public void cancelTask(final int task) { public void cancelTask(final int task) {
if (task != -1) { if (task != -1) {

View File

@ -1,8 +1,17 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.Arrays; import com.intellectualcrafters.plot.object.Location;
import java.util.List; import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -23,26 +32,17 @@ import org.bukkit.material.Tree;
import org.bukkit.material.WoodenStep; import org.bukkit.material.WoodenStep;
import org.bukkit.material.Wool; import org.bukkit.material.Wool;
import com.intellectualcrafters.plot.object.Location; import java.util.Arrays;
import com.intellectualcrafters.plot.object.PlotBlock; import java.util.List;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitUtil extends WorldUtil { public class BukkitUtil extends WorldUtil {
private static String lastString = null; private static String lastString = null;
private static World lastWorld = null; private static World lastWorld = null;
private static Player lastPlayer = null; private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null; private static PlotPlayer lastPlotPlayer = null;
public static void removePlayer(final String plr) { public static void removePlayer(final String plr) {
lastPlayer = null; lastPlayer = null;
lastPlotPlayer = null; lastPlotPlayer = null;
@ -56,7 +56,7 @@ public class BukkitUtil extends WorldUtil {
player.loadData(); player.loadData();
return new BukkitPlayer(player, true); return new BukkitPlayer(player, true);
} }
public static PlotPlayer getPlayer(final Player player) { public static PlotPlayer getPlayer(final Player player) {
if (player == lastPlayer) { if (player == lastPlayer) {
return lastPlotPlayer; return lastPlotPlayer;
@ -71,15 +71,15 @@ public class BukkitUtil extends WorldUtil {
lastPlayer = player; lastPlayer = player;
return lastPlotPlayer; return lastPlotPlayer;
} }
public static Location getLocation(final org.bukkit.Location loc) { public static Location getLocation(final org.bukkit.Location loc) {
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ())); return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()));
} }
public static org.bukkit.Location getLocation(final Location loc) { public static org.bukkit.Location getLocation(final Location loc) {
return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()); return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ());
} }
public static World getWorld(final String string) { public static World getWorld(final String string) {
if (StringMan.isEqual(string, lastString)) { if (StringMan.isEqual(string, lastString)) {
if (lastWorld != null) { if (lastWorld != null) {
@ -91,36 +91,37 @@ public class BukkitUtil extends WorldUtil {
lastWorld = world; lastWorld = world;
return world; return world;
} }
public static String getWorld(final Entity entity) { public static String getWorld(final Entity entity) {
return entity.getWorld().getName(); return entity.getWorld().getName();
} }
public static List<Entity> getEntities(final String worldname) { public static List<Entity> getEntities(final String worldname) {
return getWorld(worldname).getEntities(); return getWorld(worldname).getEntities();
} }
public static Location getLocation(final Entity entity) { public static Location getLocation(final Entity entity) {
final org.bukkit.Location loc = entity.getLocation(); final org.bukkit.Location loc = entity.getLocation();
final String world = loc.getWorld().getName(); final String world = loc.getWorld().getName();
return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
} }
public static Location getLocationFull(final Entity entity) { public static Location getLocationFull(final Entity entity) {
final org.bukkit.Location loc = entity.getLocation(); final org.bukkit.Location loc = entity.getLocation();
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()), loc.getYaw(), loc.getPitch()); return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()),
loc.getYaw(), loc.getPitch());
} }
@Override @Override
public boolean isWorld(final String world) { public boolean isWorld(final String world) {
return getWorld(world) != null; return getWorld(world) != null;
} }
@Override @Override
public String getBiome(final String world, final int x, final int z) { public String getBiome(final String world, final int x, final int z) {
return getWorld(world).getBiome(x, z).name(); return getWorld(world).getBiome(x, z).name();
} }
@Override @Override
public void setSign(final String worldname, final int x, final int y, final int z, final String[] lines) { public void setSign(final String worldname, final int x, final int y, final int z, final String[] lines) {
final World world = getWorld(worldname); final World world = getWorld(worldname);
@ -128,7 +129,7 @@ public class BukkitUtil extends WorldUtil {
// block.setType(Material.AIR); // block.setType(Material.AIR);
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
final BlockState blockstate = block.getState(); final BlockState blockstate = block.getState();
if ((blockstate instanceof Sign)) { if (blockstate instanceof Sign) {
final Sign sign = (Sign) blockstate; final Sign sign = (Sign) blockstate;
for (int i = 0; i < lines.length; i++) { for (int i = 0; i < lines.length; i++) {
sign.setLine(i, lines[i]); sign.setLine(i, lines[i]);
@ -142,7 +143,7 @@ public class BukkitUtil extends WorldUtil {
}, 20); }, 20);
} }
} }
@Override @Override
public String[] getSign(final Location loc) { public String[] getSign(final Location loc) {
final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ()); final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ());
@ -154,18 +155,18 @@ public class BukkitUtil extends WorldUtil {
} }
return null; return null;
} }
@Override @Override
public Location getSpawn(final String world) { public Location getSpawn(final String world) {
final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); final org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
} }
@Override @Override
public int getHeighestBlock(final String world, final int x, final int z) { public int getHeighestBlock(final String world, final int x, final int z) {
return getWorld(world).getHighestBlockAt(x, z).getY(); return getWorld(world).getHighestBlockAt(x, z).getY();
} }
@Override @Override
public int getBiomeFromString(final String biomeStr) { public int getBiomeFromString(final String biomeStr) {
try { try {
@ -178,7 +179,7 @@ public class BukkitUtil extends WorldUtil {
return -1; return -1;
} }
} }
@Override @Override
public String[] getBiomeList() { public String[] getBiomeList() {
final Biome[] biomes = Biome.values(); final Biome[] biomes = Biome.values();
@ -188,7 +189,7 @@ public class BukkitUtil extends WorldUtil {
} }
return list; return list;
} }
@Override @Override
public boolean addItems(final String worldname, final PlotItem items) { public boolean addItems(final String worldname, final PlotItem items) {
final World world = getWorld(worldname); final World world = getWorld(worldname);
@ -197,8 +198,8 @@ public class BukkitUtil extends WorldUtil {
return false; return false;
} }
final BlockState state = block.getState(); final BlockState state = block.getState();
if ((state != null) && (state instanceof InventoryHolder)) { if (state instanceof InventoryHolder) {
final InventoryHolder holder = ((InventoryHolder) state); final InventoryHolder holder = (InventoryHolder) state;
final Inventory inv = holder.getInventory(); final Inventory inv = holder.getInventory();
for (int i = 0; i < items.id.length; i++) { for (int i = 0; i < items.id.length; i++) {
final ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]); final ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]);
@ -209,24 +210,23 @@ public class BukkitUtil extends WorldUtil {
} }
return false; return false;
} }
@Override @Override
public boolean isBlockSolid(final PlotBlock block) { public boolean isBlockSolid(final PlotBlock block) {
try { try {
final Material material = Material.getMaterial(block.id); final Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity()) { if (material.isBlock() && material.isSolid() && !material.hasGravity()) {
final Class<? extends MaterialData> data = material.getData(); final Class<? extends MaterialData> data = material.getData();
if ((data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()) if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()
|| data.equals(Tree.class) || data.equals(Tree.class)
|| data.equals(Sandstone.class) || data.equals(Sandstone.class)
|| data.equals(Wool.class) || data.equals(Wool.class)
|| data.equals(Step.class) || data.equals(Step.class)
|| data.equals(WoodenStep.class)) { || data.equals(WoodenStep.class)) {
switch (material) { switch (material) {
case NOTE_BLOCK: case NOTE_BLOCK:
case MOB_SPAWNER: { case MOB_SPAWNER:
return false; return false;
}
default: default:
return true; return true;
} }
@ -237,7 +237,7 @@ public class BukkitUtil extends WorldUtil {
return false; return false;
} }
} }
@Override @Override
public String getClosestMatchingName(final PlotBlock block) { public String getClosestMatchingName(final PlotBlock block) {
try { try {
@ -246,16 +246,15 @@ public class BukkitUtil extends WorldUtil {
return null; return null;
} }
} }
@Override @Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) { public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try { try {
final Material material = Material.valueOf(name.toUpperCase()); final Material material = Material.valueOf(name.toUpperCase());
return new StringComparison<PlotBlock>().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0)); return new StringComparison<PlotBlock>().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0));
} catch (Exception e) {} } catch (IllegalArgumentException e) {
}
try { try {
double match;
short id;
byte data; byte data;
final String[] split = name.split(":"); final String[] split = name.split(":");
if (split.length == 2) { if (split.length == 2) {
@ -264,22 +263,25 @@ public class BukkitUtil extends WorldUtil {
} else { } else {
data = 0; data = 0;
} }
double match;
short id;
if (MathMan.isInteger(split[0])) { if (MathMan.isInteger(split[0])) {
id = Short.parseShort(split[0]); id = Short.parseShort(split[0]);
match = 0; match = 0;
} else { } else {
final StringComparison<Material>.ComparisonResult comparison = new StringComparison<Material>(name, Material.values()).getBestMatchAdvanced(); final StringComparison<Material>.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced();
match = comparison.match; match = comparison.match;
id = (short) comparison.best.getId(); id = (short) comparison.best.getId();
} }
final PlotBlock block = new PlotBlock(id, data); final PlotBlock block = new PlotBlock(id, data);
final StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>(); final StringComparison<PlotBlock> outer = new StringComparison<>();
return outer.new ComparisonResult(match, block); return outer.new ComparisonResult(match, block);
} catch (final Exception e) {} } catch (NumberFormatException e) {
}
return null; return null;
} }
@Override @Override
public void setBiomes(final String worldname, RegionWrapper region, final String biomeStr) { public void setBiomes(final String worldname, RegionWrapper region, final String biomeStr) {
final World world = getWorld(worldname); final World world = getWorld(worldname);
@ -290,7 +292,7 @@ public class BukkitUtil extends WorldUtil {
} }
} }
} }
@Override @Override
public PlotBlock getBlock(final Location loc) { public PlotBlock getBlock(final Location loc) {
final World world = getWorld(loc.getWorld()); final World world = getWorld(loc.getWorld());
@ -300,7 +302,7 @@ public class BukkitUtil extends WorldUtil {
} }
return new PlotBlock((short) block.getTypeId(), block.getData()); return new PlotBlock((short) block.getTypeId(), block.getData());
} }
@Override @Override
public String getMainWorld() { public String getMainWorld() {
return Bukkit.getWorlds().get(0).getName(); return Bukkit.getWorlds().get(0).getName();

View File

@ -20,6 +20,15 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -41,17 +50,8 @@ import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
public class Metrics { public class Metrics {
/** /**
* The current revision number * The current revision number
*/ */
@ -85,7 +85,7 @@ public class Metrics {
*/ */
private final File configurationFile; private final File configurationFile;
/** /**
* Unique server id * Unique server type
*/ */
private final String guid; private final String guid;
/** /**
@ -100,7 +100,7 @@ public class Metrics {
* The scheduled task * The scheduled task
*/ */
private volatile BukkitTask task = null; private volatile BukkitTask task = null;
public Metrics(final Plugin plugin) throws IOException { public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) { if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null"); throw new IllegalArgumentException("Plugin cannot be null");
@ -122,7 +122,7 @@ public class Metrics {
guid = configuration.getString("guid"); guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false); debug = configuration.getBoolean("debug", false);
} }
/** /**
* GZip compress a string of bytes * GZip compress a string of bytes
* *
@ -142,12 +142,13 @@ public class Metrics {
if (gzos != null) { if (gzos != null) {
try { try {
gzos.close(); gzos.close();
} catch (final IOException ignore) {} } catch (final IOException ignore) {
}
} }
} }
return baos.toByteArray(); return baos.toByteArray();
} }
/** /**
* Appends a json encoded key/value pair to the given string builder. * Appends a json encoded key/value pair to the given string builder.
* *
@ -157,7 +158,7 @@ public class Metrics {
* *
* @throws UnsupportedEncodingException * @throws UnsupportedEncodingException
*/ */
private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException { private static void appendJSONPair(final StringBuilder json, final String key, final String value) {
boolean isValueNumeric = false; boolean isValueNumeric = false;
try { try {
if (value.equals("0") || !value.endsWith("0")) { if (value.equals("0") || !value.endsWith("0")) {
@ -178,7 +179,7 @@ public class Metrics {
json.append(escapeJSON(value)); json.append(escapeJSON(value));
} }
} }
/** /**
* Escape a string to create a valid JSON string * Escape a string to create a valid JSON string
* *
@ -222,7 +223,7 @@ public class Metrics {
builder.append('"'); builder.append('"');
return builder.toString(); return builder.toString();
} }
/** /**
* Encode text as UTF-8 * Encode text as UTF-8
* *
@ -233,7 +234,7 @@ public class Metrics {
private static String urlEncode(final String text) throws UnsupportedEncodingException { private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} }
/** /**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned. * website. Plotters can be added to the graph object returned.
@ -253,7 +254,7 @@ public class Metrics {
// and return back // and return back
return graph; return graph;
} }
/** /**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
* *
@ -265,7 +266,7 @@ public class Metrics {
} }
graphs.add(graph); graphs.add(graph);
} }
/** /**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
@ -286,7 +287,7 @@ public class Metrics {
// Begin hitting the server with glorious data // Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true; private boolean firstPost = true;
@Override @Override
public void run() { public void run() {
try { try {
@ -297,7 +298,7 @@ public class Metrics {
// Disable Task, if it is running and the // Disable Task, if it is running and the
// server // server
// owner decided to opt-out // owner decided to opt-out
if (isOptOut() && (task != null)) { if (isOptOut() && task != null) {
task.cancel(); task.cancel();
task = null; task = null;
// Tell all plotters to stop gathering // Tell all plotters to stop gathering
@ -330,7 +331,7 @@ public class Metrics {
return true; return true;
} }
} }
/** /**
* Has the server owner denied plugin metrics? * Has the server owner denied plugin metrics?
* *
@ -355,7 +356,7 @@ public class Metrics {
return configuration.getBoolean("opt-out", false); return configuration.getBoolean("opt-out", false);
} }
} }
/** /**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
* *
@ -377,7 +378,7 @@ public class Metrics {
} }
} }
} }
/** /**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
* *
@ -400,7 +401,7 @@ public class Metrics {
} }
} }
} }
/** /**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
* *
@ -417,7 +418,7 @@ public class Metrics {
// return => base/plugins/PluginMetrics/config.yml // return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
/** /**
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website
*/ */
@ -436,11 +437,12 @@ public class Metrics {
int playersOnline = 0; int playersOnline = 0;
try { try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) { if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).size(); playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).size();
} else { } else {
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).length; playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).length;
} }
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {} } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
}
// END server software specific section -- all code below does not use // END server software specific section -- all code below does not use
// any code outside of this class / Java // any code outside of this class / Java
// Construct the post data // Construct the post data
@ -472,7 +474,7 @@ public class Metrics {
if (isPing) { if (isPing) {
appendJSONPair(json, "ping", "1"); appendJSONPair(json, "ping", "1");
} }
if (graphs.size() > 0) { if (!graphs.isEmpty()) {
synchronized (graphs) { synchronized (graphs) {
json.append(','); json.append(',');
json.append('"'); json.append('"');
@ -526,16 +528,15 @@ public class Metrics {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
} }
// Write the data // Write the data
final OutputStream os = connection.getOutputStream(); String response;
os.write(compressed); try (OutputStream os = connection.getOutputStream();
os.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
// Now read the response os.write(compressed);
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); os.flush();
String response = reader.readLine(); // Now read the response
// close resources response = reader.readLine();
os.close(); }
reader.close(); if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) { if (response == null) {
response = "null"; response = "null";
} else if (response.startsWith("7")) { } else if (response.startsWith("7")) {
@ -544,7 +545,7 @@ public class Metrics {
throw new IOException(response); throw new IOException(response);
} else { } else {
// Is this the first update this hour? // Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour")) { if ("1".equals(response) || response.contains("This is your first update this hour")) {
synchronized (graphs) { synchronized (graphs) {
for (final Graph graph : graphs) { for (final Graph graph : graphs) {
for (final Plotter plotter : graph.getPlotters()) { for (final Plotter plotter : graph.getPlotters()) {
@ -555,7 +556,7 @@ public class Metrics {
} }
} }
} }
/** /**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests * Check if mineshafter is present. If it is, we need to bypass it to send POST requests
* *
@ -565,15 +566,16 @@ public class Metrics {
try { try {
Class.forName("mineshafter.MineServer"); Class.forName("mineshafter.MineServer");
return true; return true;
} catch (final Exception e) { } catch (ClassNotFoundException e) {
return false; return false;
} }
} }
/** /**
* Represents a custom graph on the website * Represents a custom graph on the website
*/ */
public static class Graph { public static class Graph {
/** /**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected * rejected
@ -582,12 +584,12 @@ public class Metrics {
/** /**
* The set of plotters that are contained within this graph * The set of plotters that are contained within this graph
*/ */
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>(); private final Set<Plotter> plotters = new LinkedHashSet<>();
private Graph(final String name) { private Graph(final String name) {
this.name = name; this.name = name;
} }
/** /**
* Gets the graph's name * Gets the graph's name
* *
@ -596,7 +598,7 @@ public class Metrics {
public String getName() { public String getName() {
return name; return name;
} }
/** /**
* Add a plotter to the graph, which will be used to plot entries * Add a plotter to the graph, which will be used to plot entries
* *
@ -605,7 +607,7 @@ public class Metrics {
public void addPlotter(final Plotter plotter) { public void addPlotter(final Plotter plotter) {
plotters.add(plotter); plotters.add(plotter);
} }
/** /**
* Remove a plotter from the graph * Remove a plotter from the graph
* *
@ -614,7 +616,7 @@ public class Metrics {
public void removePlotter(final Plotter plotter) { public void removePlotter(final Plotter plotter) {
plotters.remove(plotter); plotters.remove(plotter);
} }
/** /**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph * Gets an <b>unmodifiable</b> set of the plotter objects in the graph
* *
@ -623,12 +625,12 @@ public class Metrics {
public Set<Plotter> getPlotters() { public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(plotters); return Collections.unmodifiableSet(plotters);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return name.hashCode(); return name.hashCode();
} }
@Override @Override
public boolean equals(final Object object) { public boolean equals(final Object object) {
if (!(object instanceof Graph)) { if (!(object instanceof Graph)) {
@ -637,29 +639,31 @@ public class Metrics {
final Graph graph = (Graph) object; final Graph graph = (Graph) object;
return graph.name.equals(name); return graph.name.equals(name);
} }
/** /**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running. * Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/ */
protected void onOptOut() {} protected void onOptOut() {
}
} }
/** /**
* Interface used to collect custom data for a plugin * Interface used to collect custom data for a plugin
*/ */
public static abstract class Plotter { public static abstract class Plotter {
/** /**
* The plot's name * The plot's name
*/ */
private final String name; private final String name;
/** /**
* Construct a plotter with the default plot name * Construct a plotter with the default plot name
*/ */
public Plotter() { public Plotter() {
this("Default"); this("Default");
} }
/** /**
* Construct a plotter with a specific plot name * Construct a plotter with a specific plot name
* *
@ -668,7 +672,7 @@ public class Metrics {
public Plotter(final String name) { public Plotter(final String name) {
this.name = name; this.name = name;
} }
/** /**
* Get the current value for the plotted point. Since this function defers to an external function it may or may * Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
@ -677,7 +681,7 @@ public class Metrics {
* @return the current value for the point to be plotted. * @return the current value for the point to be plotted.
*/ */
public abstract int getValue(); public abstract int getValue();
/** /**
* Get the column name for the plotted point * Get the column name for the plotted point
* *
@ -686,24 +690,25 @@ public class Metrics {
public String getColumnName() { public String getColumnName() {
return name; return name;
} }
/** /**
* Called after the website graphs have been updated * Called after the website graphs have been updated
*/ */
public void reset() {} public void reset() {
}
@Override @Override
public int hashCode() { public int hashCode() {
return getColumnName().hashCode(); return getColumnName().hashCode();
} }
@Override @Override
public boolean equals(final Object object) { public boolean equals(final Object object) {
if (!(object instanceof Plotter)) { if (!(object instanceof Plotter)) {
return false; return false;
} }
final Plotter plotter = (Plotter) object; final Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && (plotter.getValue() == getValue()); return plotter.name.equals(name) && plotter.getValue() == getValue();
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -8,25 +8,25 @@ import static com.intellectualcrafters.plot.util.ReflectionUtils.getUtilClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.makeConstructor; import static com.intellectualcrafters.plot.util.ReflectionUtils.makeConstructor;
import static com.intellectualcrafters.plot.util.ReflectionUtils.makeMethod; import static com.intellectualcrafters.plot.util.ReflectionUtils.makeMethod;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.UUID;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.UUID;
public class OfflinePlayerUtil { public class OfflinePlayerUtil {
public static Player loadPlayer(final String name) { public static Player loadPlayer(final String name) {
return loadPlayer(Bukkit.getOfflinePlayer(name)); return loadPlayer(Bukkit.getOfflinePlayer(name));
} }
public static Player loadPlayer(final UUID id) { public static Player loadPlayer(final UUID id) {
return loadPlayer(Bukkit.getOfflinePlayer(id)); return loadPlayer(Bukkit.getOfflinePlayer(id));
} }
public static Player loadPlayer(final OfflinePlayer player) { public static Player loadPlayer(final OfflinePlayer player) {
if (player == null) { if (player == null) {
return null; return null;
@ -36,27 +36,26 @@ public class OfflinePlayerUtil {
} }
return loadPlayer(player.getUniqueId(), player.getName()); return loadPlayer(player.getUniqueId(), player.getName());
} }
private static Player loadPlayer(final UUID id, final String name) { private static Player loadPlayer(final UUID id, final String name) {
final Object server = getMinecraftServer(); final Object server = getMinecraftServer();
final Object interactManager = newPlayerInteractManager(); final Object interactManager = newPlayerInteractManager();
final Object worldServer = getWorldServer(); final Object worldServer = getWorldServer();
final Object profile = newGameProfile(id, name); final Object profile = newGameProfile(id, name);
final Class<?> entityPlayerClass = getNmsClass("EntityPlayer"); final Class<?> entityPlayerClass = getNmsClass("EntityPlayer");
final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"),
getNmsClass("PlayerInteractManager")); getUtilClass("com.mojang.authlib.GameProfile"),
getNmsClass("PlayerInteractManager"));
final Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); final Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
final Player player = (Player) getBukkitEntity(entityPlayer); return (Player) getBukkitEntity(entityPlayer);
return player;
} }
private static Object newGameProfile(final UUID id, final String name) { private static Object newGameProfile(final UUID id, final String name) {
final Class<?> gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); final Class<?> gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile");
if (gameProfileClass == null) { //Before uuids if (gameProfileClass == null) { //Before uuids
return name; return name;
} }
Constructor gameProfileConstructor = null; Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
if (gameProfileConstructor == null) { //Verson has string constructor if (gameProfileConstructor == null) { //Verson has string constructor
gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class); gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name); return callConstructor(gameProfileConstructor, id.toString(), name);
@ -64,7 +63,7 @@ public class OfflinePlayerUtil {
return callConstructor(gameProfileConstructor, id, name); return callConstructor(gameProfileConstructor, id, name);
} }
} }
private static Object newPlayerInteractManager() { private static Object newPlayerInteractManager() {
final Object worldServer = getWorldServer(); final Object worldServer = getWorldServer();
final Class<?> playerInteractClass = getNmsClass("PlayerInteractManager"); final Class<?> playerInteractClass = getNmsClass("PlayerInteractManager");
@ -72,20 +71,20 @@ public class OfflinePlayerUtil {
final Constructor c = makeConstructor(playerInteractClass, worldClass); final Constructor c = makeConstructor(playerInteractClass, worldClass);
return callConstructor(c, worldServer); return callConstructor(c, worldServer);
} }
private static Object getWorldServer() { private static Object getWorldServer() {
final Object server = getMinecraftServer(); final Object server = getMinecraftServer();
final Class<?> minecraftServerClass = getNmsClass("MinecraftServer"); final Class<?> minecraftServerClass = getNmsClass("MinecraftServer");
final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class);
return callMethod(getWorldServer, server, 0); return callMethod(getWorldServer, server, 0);
} }
//NMS Utils //NMS Utils
private static Object getMinecraftServer() { private static Object getMinecraftServer() {
return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer()); return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer());
} }
private static Entity getBukkitEntity(final Object o) { private static Entity getBukkitEntity(final Object o) {
final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity");
return callMethod(getBukkitEntity, o); return callMethod(getBukkitEntity, o);

View File

@ -1,148 +0,0 @@
package com.plotsquared.bukkit.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
/**
* Reflection Utilities for minecraft
*
*/
public class ReflectionUtil {
public static Class<?> getNmsClass(final String name) {
final String className = "net.minecraft.server." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getCbClass(final String name) {
final String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getUtilClass(final String name) {
try {
return Class.forName(name); //Try before 1.8 first
} catch (final ClassNotFoundException ex) {
try {
return Class.forName("net.minecraft.util." + name); //Not 1.8
} catch (final ClassNotFoundException ex2) {
return null;
}
}
}
public static String getVersion() {
final String packageName = Bukkit.getServer().getClass().getPackage().getName();
return packageName.substring(packageName.lastIndexOf('.') + 1);
}
public static Object getHandle(final Object wrapper) {
final Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
return callMethod(getHandle, wrapper);
}
//Utils
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters) {
try {
return clazz.getDeclaredMethod(methodName, paramaters);
} catch (final NoSuchMethodException ex) {
return null;
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters) {
if (method == null) {
throw new RuntimeException("No such method");
}
method.setAccessible(true);
try {
return (T) method.invoke(instance, paramaters);
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes) {
try {
return (Constructor<T>) clazz.getConstructor(paramaterTypes);
} catch (final NoSuchMethodException ex) {
return null;
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters) {
if (constructor == null) {
throw new RuntimeException("No such constructor");
}
constructor.setAccessible(true);
try {
return constructor.newInstance(paramaters);
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static Field makeField(final Class<?> clazz, final String name) {
try {
return clazz.getDeclaredField(name);
} catch (final NoSuchFieldException ex) {
return null;
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T getField(final Field field, final Object instance) {
if (field == null) {
throw new RuntimeException("No such field");
}
field.setAccessible(true);
try {
return (T) field.get(instance);
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static void setField(final Field field, final Object instance, final Object value) {
if (field == null) {
throw new RuntimeException("No such field");
}
field.setAccessible(true);
try {
field.set(instance, value);
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static Class<?> getClass(final String name) {
try {
return Class.forName(name);
} catch (final ClassNotFoundException ex) {
return null;
}
}
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass) {
try {
return Class.forName(name).asSubclass(superClass);
} catch (ClassCastException | ClassNotFoundException ex) {
return null;
}
}
}

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