diff --git a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/src/main/java/com/intellectualcrafters/configuration/MemorySection.java index 2e19c8ae0..bce9578f5 100644 --- a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java +++ b/src/main/java/com/intellectualcrafters/configuration/MemorySection.java @@ -16,7 +16,56 @@ public class MemorySection implements ConfigurationSection { private final ConfigurationSection parent; private final String path; private final String fullPath; - + + /** + * Creates an empty MemorySection for use as a root {@link Configuration} + * section. + *

+ * Note that calling this without being yourself a {@link Configuration} + * will throw an exception! + * + * @throws IllegalStateException Thrown if this is not a {@link + * Configuration} root. + */ + protected MemorySection() { + if (!(this instanceof Configuration)) { + throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); + } + + path = ""; + fullPath = ""; + parent = null; + root = (Configuration) this; + } + + /** + * Creates an empty MemorySection with the specified parent and path. + * + * @param parent Parent section that contains this own section. + * @param path Path that you may access this section from via the root + * {@link Configuration}. + * @throws IllegalArgumentException Thrown is parent or path is null, or + * if parent contains no root Configuration. + */ + protected MemorySection(final ConfigurationSection parent, final String path) { + if (parent == null) { + throw new NullPointerException("Parent may not be null"); + } + if (path == null) { + throw new NullPointerException("Path may not be null"); + } + + this.path = path; + this.parent = parent; + root = parent.getRoot(); + + if (root == null) { + throw new NullPointerException("Path may not be orphaned"); + } + + fullPath = createPath(parent, path); + } + public static double toDouble(final Object obj, final double def) { if (obj instanceof Number) { return ((Number) obj).doubleValue(); @@ -28,7 +77,7 @@ public class MemorySection implements ConfigurationSection { } } else if (obj instanceof List) { final List val = ((List) obj); - if (val.size() > 0) { + if (!val.isEmpty()) { return toDouble(val.get(0), def); } } @@ -46,7 +95,7 @@ public class MemorySection implements ConfigurationSection { } } else if (obj instanceof List) { final List val = ((List) obj); - if (val.size() > 0) { + if (!val.isEmpty()) { return toInt(val.get(0), def); } } @@ -64,7 +113,7 @@ public class MemorySection implements ConfigurationSection { } } else if (obj instanceof List) { final List val = ((List) obj); - if (val.size() > 0) { + if (!val.isEmpty()) { return toLong(val.get(0), def); } } @@ -72,87 +121,95 @@ public class MemorySection implements ConfigurationSection { } /** - * Creates an empty MemorySection for use as a root {@link Configuration} - * section. + * Creates a full path to the given {@link ConfigurationSection} from its + * root {@link Configuration}. *

- * Note that calling this without being yourself a {@link Configuration} - * will throw an exception! + * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. * - * @throws IllegalStateException Thrown if this is not a {@link - * Configuration} root. + * @param section Section to create a path for. + * @param key Name of the specified section. + * @return Full path of the section from its root. */ - protected MemorySection() { - if (!(this instanceof Configuration)) { - throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); - } - - path = ""; - fullPath = ""; - parent = null; - root = (Configuration) this; + public static String createPath(final ConfigurationSection section, final String key) { + return createPath(section, key, (section == null) ? null : section.getRoot()); } /** - * Creates an empty MemorySection with the specified parent and path. + * Creates a relative path to the given {@link ConfigurationSection} from + * the given relative section. + *

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

- * You may use this method for any given {@link ConfigurationSection}, not - * only {@link MemorySection}. - * - * @param section Section to create a path for. - * @param key Name of the specified section. - * @return Full path of the section from its root. - */ - public static String createPath(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. - *

- * You may use this method for any given {@link ConfigurationSection}, not - * only {@link MemorySection}. - * - * @param section Section to create a path for. - * @param key Name of the specified section. - * @param relativeTo Section to create the path relative to. - * @return Full path of the section from its root. - */ - public static String createPath(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo) { - if (section == null) { - throw new NullPointerException("Cannot create path without a section"); - } - final Configuration root = section.getRoot(); - if (root == null) { - throw new IllegalStateException("Cannot create path without a root"); - } - final char separator = root.options().pathSeparator(); - - final StringBuilder builder = new StringBuilder(); - for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) { - if (builder.length() > 0) { - builder.insert(0, separator); - } - - builder.insert(0, parent.getName()); - } - - if ((key != null) && (key.length() > 0)) { - if (builder.length() > 0) { - builder.append(separator); - } - - builder.append(key); - } - - return builder.toString(); - } - @Override public String toString() { final Configuration root = getRoot(); diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java index a1b1d7d78..9f99def54 100644 --- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java +++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java @@ -1,22 +1,20 @@ package com.intellectualcrafters.configuration.file; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.Map; - -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.error.YAMLException; -import org.yaml.snakeyaml.representer.Representer; - import com.intellectualcrafters.configuration.Configuration; import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.InvalidConfigurationException; import com.intellectualcrafters.plot.PS; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.representer.Representer; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.Map; /** * An implementation of {@link Configuration} which saves all files in Yaml. @@ -28,139 +26,7 @@ public class YamlConfiguration extends FileConfiguration { private final DumperOptions yamlOptions = new DumperOptions(); private final Representer yamlRepresenter = new YamlRepresenter(); private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); - - @Override - @SuppressWarnings("deprecation") - public String saveToString() { - yamlOptions.setIndent(options().indent()); - yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - yamlOptions.setAllowUnicode(SYSTEM_UTF); - yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - - final String header = buildHeader(); - String dump = yaml.dump(getValues(false)); - - if (dump.equals(BLANK_CONFIG)) { - dump = ""; - } - - return header + dump; - } - - @Override - public void loadFromString(final String contents) throws InvalidConfigurationException { - if (contents == null) { - throw new NullPointerException("Contents cannot be null"); - } - - Map input; - try { - input = (Map) yaml.load(contents); - } catch (final YAMLException e) { - throw new InvalidConfigurationException(e); - } catch (final ClassCastException e) { - throw new InvalidConfigurationException("Top level is not a Map."); - } - - final String header = parseHeader(contents); - if (header.length() > 0) { - options().header(header); - } - - if (input != null) { - convertMapsToSections(input, this); - } - } - - protected void convertMapsToSections(final Map input, final ConfigurationSection section) { - for (final Map.Entry entry : input.entrySet()) { - final String key = entry.getKey().toString(); - final Object value = entry.getValue(); - - if (value instanceof Map) { - convertMapsToSections((Map) value, section.createSection(key)); - } else { - section.set(key, value); - } - } - } - - protected String parseHeader(final String input) { - final String[] lines = input.split("\r?\n", -1); - final StringBuilder result = new StringBuilder(); - boolean readingHeader = true; - boolean foundHeader = false; - - for (int i = 0; (i < lines.length) && (readingHeader); i++) { - final String line = lines[i]; - - if (line.startsWith(COMMENT_PREFIX)) { - if (i > 0) { - result.append("\n"); - } - - if (line.length() > COMMENT_PREFIX.length()) { - result.append(line.substring(COMMENT_PREFIX.length())); - } - - foundHeader = true; - } else if ((foundHeader) && (line.length() == 0)) { - result.append("\n"); - } else if (foundHeader) { - readingHeader = false; - } - } - - return result.toString(); - } - - @Override - protected String buildHeader() { - final String header = options().header(); - - if (options().copyHeader()) { - final Configuration def = getDefaults(); - - if ((def != null) && (def instanceof FileConfiguration)) { - final FileConfiguration filedefaults = (FileConfiguration) def; - final String defaultsHeader = filedefaults.buildHeader(); - - if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { - return defaultsHeader; - } - } - } - - if (header == null) { - return ""; - } - - final StringBuilder builder = new StringBuilder(); - final String[] lines = header.split("\r?\n", -1); - boolean startedHeader = false; - - for (int i = lines.length - 1; i >= 0; i--) { - builder.insert(0, "\n"); - - if ((startedHeader) || (lines[i].length() != 0)) { - builder.insert(0, lines[i]); - builder.insert(0, COMMENT_PREFIX); - startedHeader = true; - } - } - - return builder.toString(); - } - - @Override - public YamlConfigurationOptions options() { - if (options == null) { - options = new YamlConfigurationOptions(this); - } - - return (YamlConfigurationOptions) options; - } - + /** * Creates a new {@link YamlConfiguration}, loading from the given file. *

@@ -178,12 +44,12 @@ public class YamlConfiguration extends FileConfiguration { if (file == null) { throw new NullPointerException("File cannot be null"); } - + final YamlConfiguration config = new YamlConfiguration(); - + try { config.load(file); - } catch (final Exception ex) { + } catch (InvalidConfigurationException | IOException ex) { try { file.getAbsolutePath(); File dest = new File(file.getAbsolutePath() + "_broken"); @@ -201,45 +67,10 @@ public class YamlConfiguration extends FileConfiguration { e.printStackTrace(); } } - + return config; } - - /** - * Creates a new {@link YamlConfiguration}, loading from the given stream. - *

- * 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. *

@@ -255,19 +86,148 @@ public class YamlConfiguration extends FileConfiguration { if (reader == null) { throw new NullPointerException("Reader cannot be null"); } - + final YamlConfiguration config = new YamlConfiguration(); - + try { config.load(reader); - } catch (final IOException ex) { - PS.debug("Cannot load configuration from stream"); - ex.printStackTrace(); - } catch (final InvalidConfigurationException ex) { + } catch (final IOException | InvalidConfigurationException ex) { PS.debug("Cannot load configuration from stream"); ex.printStackTrace(); } - + return config; } + + @Override + @SuppressWarnings("deprecation") + public String saveToString() { + yamlOptions.setIndent(options().indent()); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yamlOptions.setAllowUnicode(SYSTEM_UTF); + yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + final String header = buildHeader(); + String dump = yaml.dump(getValues(false)); + + if (dump.equals(BLANK_CONFIG)) { + dump = ""; + } + + return header + dump; + } + + @Override + public void loadFromString(final String contents) throws InvalidConfigurationException { + if (contents == null) { + throw new NullPointerException("Contents cannot be null"); + } + + Map input; + try { + input = (Map) yaml.load(contents); + } catch (final YAMLException e) { + throw new InvalidConfigurationException(e); + } catch (final ClassCastException e) { + throw new InvalidConfigurationException("Top level is not a Map."); + } + + final String header = parseHeader(contents); + if (!header.isEmpty()) { + options().header(header); + } + + if (input != null) { + convertMapsToSections(input, this); + } + } + + protected void convertMapsToSections(final Map input, final ConfigurationSection section) { + for (final Map.Entry entry : input.entrySet()) { + final String key = entry.getKey().toString(); + final Object value = entry.getValue(); + + if (value instanceof Map) { + convertMapsToSections((Map) value, section.createSection(key)); + } else { + section.set(key, value); + } + } + } + + protected String parseHeader(final String input) { + final String[] lines = input.split("\r?\n", -1); + final StringBuilder result = new StringBuilder(); + boolean readingHeader = true; + boolean foundHeader = false; + + for (int i = 0; (i < lines.length) && (readingHeader); i++) { + final String line = lines[i]; + + if (line.startsWith(COMMENT_PREFIX)) { + if (i > 0) { + result.append("\n"); + } + + if (line.length() > COMMENT_PREFIX.length()) { + result.append(line.substring(COMMENT_PREFIX.length())); + } + + foundHeader = true; + } else if ((foundHeader) && (line.isEmpty())) { + result.append("\n"); + } else if (foundHeader) { + readingHeader = false; + } + } + + return result.toString(); + } + + @Override + protected String buildHeader() { + final String header = options().header(); + + if (options().copyHeader()) { + final Configuration def = getDefaults(); + + if ((def != null) && (def instanceof FileConfiguration)) { + final FileConfiguration filedefaults = (FileConfiguration) def; + final String defaultsHeader = filedefaults.buildHeader(); + + if ((defaultsHeader != null) && (!defaultsHeader.isEmpty())) { + return defaultsHeader; + } + } + } + + if (header == null) { + return ""; + } + + final StringBuilder builder = new StringBuilder(); + final String[] lines = header.split("\r?\n", -1); + boolean startedHeader = false; + + for (int i = lines.length - 1; i >= 0; i--) { + builder.insert(0, "\n"); + + if ((startedHeader) || (!lines[i].isEmpty())) { + builder.insert(0, lines[i]); + builder.insert(0, COMMENT_PREFIX); + startedHeader = true; + } + } + + return builder.toString(); + } + + @Override + public YamlConfigurationOptions options() { + if (options == null) { + options = new YamlConfigurationOptions(this); + } + + return (YamlConfigurationOptions) options; + } } diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java b/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java index d73b8964a..f4980530f 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java @@ -21,12 +21,14 @@ package com.intellectualcrafters.jnbt; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** * A class which holds constant values. */ public final class NBTConstants { - public static final Charset CHARSET = Charset.forName("UTF-8"); + + public static final Charset CHARSET = StandardCharsets.UTF_8; public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11; diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java b/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java index 3606d3355..ca75e3204 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java @@ -26,7 +26,7 @@ public final class NBTInputStream implements Closeable { * * @throws IOException if an I/O error occurs */ - public NBTInputStream(final InputStream is) throws IOException { + public NBTInputStream(final InputStream is) { this.is = new DataInputStream(is); } diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java index 524156f65..cd11ccbb7 100644 --- a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java +++ b/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java @@ -48,7 +48,7 @@ public final class NBTOutputStream implements Closeable { * * @throws IOException if an I/O error occurs. */ - public NBTOutputStream(final OutputStream os) throws IOException { + public NBTOutputStream(final OutputStream os) { this.os = new DataOutputStream(os); } diff --git a/src/main/java/com/intellectualcrafters/json/CDL.java b/src/main/java/com/intellectualcrafters/json/CDL.java index 717b12349..0c791c6e4 100644 --- a/src/main/java/com/intellectualcrafters/json/CDL.java +++ b/src/main/java/com/intellectualcrafters/json/CDL.java @@ -75,7 +75,7 @@ public class CDL { for (;;) { final String value = getValue(x); char c = x.next(); - if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) { + if ((value == null) || ((ja.length() == 0) && (value.isEmpty()) && (c != ','))) { return null; } ja.put(value); @@ -128,7 +128,8 @@ public class CDL { final Object object = ja.opt(i); if (object != null) { final String string = object.toString(); - if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) { + if ((!string.isEmpty()) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || ( + string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) { sb.append('"'); final int length = string.length(); for (int j = 0; j < length; j += 1) { diff --git a/src/main/java/com/intellectualcrafters/json/JSONObject.java b/src/main/java/com/intellectualcrafters/json/JSONObject.java index 81f89ff01..c413e8510 100644 --- a/src/main/java/com/intellectualcrafters/json/JSONObject.java +++ b/src/main/java/com/intellectualcrafters/json/JSONObject.java @@ -360,7 +360,7 @@ public class JSONObject { } public static Writer quote(final String string, final Writer w) throws IOException { - if ((string == null) || (string.length() == 0)) { + if ((string == null) || (string.isEmpty())) { w.write("\"\""); return w; } @@ -1111,7 +1111,7 @@ public class JSONObject { } else if (name.startsWith("is")) { key = name.substring(2); } - if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) { + if ((!key.isEmpty()) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { diff --git a/src/main/java/com/intellectualcrafters/json/XML.java b/src/main/java/com/intellectualcrafters/json/XML.java index 7f95563cc..40f063fbb 100644 --- a/src/main/java/com/intellectualcrafters/json/XML.java +++ b/src/main/java/com/intellectualcrafters/json/XML.java @@ -108,7 +108,7 @@ public class XML { if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); - if (string.length() > 0) { + if (!string.isEmpty()) { context.accumulate("content", string); } return false; @@ -192,7 +192,7 @@ public class XML { return false; } else if (token instanceof String) { string = (String) token; - if (string.length() > 0) { + if (!string.isEmpty()) { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element @@ -380,7 +380,8 @@ public class XML { return sb.toString(); } else { string = (object == null) ? "null" : escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; + return (tagName == null) ? "\"" + string + "\"" : + (string.isEmpty()) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; } } } diff --git a/src/main/java/com/intellectualcrafters/plot/PS.java b/src/main/java/com/intellectualcrafters/plot/PS.java index e82c41feb..8d0a02b15 100644 --- a/src/main/java/com/intellectualcrafters/plot/PS.java +++ b/src/main/java/com/intellectualcrafters/plot/PS.java @@ -1,33 +1,5 @@ package com.intellectualcrafters.plot; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.MemorySection; import com.intellectualcrafters.configuration.file.YamlConfiguration; @@ -84,6 +56,37 @@ import com.intellectualcrafters.plot.util.area.QuadMap; import com.plotsquared.listener.WESubscriber; import com.sk89q.worldedit.WorldEdit; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + /** * An implementation of the core, * with a static getter for easy access @@ -95,11 +98,6 @@ public class PS { // protected static: private static PS instance; - - /** - * All plot areas (quick global access) - */ - private PlotArea[] plotareas = new PlotArea[0]; /** * All plot areas mapped by world (quick world access) */ @@ -108,11 +106,8 @@ public class PS { * All plot areas mapped by location (quick location based access) */ private final HashMap> plotareagrid = new HashMap<>(); - public HashMap> clusters_tmp; - public HashMap> plots_tmp; - // public: public File styleFile; public File configFile; @@ -124,7 +119,10 @@ public class PS { public TaskManager TASK; public WorldEdit worldedit; public URL update; - + /** + * All plot areas (quick global access) + */ + private PlotArea[] plotareas = new PlotArea[0]; // private: private File storageFile; private File FILE = null; // This file @@ -146,11 +144,10 @@ public class PS { SetupUtils.generators = new HashMap<>(); IMP = imp_class; new ReflectionUtils(IMP.getNMSPackage()); - URL url; try { - url = PS.class.getProtectionDomain().getCodeSource().getLocation(); + URL url = PS.class.getProtectionDomain().getCodeSource().getLocation(); FILE = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); - } catch (final Exception e) { + } catch (MalformedURLException | URISyntaxException e) { e.printStackTrace(); FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared.jar"); if (!FILE.exists()) { @@ -169,7 +166,7 @@ public class PS { log(C.CONSOLE_JAVA_OUTDATED_1_8); } TASK = IMP.getTaskManager(); - if (C.ENABLED.s().length() > 0) { + if (!C.ENABLED.s().isEmpty()) { log(C.ENABLED.s()); } setupConfigs(); @@ -214,7 +211,7 @@ public class PS { @Override public void run() { for (final Plot plot : getPlots()) { - if ((plot.owner != null) && (plot.temp != -1)) { + if ((plot.hasOwner()) && (plot.temp != -1)) { if (UUIDHandler.getName(plot.owner) == null) { UUIDHandler.implementation.unknown.add(plot.owner); } @@ -323,14 +320,6 @@ public class PS { } } - public boolean isMainThread(final Thread thread) { - return this.thread == thread; - } - - public boolean checkVersion(final int[] version, final int major, final int minor, final int minor2) { - return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && (version[2] >= minor2)); - } - /** * Get the instance of PlotSquared * @@ -340,30 +329,6 @@ public class PS { return instance; } - /** - * Get the last PlotSquared version - * @return last version in config or null - */ - public String getLastVersion() { - return LAST_VERSION; - } - - /** - * Get the current PlotSquared version - * @return current version in config or null - */ - public int[] getVersion() { - return VERSION; - } - - /** - * Get the platform this is running on (Bukkit, Sponge) - * @return - */ - public String getPlatform() { - return PLATFORM; - } - /** * Log a message to the IPlotMain logger * @@ -389,7 +354,40 @@ public class PS { log(message); } } - + + public boolean isMainThread(final Thread thread) { + return this.thread == thread; + } + + public boolean checkVersion(final int[] version, final int major, final int minor, final int minor2) { + return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && ( + version[2] >= minor2)); + } + + /** + * Get the last PlotSquared version + * @return last version in config or null + */ + public String getLastVersion() { + return LAST_VERSION; + } + + /** + * Get the current PlotSquared version + * @return current version in config or null + */ + public int[] getVersion() { + return VERSION; + } + + /** + * Get the platform this is running on (Bukkit, Sponge) + * @return + */ + public String getPlatform() { + return PLATFORM; + } + /** * Get the database object * @@ -434,8 +432,6 @@ public class PS { case 7: case 8: String world = loc.getWorld(); - int x = loc.getX(); - int y = loc.getY(); int hash = world.hashCode(); for (PlotArea area : plotareas) { if (hash == area.worldhash) { @@ -450,6 +446,8 @@ public class PS { if (areas == null) { return null; } + int y; + int x; switch (areas.length) { case 1: return areas[0]; @@ -561,8 +559,6 @@ public class PS { case 7: case 8: String world = loc.getWorld(); - int x = loc.getX(); - int y = loc.getY(); int hash = world.hashCode(); for (PlotArea area : plotareas) { if (hash == area.worldhash) { @@ -577,6 +573,8 @@ public class PS { if (areas == null) { return null; } + int x; + int y; switch (areas.length) { case 0: PlotArea a = areas[0]; @@ -615,10 +613,8 @@ public class PS { /** * Add a global reference to a plot world * - * @param world World Name - * @param plotworld PlotArea Instance - * @param manager PlotManager - * @see #removePlotWorld(String) To remove the reference + * @param plotarea World Name + * @see #removePlotArea(PlotArea) To remove the reference */ public void addPlotArea(final PlotArea plotarea) { HashMap plots = plots_tmp.remove(plotarea.toString()); @@ -640,8 +636,8 @@ public class PS { Set globalAreas = getPlotAreas(); localAreas.add(plotarea); globalAreas.add(plotarea); - plotareas = globalAreas.toArray(new PlotArea[0]); - plotareamap.put(plotarea.worldname, localAreas.toArray(new PlotArea[0])); + plotareas = globalAreas.toArray(new PlotArea[globalAreas.size()]); + plotareamap.put(plotarea.worldname, localAreas.toArray(new PlotArea[localAreas.size()])); if (plotarea.TYPE == 2) { QuadMap map = plotareagrid.get(plotarea.worldname); if (map == null) { @@ -660,14 +656,14 @@ public class PS { /** * Remove a plot world reference * - * @param world World name - * @see #addPlotWorld(String, PlotArea, PlotManager) To add a reference + * @param area World name + * @see #addPlotArea(PlotArea) To add a reference */ public void removePlotArea(final PlotArea area) { Set areas = getPlotAreas(area.worldname); areas.remove(area); - plotareas = areas.toArray(new PlotArea[0]); - if (areas.size() == 0) { + plotareas = areas.toArray(new PlotArea[areas.size()]); + if (areas.isEmpty()) { plotareamap.remove(area.worldname); plotareagrid.remove(area.worldname); } else { @@ -685,7 +681,7 @@ public class PS { private void setPlotsTmp(PlotArea area) { if (plots_tmp == null) { - plots_tmp = new HashMap>(); + plots_tmp = new HashMap<>(); } HashMap map = plots_tmp.get(area.toString()); if (map == null) { @@ -701,6 +697,60 @@ public class PS { clusters_tmp.put(area.toString(), area.getClusters()); } + public Set getClusters(String world) { + HashSet set = new HashSet<>(); + if (Settings.ENABLE_CLUSTERS) { + for (PlotArea area : getPlotAreas(world)) { + set.addAll(area.getClusters()); + } + } + return set; + + } + + /** + * A more generic way to filter plots - make your own method if you need complex filters + * @param filters + * @return + */ + public Set getPlots(final PlotFilter... filters) { + final HashSet set = new HashSet<>(); + foreachPlotArea(new RunnableVal() { + @Override + public void run(PlotArea value) { + for (final PlotFilter filter : filters) { + if (!filter.allowsArea(value)) { + } + } + for (Entry entry2 : value.getPlotEntries()) { + Plot plot = entry2.getValue(); + for (final PlotFilter filter : filters) { + if (!filter.allowsPlot(plot)) { + } + } + set.add(plot); + } + } + }); + return set; + } + + /** + * Get all the plots in a single set + * @return Set of Plot + */ + public Set getPlots() { + int size = getPlotCount(); + final Set result = new HashSet<>(size); + foreachPlotArea(new RunnableVal() { + @Override + public void run(PlotArea value) { + result.addAll(value.getPlots()); + } + }); + return result; + } + public void setPlots(HashMap> plots) { if (plots_tmp == null) { plots_tmp = new HashMap<>(); @@ -725,62 +775,6 @@ public class PS { } } - public Set getClusters(String world) { - HashSet set = new HashSet<>(); - if (Settings.ENABLE_CLUSTERS) { - for (PlotArea area : getPlotAreas(world)) { - set.addAll(area.getClusters()); - } - } - return set; - - } - - /** - * A more generic way to filter plots - make your own method if you need complex filters - * @param filters - * @return - */ - public Set getPlots(final PlotFilter... filters) { - final HashSet set = new HashSet<>(); - foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { - for (final PlotFilter filter : filters) { - if (!filter.allowsArea(value)) { - continue; - } - } - for (Entry entry2 : value.getPlotEntries()) { - Plot plot = entry2.getValue(); - for (final PlotFilter filter : filters) { - if (!filter.allowsPlot(plot)) { - continue; - } - } - set.add(plot); - } - } - }); - return set; - } - - /** - * Get all the plots in a single set - * @return Set of Plot - */ - public Set getPlots() { - int size = getPlotCount(); - final Set result = new HashSet<>(size); - foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { - result.addAll(value.getPlots()); - } - }); - return result; - } - /** * Get all the base plots in a single set (for merged plots it just returns the bottom plot) * @return Set of base Plot @@ -801,18 +795,7 @@ public class PS { }); return result; } - - /** - * Sort a collection of plots by the hashcode (assumes that all plots are in the same world) - * @param plots - * @return ArrayList of plot - * @deprecated use sortPlot - */ - @Deprecated - public ArrayList sortPlots(final Collection plots) { - return sortPlots(plots, SortType.DISTANCE_FROM_ORIGIN, null); - } - + public ArrayList sortPlotsByTemp(final Collection plots) { int max = 0; int overflowCount = 0; @@ -854,7 +837,7 @@ public class PS { * Sort plots by hashcode * @param plots * @return - * @deprecated Unchecked, please use {@link #sortPlots(Collection, SortType, String)} which has additional checks before calling this + * @deprecated Unchecked, please use {@link #sortPlots(Collection, SortType, PlotArea)} which has additional checks before calling this */ @Deprecated public ArrayList sortPlotsByHash(final Collection plots) { @@ -907,7 +890,7 @@ public class PS { /** * Sort plots by creation timestamp * @param input - * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will call this after checks + * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks * @return */ @Deprecated @@ -932,9 +915,9 @@ public class PS { } } final long range = max - min; - Plot[] plots; try { final ArrayList overflow = new ArrayList<>(); + Plot[] plots; if ((range > limit) && (size > 1024)) { plots = new Plot[limit]; final int factor = (int) ((range / limit)); @@ -1034,7 +1017,7 @@ public class PS { } } final ArrayList result = new ArrayList<>(size); - if (overflow.size() > 0) { + if (!overflow.isEmpty()) { Collections.sort(overflow, new Comparator() { @Override public int compare(final Plot a, final Plot b) { @@ -1075,7 +1058,7 @@ public class PS { } /** - * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this + * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will in turn call this * @param input */ @Deprecated @@ -1085,11 +1068,11 @@ public class PS { bucket[i] = new ArrayList<>(); } boolean maxLength = false; - int tmp, placement = 1; + int placement = 1; while (!maxLength) { maxLength = true; for (final Plot i : input) { - tmp = MathMan.getPositiveId(i.hashCode()) / placement; + int tmp = MathMan.getPositiveId(i.hashCode()) / placement; bucket[tmp & 31].add(i); if (maxLength && (tmp > 0)) { maxLength = false; @@ -1105,50 +1088,12 @@ public class PS { placement *= 32; } } - - /** - * Sort plots by timestamp - * @param input - * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this - */ - @Deprecated - public void sortPlotsByTimestamp(final Plot[] input) { - final int SIZE = 100; - final List[] bucket = new ArrayList[SIZE]; - for (int i = 0; i < bucket.length; i++) { - bucket[i] = new ArrayList<>(); - } - boolean maxLength = false; - int tmp = -1, placement = 1; - while (!maxLength) { - maxLength = true; - for (final Plot i : input) { - tmp = MathMan.getPositiveId(i.hashCode()) / placement; - bucket[tmp % SIZE].add(i); - if (maxLength && (tmp > 0)) { - maxLength = false; - } - } - int a = 0; - for (int b = 0; b < SIZE; b++) { - for (final Plot i : bucket[b]) { - input[a++] = i; - } - bucket[b].clear(); - } - placement *= SIZE; - } - } - - public enum SortType { - CREATION_DATE, CREATION_DATE_TIMESTAMP, DISTANCE_FROM_ORIGIN - } - + /** * Sort a collection of plots by world (with a priority world), then by hashcode - * @param plots + * @param myplots * @param type The sorting method to use for each world (timestamp, or hash) - * @param priorityWorld - Use null, "world" or "gibberish" if you want default world order + * @param priorityArea - Use null, "world" or "gibberish" if you want default world order * @return ArrayList of plot */ public ArrayList sortPlots(final Collection myplots, final SortType type, final PlotArea priorityArea) { @@ -1161,7 +1106,6 @@ public class PS { map.put(area, area.getPlots()); } } else { - int size = plotareas.length; for (PlotArea area : plotareas) { map.put(area, new ArrayList(0)); } @@ -1206,36 +1150,6 @@ public class PS { return toReturn; } - /** - * Sort a collection of plots by world, then by hashcode - * @param plots - * @deprecated Use #sortPlots(Collection, String) instead - * @return ArrayList of plot - */ - @Deprecated - public ArrayList sortPlotsByArea(final Collection plots) { - final ArrayList newPlots = new ArrayList<>(); - ArrayList areas = new ArrayList(Arrays.asList(plotareas)); - Collections.sort(areas, new Comparator() { - @Override - public int compare(final PlotArea a, final PlotArea b) { - return a.hashCode() - b.hashCode(); - } - }); - final HashSet set = new HashSet<>(plots); - foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { - for (Plot plot : value.getPlots()) { - if (set.contains(plot)) { - newPlots.add(plot); - } - } - } - }); - return newPlots; - } - /** * Get all the plots owned by a player name * @param world @@ -1246,10 +1160,10 @@ public class PS { final UUID uuid = UUIDHandler.getUUID(player, null); return getPlots(world, uuid); } - + /** * Get all the plots owned by a player name - * @param world + * @param area * @param player * @return Set of Plot */ @@ -1271,7 +1185,7 @@ public class PS { /** * Get all plots by a PlotPlayer - * @param world + * @param area * @param player * @return Set of plot */ @@ -1300,7 +1214,7 @@ public class PS { /** * Get all plots by a UUID in an area - * @param world + * @param area * @param uuid * @return Set of plot */ @@ -1319,7 +1233,7 @@ public class PS { /** * Check if a plot world * @param world - * @see #getPlotArea(String) to get the PlotArea object + * @see #getPlotAreaByString(String) to get the PlotArea object * @return if a plot world is registered */ public boolean hasPlotArea(final String world) { @@ -1405,7 +1319,7 @@ public class PS { foreachPlot(new RunnableVal() { @Override public void run(Plot value) { - if (value.owner.equals(uuid)) { + if (value.isOwner(uuid)) { myplots.add(value); } } @@ -1415,8 +1329,7 @@ public class PS { /** * Unregister a plot from local memory (does not call DB) - * @param world - * @param id + * @param plot * @param callEvent If to call an event about the plot being removed * @return true if plot existed | false if it didn't */ @@ -1449,7 +1362,7 @@ public class PS { * - Creates the AugmentedPopulator classes
* - Injects the AugmentedPopulator classes if required * @param world The world to load - * @param generator The generator for that world, or null if no generator + * @param baseGenerator The generator for that world, or null if no generator */ public void loadWorld(final String world, final GeneratorWrapper baseGenerator) { if (world.equals("CheckingPlotSquaredGenerator")) { @@ -1466,7 +1379,7 @@ public class PS { } IndependentPlotGenerator pg; if (baseGenerator != null && baseGenerator.isFull()) { - pg = baseGenerator.getPlotGenerator(); + pg = baseGenerator.getPlotGenerator(); } else if (worldSection != null) { String secondaryGeneratorName = worldSection.getString("generator.plugin"); @@ -1589,7 +1502,7 @@ public class PS { String name = split[0]; PlotId pos1 = PlotId.fromString(split[1]); PlotId pos2 = PlotId.fromString(split[2]); - if (pos1 == null || pos2 == null || name.length() == 0) { + if (pos1 == null || pos2 == null || name.isEmpty()) { throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); } if (getPlotAreaAbs(world, name) != null) { @@ -1623,7 +1536,7 @@ public class PS { } PlotArea pa = areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); pa.saveConfiguration(clone); - // netSections is the combination of + // netSections is the combination of for (String key : clone.getKeys(true)) { if (clone.get(key) instanceof MemorySection) { continue; @@ -1662,7 +1575,7 @@ public class PS { * @return boolean | if valid arguments were provided */ public boolean setupPlotWorld(final String world, final String args, IndependentPlotGenerator generator) { - if ((args != null) && (args.length() > 0)) { + if ((args != null) && (!args.isEmpty())) { // save configuration final String[] split = args.split(","); final HybridPlotWorld plotworld = new HybridPlotWorld(world, null, generator, null, null); @@ -1732,7 +1645,7 @@ public class PS { plotworld.saveConfiguration(section); plotworld.loadConfiguration(section); config.save(configFile); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -1765,32 +1678,32 @@ public class PS { */ public URL getUpdate() { final String pom = "https://raw.githubusercontent.com/IntellectualSites/PlotSquared/master/pom.xml"; - String dl = "https://raw.githubusercontent.com/IntellectualSites/PlotSquared/master/target/PlotSquared-${PLATFORM}.jar"; - final String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1"; try { final URL page = new URL(pom); final URLConnection con = page.openConnection(); + final String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1"; con.addRequestProperty("User-Agent", agent); - final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String line = null; - while ((line = in.readLine()) != null) { - line = line.trim(); - if (line.startsWith("")) { - line = line.replaceAll("[^\\d.]", ""); - break; + String line; + try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { + while ((line = in.readLine()) != null) { + line = line.trim(); + if (line.startsWith("")) { + line = line.replaceAll("[^\\d.]", ""); + break; + } } } - in.close(); if (!canUpdate(config.getString("version"), line)) { PS.debug("&7PlotSquared is already up to date!"); return null; } + String dl = "https://raw.githubusercontent.com/IntellectualSites/PlotSquared/master/target/PlotSquared-${PLATFORM}.jar"; dl = dl.replaceAll(Pattern.quote("${PLATFORM}"), getPlatform()); log("&6PlotSquared v" + line + " is available:"); log("&8 - &3Use: &7/plot update"); log("&8 - &3Or: &7" + dl); return new URL(dl); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); log("&dCould not check for updates (0)"); log("&7 - Manually check for updates: " + pom); @@ -1820,7 +1733,7 @@ public class PS { stream.close(); MainUtil.sendMessage(sender, "$1The update will take effect when the server is restarted next"); return true; - } catch (final Exception e) { + } catch (IOException e) { MainUtil.sendMessage(sender, "Failed to update PlotSquared"); MainUtil.sendMessage(sender, " - Please update manually"); log("============ Stacktrace ============"); @@ -1885,7 +1798,7 @@ public class PS { } fos.close(); stream.close(); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); log("&cCould not save " + file); } @@ -1913,7 +1826,7 @@ public class PS { database = null; // Validate that all data in the db is correct DBFunc.validatePlots(getPlots()); - + // Close the connection DBFunc.close(); UUIDHandler.handleShutdown(); @@ -1921,7 +1834,7 @@ public class PS { log("&cCould not close database connection!"); } } - + /** * Setup the database connection */ @@ -1949,7 +1862,7 @@ public class PS { if (Settings.ENABLE_CLUSTERS) { this.clusters_tmp = DBFunc.getClusters(); } - } catch (final Exception e) { + } catch (ClassNotFoundException | SQLException e) { log(C.PREFIX.s() + "&cFailed to open DATABASE connection. The plugin will disable itself."); if (Settings.DB.USE_MONGO) { log("$4MONGO"); @@ -1963,7 +1876,6 @@ public class PS { log("&d==== End of stacktrace ===="); log("&6Please go to the PlotSquared 'storage.yml' and configure the database correctly."); IMP.disable(); - return; } } @@ -2019,7 +1931,7 @@ public class PS { FlagManager.addFlag(new AbstractFlag("blocked-cmds", new FlagValue.StringListValue())); FlagManager.addFlag(new AbstractFlag("ice-melt", new FlagValue.BooleanValue())); FlagManager.addFlag(new AbstractFlag("gamemode") { - + @Override public PlotGamemode parseValueRaw(final String value) { switch (value.toLowerCase()) { @@ -2042,7 +1954,7 @@ public class PS { return null; } } - + @Override public String getValueDesc() { return "Flag value must be a gamemode: 'creative' , 'survival', 'adventure' or 'spectator'"; @@ -2051,7 +1963,7 @@ public class PS { FlagManager.addFlag(new AbstractFlag("price", new FlagValue.UnsignedDoubleValue())); FlagManager.addFlag(new AbstractFlag("time", new FlagValue.LongValue())); FlagManager.addFlag(new AbstractFlag("weather") { - + @Override public PlotWeather parseValueRaw(final String value) { switch (value.toLowerCase()) { @@ -2069,7 +1981,7 @@ public class PS { return null; } } - + @Override public String getValueDesc() { return "Flag value must be weather type: 'clear' or 'rain'"; @@ -2085,17 +1997,17 @@ public class PS { LAST_VERSION = config.getString("version"); config.set("version", StringMan.join(VERSION, ".")); config.set("platform", PLATFORM); - + final Map options = new HashMap<>(); // Command confirmation options.put("confirmation.clear", Settings.CONFIRM_CLEAR); options.put("confirmation.delete", Settings.CONFIRM_DELETE); options.put("confirmation.unlink", Settings.CONFIRM_UNLINK); - + // Protection options.put("protection.redstone.disable-offline", Settings.REDSTONE_DISABLER); options.put("protection.redstone.disable-unoccupied", Settings.REDSTONE_DISABLER_UNOCCUPIED); - + // Clusters options.put("clusters.enabled", Settings.ENABLE_CLUSTERS); @@ -2103,17 +2015,17 @@ public class PS { options.put("plotme-alias", Settings.USE_PLOTME_ALIAS); options.put("plotme-convert.enabled", Settings.CONVERT_PLOTME); options.put("plotme-convert.cache-uuids", Settings.CACHE_PLOTME); - + // UUID options.put("uuid.use_sqluuidhandler", Settings.USE_SQLUUIDHANDLER); options.put("UUID.offline", Settings.OFFLINE_MODE); options.put("UUID.force-lowercase", Settings.UUID_LOWERCASE); options.put("uuid.read-from-disk", Settings.UUID_FROM_DISK); - + // Mob stuff options.put("kill_road_vehicles", Settings.KILL_ROAD_VEHICLES); options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS); - + // Clearing + Expiry options.put("clear.fastmode", false); options.put("clear.on.ban", false); @@ -2130,7 +2042,7 @@ public class PS { options.put("clear.auto.calibration.data_sd", 0); options.put("clear.auto.calibration.air_sd", 0); options.put("clear.auto.calibration.variety_sd", 0); - + final int keep = config.getInt("clear.keep-if-modified"); final int ignore = config.getInt("clear.ignore-if-modified"); if ((keep > 0) || (ignore > 0)) { @@ -2150,32 +2062,32 @@ public class PS { } config.set("clear.keep-if-modified", null); config.set("clear.ignore-if-modified", null); - + // Done options.put("approval.ratings.require-done", Settings.REQUIRE_DONE); options.put("approval.done.counts-towards-limit", Settings.DONE_COUNTS_TOWARDS_LIMIT); options.put("approval.done.restrict-building", Settings.DONE_RESTRICTS_BUILDING); options.put("approval.done.required-for-download", Settings.DOWNLOAD_REQUIRES_DONE); - + // Schematics options.put("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); options.put("bo3.save_path", Settings.BO3_SAVE_PATH); - + // Web options.put("web.url", Settings.WEB_URL); options.put("web.server-ip", Settings.WEB_IP); - + // Caching options.put("cache.permissions", Settings.PERMISSION_CACHING); options.put("cache.ratings", Settings.CACHE_RATINGS); - + // Titles options.put("titles", Settings.TITLES); - + // Teleportation options.put("teleport.on_login", Settings.TELEPORT_ON_LOGIN); options.put("teleport.delay", 0); - + // WorldEdit options.put("worldedit.require-selection-in-mask", Settings.REQUIRE_SELECTION); options.put("worldedit.queue-commands", Settings.QUEUE_COMMANDS); @@ -2183,7 +2095,7 @@ public class PS { options.put("worldedit.max-volume", Settings.WE_MAX_VOLUME); options.put("worldedit.max-iterations", Settings.WE_MAX_ITERATIONS); options.put("worldedit.blacklist", Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks")); - + // Chunk processor options.put("chunk-processor.enabled", Settings.CHUNK_PROCESSOR); options.put("chunk-processor.auto-unload", Settings.CHUNK_PROCESSOR_GC); @@ -2192,38 +2104,38 @@ public class PS { options.put("chunk-processor.max-blockstates", Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES); options.put("chunk-processor.max-entities", Settings.CHUNK_PROCESSOR_MAX_ENTITIES); options.put("chunk-processor.disable-physics", Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS); - + // Comments options.put("comments.notifications.enabled", Settings.COMMENT_NOTIFICATIONS); - + // Plot limits options.put("global_limit", Settings.GLOBAL_LIMIT); options.put("max_plots", Settings.MAX_PLOTS); options.put("claim.max-auto-area", Settings.MAX_AUTO_SIZE); options.put("merge.remove-terrain", Settings.MERGE_REMOVES_ROADS); - + // Misc options.put("console.color", Settings.CONSOLE_COLOR); options.put("chat.fancy", Settings.FANCY_CHAT); options.put("metrics", true); options.put("debug", true); options.put("update-notifications", Settings.UPDATE_NOTIFICATIONS); - + for (final Entry node : options.entrySet()) { if (!config.contains(node.getKey())) { config.set(node.getKey(), node.getValue()); } } - + // Command confirmation Settings.CONFIRM_CLEAR = config.getBoolean("confirmation.clear"); Settings.CONFIRM_DELETE = config.getBoolean("confirmation.delete"); Settings.CONFIRM_UNLINK = config.getBoolean("confirmation.unlink"); - + // Protection Settings.REDSTONE_DISABLER = config.getBoolean("protection.redstone.disable-offline"); Settings.REDSTONE_DISABLER_UNOCCUPIED = config.getBoolean("protection.redstone.disable-unoccupied"); - + // Clusters Settings.ENABLE_CLUSTERS = config.getBoolean("clusters.enabled"); @@ -2231,17 +2143,17 @@ public class PS { Settings.USE_PLOTME_ALIAS = config.getBoolean("plotme-alias"); Settings.CONVERT_PLOTME = config.getBoolean("plotme-convert.enabled"); Settings.CACHE_PLOTME = config.getBoolean("plotme-convert.cache-uuids"); - + // UUID Settings.USE_SQLUUIDHANDLER = config.getBoolean("uuid.use_sqluuidhandler"); Settings.OFFLINE_MODE = config.getBoolean("UUID.offline"); Settings.UUID_LOWERCASE = Settings.OFFLINE_MODE && config.getBoolean("UUID.force-lowercase"); Settings.UUID_FROM_DISK = config.getBoolean("uuid.read-from-disk"); - + // Mob stuff Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); Settings.KILL_ROAD_VEHICLES = config.getBoolean("kill_road_vehicles"); - + // Clearing + Expiry Settings.FAST_CLEAR = config.getBoolean("clear.fastmode"); Settings.DELETE_PLOTS_ON_BAN = config.getBoolean("clear.on.ban"); @@ -2249,7 +2161,7 @@ public class PS { Settings.CLEAR_THRESHOLD = config.getInt("clear.auto.threshold"); Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); Settings.CLEAR_INTERVAL = config.getInt("clear.auto.clear-interval-seconds"); - + // Clearing modifiers PlotAnalysis.MODIFIERS.changes = config.getInt("clear.auto.calibration.changes"); PlotAnalysis.MODIFIERS.faces = config.getInt("clear.auto.calibration.faces"); @@ -2261,35 +2173,35 @@ public class PS { PlotAnalysis.MODIFIERS.data_sd = config.getInt("clear.auto.calibration.data_sd"); PlotAnalysis.MODIFIERS.air_sd = config.getInt("clear.auto.calibration.air_sd"); PlotAnalysis.MODIFIERS.variety_sd = config.getInt("clear.auto.calibration.variety_sd"); - + // Done Settings.REQUIRE_DONE = config.getBoolean("approval.ratings.require-done"); Settings.DONE_COUNTS_TOWARDS_LIMIT = config.getBoolean("approval.done.counts-towards-limit"); Settings.DONE_RESTRICTS_BUILDING = config.getBoolean("approval.done.restrict-building"); Settings.DOWNLOAD_REQUIRES_DONE = config.getBoolean("approval.done.required-for-download"); - + // Schematics Settings.SCHEMATIC_SAVE_PATH = config.getString("schematics.save_path"); Settings.BO3_SAVE_PATH = config.getString("bo3.save_path"); - + // Web Settings.WEB_URL = config.getString("web.url"); Settings.WEB_IP = config.getString("web.server-ip"); - + // Caching Settings.PERMISSION_CACHING = config.getBoolean("cache.permissions"); Settings.CACHE_RATINGS = config.getBoolean("cache.ratings"); - + // Rating system Settings.RATING_CATEGORIES = config.getStringList("ratings.categories"); - + // Titles Settings.TITLES = config.getBoolean("titles"); - + // Teleportation Settings.TELEPORT_DELAY = config.getInt("teleport.delay"); Settings.TELEPORT_ON_LOGIN = config.getBoolean("teleport.on_login"); - + // WorldEdit Settings.QUEUE_COMMANDS = config.getBoolean("worldedit.queue-commands"); Settings.REQUIRE_SELECTION = config.getBoolean("worldedit.require-selection-in-mask"); @@ -2297,7 +2209,7 @@ public class PS { Settings.WE_MAX_VOLUME = config.getLong("worldedit.max-volume"); Settings.WE_MAX_ITERATIONS = config.getLong("worldedit.max-iterations"); Settings.WE_BLACKLIST = config.getStringList("worldedit.blacklist"); - + // Chunk processor Settings.CHUNK_PROCESSOR = config.getBoolean("chunk-processor.enabled"); Settings.CHUNK_PROCESSOR_GC = config.getBoolean("chunk-processor.auto-unload"); @@ -2306,10 +2218,10 @@ public class PS { Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES = config.getInt("chunk-processor.max-blockstates"); Settings.CHUNK_PROCESSOR_MAX_ENTITIES = config.getInt("chunk-processor.max-entities"); Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS = config.getBoolean("chunk-processor.disable-physics"); - + // Comments Settings.COMMENT_NOTIFICATIONS = config.getBoolean("comments.notifications.enabled"); - + // Plot limits Settings.MAX_AUTO_SIZE = config.getInt("claim.max-auto-area"); Settings.MAX_PLOTS = config.getInt("max_plots"); @@ -2318,7 +2230,7 @@ public class PS { Settings.MAX_PLOTS = 32767; } Settings.GLOBAL_LIMIT = config.getBoolean("global_limit"); - + // Misc Settings.DEBUG = config.getBoolean("debug"); if (Settings.DEBUG) { @@ -2357,7 +2269,7 @@ public class PS { } style = YamlConfiguration.loadConfiguration(styleFile); setupStyle(); - } catch (final Exception err) { + } catch (IOException err) { err.printStackTrace(); log("failed to save style.yml"); } @@ -2370,7 +2282,7 @@ public class PS { } config = YamlConfiguration.loadConfiguration(configFile); setupConfig(); - } catch (final Exception err_trans) { + } catch (IOException err_trans) { log("Failed to save settings.yml"); } try { @@ -2382,7 +2294,7 @@ public class PS { } storage = YamlConfiguration.loadConfiguration(storageFile); setupStorage(); - } catch (final Exception err_trans) { + } catch (IOException err_trans) { log("Failed to save storage.yml"); } try { @@ -2501,7 +2413,7 @@ public class PS { runnable.run(area); } } - + public PlotArea getFirstPlotArea() { return plotareas.length > 0 ? plotareas[0] : null; } @@ -2509,7 +2421,7 @@ public class PS { public int getPlotAreaCount() { return plotareas.length; } - + public int getPlotCount() { int count = 0; for (PlotArea area : plotareas) { @@ -2521,12 +2433,10 @@ public class PS { public int getPlotAreaCount(String world) { return plotareamap.size(); } - + public Set getPlotAreas() { HashSet set = new HashSet<>(plotareas.length); - for (PlotArea area : plotareas) { - set.add(area); - } + Collections.addAll(set, plotareas); return set; } @@ -2564,9 +2474,11 @@ public class PS { return new HashSet<>(0); } HashSet set = new HashSet<>(areas.length); - for (PlotArea area : areas) { - set.add(area); - } + Collections.addAll(set, areas); return set; } + + public enum SortType { + CREATION_DATE, CREATION_DATE_TIMESTAMP, DISTANCE_FROM_ORIGIN + } } diff --git a/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java index 874fee301..89849909e 100644 --- a/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java @@ -21,17 +21,6 @@ package com.intellectualcrafters.plot.api; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - import com.intellectualcrafters.configuration.file.YamlConfiguration; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.commands.MainCommand; @@ -51,6 +40,17 @@ import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.util.BukkitUtil; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; /** * PlotSquared API @@ -115,12 +115,8 @@ public class PlotAPI { /** * Add a plot world * - * @param world World Name * @param plotArea Plot World Object - * @param manager World Manager - * - * @see PS#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotArea, - * com.intellectualcrafters.plot.object.PlotManager) + * @see PS#addPlotArea(PlotArea) */ public void addPlotArea(final PlotArea plotArea) { PS.get().addPlotArea(plotArea); @@ -229,7 +225,7 @@ public class PlotAPI { public String[] getPermissions() { final ArrayList perms = new ArrayList<>(); for (final C c : C.values()) { - if (c.getCat().equals("static.permissions")) { + if ("static.permissions".equals(c.getCat())) { perms.add(c.s()); } } @@ -267,7 +263,7 @@ public class PlotAPI { * @return PlotManager * * @see com.intellectualcrafters.plot.object.PlotManager - * @see PS#getPlotManager(String) + * @see PS#getPlotManager(Plot) */ @Deprecated public PlotManager getPlotManager(final World world) { @@ -292,7 +288,7 @@ public class PlotAPI { * * @return PlotManager * - * @see PS#getPlotManager(String) + * @see PS#getPlotManager(Plot) * @see com.intellectualcrafters.plot.object.PlotManager */ @Deprecated @@ -335,7 +331,7 @@ public class PlotAPI { * * @return PlotArea class for that world ! will return null if not a plot world world * - * @see PS#getPlotArea(String) + * @see PS#getPlotArea(String, String) * @see com.intellectualcrafters.plot.object.PlotArea */ @Deprecated @@ -388,7 +384,7 @@ public class PlotAPI { * @see MainUtil#sendConsoleMessage(C, String...) */ public void sendConsoleMessage(final String msg) { - PS.log(msg);; + PS.log(msg); } /** @@ -457,7 +453,6 @@ public class PlotAPI { * * @return plot if found, otherwise it creates a temporary plot- * - * @see MainUtil#getPlotAbs(com.intellectualcrafters.plot.object.Location) * @see Plot */ public Plot getPlot(final Location l) { @@ -492,7 +487,7 @@ public class PlotAPI { */ @Deprecated public boolean hasPlot(final World world, final Player player) { - return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); + return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0; } /** @@ -507,7 +502,7 @@ public class PlotAPI { UUID uuid = BukkitUtil.getPlayer(plr).getUUID(); for (final Plot plot : PS.get().getPlots(world.getName())) { if (just_owner) { - if ((plot.owner != null) && (plot.owner.equals(uuid))) { + if (plot.hasOwner() && plot.isOwner(uuid)) { pPlots.add(plot); } } else { @@ -534,7 +529,8 @@ public class PlotAPI { if (world == null) { return new Plot[0]; } - return PS.get().getPlots(world.getName()).toArray(new Plot[0]); + Collection plots = PS.get().getPlots(world.getName()); + return plots.toArray(new Plot[plots.size()]); } /** @@ -542,11 +538,11 @@ public class PlotAPI { * * @return World[] - array of plot worlds * - * @see PS#getPlotWorlds() */ @Deprecated public String[] getPlotWorlds() { - return PS.get().getPlotWorldStrings().toArray(new String[0]); + Set plotWorldStrings = PS.get().getPlotWorldStrings(); + return plotWorldStrings.toArray(new String[plotWorldStrings.size()]); } /** @@ -572,9 +568,6 @@ public class PlotAPI { * * @deprecated As merged plots may not have a rectangular shape * - * @see MainUtil#getPlotBottomLocAbs(String, PlotId) - * @see MainUtil#getPlotTopLocAbs(String, PlotId) - * @see MainUtil#getPlotHome(String, PlotId) * @see Plot */ @Deprecated @@ -589,7 +582,6 @@ public class PlotAPI { * * @return plot bottom location * - * @see MainUtil#getPlotHome(String, PlotId) * @see Plot */ public Location getHomeLocation(final Plot p) { @@ -605,7 +597,6 @@ public class PlotAPI { * * @deprecated As merged plots may not have a rectangular shape * - * @see MainUtil#getPlotBottomLocAbs(String, PlotId) * @see Plot */ @Deprecated @@ -622,7 +613,6 @@ public class PlotAPI { * * @deprecated As merged plots may not have a rectangular shape * - * @see MainUtil#getPlotTopLocAbs(String, PlotId) * @see Plot */ @Deprecated @@ -637,7 +627,6 @@ public class PlotAPI { * * @return true if the player is in a plot, false if not- * - * @see MainUtil#getPlotAbs(com.intellectualcrafters.plot.object.Location) */ public boolean isInPlot(final Player player) { return getPlot(player) != null; @@ -677,7 +666,6 @@ public class PlotAPI { * * @return the number of plots the player has * - * @see MainUtil#getPlayerPlotCount(String, PlotPlayer) */ public int getPlayerPlotCount(final World world, final Player player) { if (world == null) { diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Alias.java b/src/main/java/com/intellectualcrafters/plot/commands/Alias.java index aabf416e7..484ef667b 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Alias.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Alias.java @@ -42,7 +42,7 @@ public class Alias extends SetCommand { @Override public boolean set(final PlotPlayer plr, final Plot plot, final String alias) { - if (alias.length() == 0) { + if (alias.isEmpty()) { C.COMMAND_SYNTAX.send(plr, getUsage()); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Area.java b/src/main/java/com/intellectualcrafters/plot/commands/Area.java index 6301daf2c..083e1fad7 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Area.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Area.java @@ -1,10 +1,5 @@ package com.intellectualcrafters.plot.commands; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Objects; -import java.util.Set; - import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; @@ -32,6 +27,11 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Objects; +import java.util.Set; + @CommandDeclaration( command = "area", permission = "plots.area", @@ -59,7 +59,7 @@ public class Area extends SubCommand { } switch (args.length) { case 1: { - C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [=]..."); return false; } case 2: { @@ -67,7 +67,7 @@ public class Area extends SubCommand { case "pos1": { // Set position 1 HybridPlotWorld area = plr. getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [=]..."); return false; } Location loc = plr.getLocation(); @@ -80,7 +80,7 @@ public class Area extends SubCommand { case "pos2": { // Set position 2 and finish creation for type=2 (partial) final HybridPlotWorld area = plr. getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [=]..."); return false; } Location pos1 = plr.getLocation(); @@ -100,7 +100,7 @@ public class Area extends SubCommand { final int offsetz = bz - (area.ROAD_WIDTH == 0 ? 0 : lower); final RegionWrapper region = new RegionWrapper(bx, tx, bz, tz); Set areas = PS.get().getPlotAreas(area.worldname, region); - if (areas.size() > 0) { + if (!areas.isEmpty()) { C.CLUSTER_INTERSECTION.send(plr, areas.iterator().next().toString()); return false; } @@ -163,14 +163,14 @@ public class Area extends SubCommand { return false; } Set areas = PS.get().getPlotAreas(pa.worldname); - if (areas.size() > 0) { + if (!areas.isEmpty()) { PlotArea area = areas.iterator().next(); pa.TYPE = area.TYPE; } for (int i = 2; i < args.length; i++) { String[] pair = args[i].split("="); if (pair.length != 2) { - C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [=]..."); return false; } switch (pair[0].toLowerCase()) { @@ -225,7 +225,7 @@ public class Area extends SubCommand { break; } default: { - C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [=]..."); return false; } } @@ -264,7 +264,7 @@ public class Area extends SubCommand { return true; } if (pa.id == null) { - C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:type]] [=]..."); return false; } if (WorldUtil.IMP.isWorld(pa.worldname)) { diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/src/main/java/com/intellectualcrafters/plot/commands/Clear.java index 2c492eec9..cc5f0e031 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Clear.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Clear.java @@ -20,8 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.Set; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.flag.FlagManager; @@ -35,7 +33,10 @@ import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "clear", description = "Clear a plot", permission = "plots.clear", category = CommandCategory.APPEARANCE, usage = "/plot clear [id]") +import java.util.Set; + +@CommandDeclaration(command = "clear", description = "Clear a plot", permission = "plots.clear", category = CommandCategory.APPEARANCE, + usage = "/plot clear [type]") public class Clear extends SubCommand { @Override @@ -45,7 +46,7 @@ public class Clear extends SubCommand { if (args.length == 1) { if (args[0].equalsIgnoreCase("mine")) { Set plots = plr.getPlots(); - if (plots.size() > 0) { + if (!plots.isEmpty()) { plot = plots.iterator().next(); } else { MainUtil.sendMessage(plr, C.NO_PLOTS); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java index 266577bd0..b5f6d7170 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java @@ -20,11 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -43,6 +38,11 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + @CommandDeclaration( command = "cluster", aliases = { "clusters" }, @@ -103,7 +103,7 @@ public class Cluster extends SubCommand { return false; } if (args.length != 4) { - MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster create "); + MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster create "); return false; } // check pos1 / pos2 @@ -132,7 +132,7 @@ public class Cluster extends SubCommand { } // Check if it occupies existing plots final Set plots = area.getPlotSelectionOwned(pos1, pos2); - if (plots.size() > 0) { + if (!plots.isEmpty()) { if (!Permissions.hasPermission(plr, "plots.cluster.create.other")) { final UUID uuid = plr.getUUID(); for (final Plot plot : plots) { @@ -263,14 +263,14 @@ public class Cluster extends SubCommand { final HashSet removed = ((HashSet) existing.clone()); removed.removeAll(newplots); // Check expand / shrink - if (removed.size() > 0) { + if (!removed.isEmpty()) { if (!Permissions.hasPermission(plr, "plots.cluster.resize.shrink")) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.shrink"); return false; } } newplots.removeAll(existing); - if (newplots.size() > 0) { + if (!newplots.isEmpty()) { if (!Permissions.hasPermission(plr, "plots.cluster.resize.expand")) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.expand"); return false; @@ -336,7 +336,6 @@ public class Cluster extends SubCommand { if (!cluster.isAdded(uuid)) { // add the user if not added cluster.invited.add(uuid); - final String world = plr.getLocation().getWorld(); DBFunc.setInvited(cluster, uuid); final PlotPlayer player = UUIDHandler.getPlayer(uuid); if (player != null) { diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/src/main/java/com/intellectualcrafters/plot/commands/Condense.java index 9fa17566c..2014f89f2 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Condense.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Condense.java @@ -20,14 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotArea; @@ -39,6 +31,14 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + @CommandDeclaration(command = "condense", permission = "plots.admin", description = "Condense a plotworld", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE) public class Condense extends SubCommand { @@ -126,7 +126,7 @@ public class Condense extends SubCommand { } start = Auto.getNextPlotId(start, 1); } - if ((free.size() == 0) || (to_move.size() == 0)) { + if ((free.isEmpty()) || (to_move.isEmpty())) { MainUtil.sendMessage(plr, "NO FREE PLOTS FOUND"); return false; } @@ -137,7 +137,7 @@ public class Condense extends SubCommand { if (!TASK) { MainUtil.sendMessage(plr, "TASK CANCELLED."); } - if (allPlots.size() == 0) { + if (allPlots.isEmpty()) { TASK = false; MainUtil.sendMessage(plr, "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); return; @@ -147,7 +147,7 @@ public class Condense extends SubCommand { int i = 0; while (free.size() > i) { final Plot possible = origin.getArea().getPlotAbs(free.get(i)); - if (possible.owner != null) { + if (possible.hasOwner()) { free.remove(i); continue; } @@ -166,7 +166,7 @@ public class Condense extends SubCommand { break; } } - if (free.size() == 0) { + if (free.isEmpty()) { TASK = false; MainUtil.sendMessage(plr, "TASK FAILED. NO FREE PLOTS FOUND!"); return; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/src/main/java/com/intellectualcrafters/plot/commands/Database.java index 0d62f65b0..5d529e284 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Database.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Database.java @@ -1,11 +1,5 @@ package com.intellectualcrafters.plot.commands; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map.Entry; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.MySQL; @@ -19,6 +13,12 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map.Entry; + @CommandDeclaration( command = "database", aliases = { "convert" }, @@ -101,7 +101,7 @@ public class Database extends SubCommand { for (final Entry entry2 : entry.getValue().entrySet()) { final Plot plot = entry2.getValue(); if (pa.getOwnedPlotAbs(plot.getId()) != null) { - MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp); + MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | type=" + plot.temp); continue; } PS.get().updatePlot(plot); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java index c6000204d..c961a4228 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java @@ -20,9 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.UUID; - import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; @@ -42,6 +39,10 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Map; +import java.util.UUID; + @CommandDeclaration( command = "debugclaimtest", description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. Execution time may vary", @@ -109,14 +110,14 @@ public class DebugClaimTest extends SubCommand { final String[] lines = WorldUtil.IMP.getSign(loc); if (lines != null) { String line = lines[2]; - if ((line != null) && (line.length() > 2)) { + if (line != null && line.length() > 2) { line = line.substring(2); final BiMap map = UUIDHandler.getUuidMap(); - UUID uuid = (map.get(new StringWrapper(line))); + UUID uuid = map.get(new StringWrapper(line)); if (uuid == null) { - for (final StringWrapper string : map.keySet()) { - if (string.value.toLowerCase().startsWith(line.toLowerCase())) { - uuid = map.get(string); + for (final Map.Entry stringWrapperUUIDEntry : map.entrySet()) { + if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) { + uuid = stringWrapperUUIDEntry.getValue(); break; } } @@ -134,7 +135,7 @@ public class DebugClaimTest extends SubCommand { } } } - if (plots.size() > 0) { + if (!plots.isEmpty()) { MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!"); DBFunc.createPlotsAndData(plots, new Runnable() { @Override diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java index 59064c5f7..51a4af66c 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java @@ -74,7 +74,8 @@ import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleScriptContext; -@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = { "exec" }, category = CommandCategory.DEBUG) +@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = "exec", + category = CommandCategory.DEBUG) public class DebugExec extends SubCommand { private ScriptEngine engine; @@ -85,13 +86,16 @@ public class DebugExec extends SubCommand { final File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js"); if (file.exists()) { init(); - final String script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"), StandardCharsets.UTF_8), - System.getProperty("line.separator")); + final String script = StringMan.join(Files + .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"), + StandardCharsets.UTF_8), + System.getProperty("line.separator")); scope.put("THIS", this); scope.put("PlotPlayer", ConsolePlayer.getConsole()); engine.eval(script, scope); } - } catch (final Exception e) {} + } catch (IOException | ScriptException e) { + } } public ScriptEngine getEngine() { @@ -106,9 +110,9 @@ public class DebugExec extends SubCommand { if (engine != null) { return; } - engine = (new ScriptEngineManager(null)).getEngineByName("nashorn"); + engine = new ScriptEngineManager(null).getEngineByName("nashorn"); if (engine == null) { - engine = (new ScriptEngineManager(null)).getEngineByName("JavaScript"); + engine = new ScriptEngineManager(null).getEngineByName("JavaScript"); } final ScriptContext context = new SimpleScriptContext(); scope = context.getBindings(ScriptContext.ENGINE_SCOPE); @@ -168,7 +172,7 @@ public class DebugExec extends SubCommand { final PlotAnalysis analysis = plot.getComplexity(); if (analysis != null) { final int complexity = analysis.getComplexity(); - MainUtil.sendMessage(player, "Changes/column: " + (analysis.changes / 1.0)); + MainUtil.sendMessage(player, "Changes/column: " + analysis.changes / 1.0); MainUtil.sendMessage(player, "Complexity: " + complexity); return true; } @@ -181,7 +185,7 @@ public class DebugExec extends SubCommand { }); return true; } - case "calibrate-analysis": { + case "calibrate-analysis": if (args.length != 2) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze "); MainUtil.sendMessage(player, "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating it)"); @@ -202,8 +206,7 @@ public class DebugExec extends SubCommand { } }, threshold); return true; - } - case "stop-expire": { + case "stop-expire": if (ExpireManager.task != -1) { PS.get().TASK.cancelTask(ExpireManager.task); } else { @@ -211,8 +214,7 @@ public class DebugExec extends SubCommand { } ExpireManager.task = -1; return MainUtil.sendMessage(player, "Cancelled task."); - } - case "remove-flag": { + case "remove-flag": if (args.length != 2) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag "); return false; @@ -224,20 +226,19 @@ public class DebugExec extends SubCommand { } } return MainUtil.sendMessage(player, "Cleared flag: " + flag); - } case "start-rgar": { if (args.length != 2) { MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar "); return false; } - boolean result; PlotArea area = PS.get().getPlotAreaByString(args[1]); if (area == null) { MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); return false; } + boolean result; if (HybridUtils.regions != null) { - result = ((HybridUtils.manager)).scheduleRoadUpdate(area, HybridUtils.regions, 0); + result = HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0); } else { result = HybridUtils.manager.scheduleRoadUpdate(area, 0); } @@ -247,7 +248,7 @@ public class DebugExec extends SubCommand { } return true; } - case "stop-rgar": { + case "stop-rgar": if (!HybridUtils.UPDATE) { MainUtil.sendMessage(player, "&cTASK NOT RUNNING!"); return false; @@ -255,16 +256,14 @@ public class DebugExec extends SubCommand { HybridUtils.UPDATE = false; MainUtil.sendMessage(player, "&cCancelling task... (please wait)"); return true; - } - case "start-expire": { + case "start-expire": if (ExpireManager.task == -1) { ExpireManager.runTask(); } else { return MainUtil.sendMessage(player, "Plot expiry task already started"); } return MainUtil.sendMessage(player, "Started plot expiry task"); - } - case "update-expired": { + case "update-expired": if (args.length > 1) { PlotArea area = PS.get().getPlotAreaByString(args[1]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { @@ -276,8 +275,7 @@ public class DebugExec extends SubCommand { return true; } return MainUtil.sendMessage(player, "Use /plot debugexec update-expired "); - } - case "show-expired": { + case "show-expired": if (args.length > 1) { final String world = args[1]; if (!WorldUtil.IMP.isWorld(world)) { @@ -294,8 +292,7 @@ public class DebugExec extends SubCommand { return true; } return MainUtil.sendMessage(player, "Use /plot debugexec show-expired "); - } - case "seen": { + case "seen": if (args.length != 2) { return MainUtil.sendMessage(player, "Use /plot debugexec seen "); } @@ -304,7 +301,7 @@ public class DebugExec extends SubCommand { return MainUtil.sendMessage(player, "player not found: " + args[1]); } final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); - if ((op == null) || (op.getLastPlayed() == 0)) { + if (op == null || op.getLastPlayed() == 0) { return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]); } final Timestamp stamp = new Timestamp(op.getLastPlayed()); @@ -315,8 +312,7 @@ public class DebugExec extends SubCommand { MainUtil.sendMessage(player, "GMT: " + date.toGMTString()); MainUtil.sendMessage(player, "Local: " + date.toLocaleString()); return true; - } - case "trim-check": { + case "trim-check": if (args.length != 2) { MainUtil.sendMessage(player, "Use /plot debugexec trim-check "); MainUtil.sendMessage(player, "&7 - Generates a list of regions to trim"); @@ -332,12 +328,11 @@ public class DebugExec extends SubCommand { public void run() { Trim.sendMessage("Processing is complete! Here's how many chunks would be deleted:"); Trim.sendMessage(" - MCA #: " + empty.size()); - Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)"); + Trim.sendMessage(" - CHUNKS: " + empty.size() * 1024 + " (max)"); Trim.sendMessage("Exporting log for manual approval..."); final File file = new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt"); - PrintWriter writer; try { - writer = new PrintWriter(file); + PrintWriter writer = new PrintWriter(file); for (final ChunkLoc loc : empty) { writer.println(world + "/region/r." + loc.x + "." + loc.z + ".mca"); } @@ -357,18 +352,18 @@ public class DebugExec extends SubCommand { MainUtil.sendMessage(player, "Trim task already started!"); } return result; - } case "h": case "he": case "?": - case "help": { + case "help": MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">"); return false; - } - case "addcmd": { + case "addcmd": try { - final String cmd = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), - System.getProperty("line.separator")); + final String cmd = StringMan.join(Files + .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), + StandardCharsets.UTF_8), + System.getProperty("line.separator")); final Command subcommand = new Command(args[1].split("\\.")[0]) { @Override public boolean onCommand(final PlotPlayer plr, final String[] args) { @@ -386,16 +381,14 @@ public class DebugExec extends SubCommand { }; MainCommand.getInstance().addCommand(subcommand); return true; - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); return false; } - } - case "runasync": { + case "runasync": async = true; - } - case "run": { + case "run": try { script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), System.getProperty("line.separator")); @@ -411,8 +404,7 @@ public class DebugExec extends SubCommand { return false; } break; - } - case "allcmd": { + case "allcmd": if (args.length < 3) { C.COMMAND_SYNTAX.send(player, "/plot debugexec allcmd "); return false; @@ -420,9 +412,9 @@ public class DebugExec extends SubCommand { long start = System.currentTimeMillis(); Command cmd = MainCommand.getInstance().getCommand(args[3]); String[] params = Arrays.copyOfRange(args, 4, args.length); - if (args[1].equals("true")) { - Location loc = (Location) player.getMeta("location"); - Plot plot = (Plot) player.getMeta("lastplot"); + if ("true".equals(args[1])) { + Location loc = player.getMeta("location"); + Plot plot = player.getMeta("lastplot"); for (Plot current : PS.get().getBasePlots()) { player.setMeta("location", current.getBottomAbs()); player.setMeta("lastplot", current); @@ -445,19 +437,20 @@ public class DebugExec extends SubCommand { scope.put("_2", params); scope.put("_3", cmd); script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand(PlotPlayer,_2)}}"; + break; - } - case "all": { + case "all": if (args.length < 3) { C.COMMAND_SYNTAX.send(player, "/plot debugexec all "); return false; } - script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ") + "}}"; + script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan + .join(Arrays.copyOfRange(args, 2, args.length), " ") + + "}}"; + break; - } - default: { + default: script = StringMan.join(args, " "); - } } if (!ConsolePlayer.isConsole(player)) { MainUtil.sendMessage(player, C.NOT_CONSOLE); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Desc.java b/src/main/java/com/intellectualcrafters/plot/commands/Desc.java index 151399546..9b6fae68e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Desc.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Desc.java @@ -40,7 +40,7 @@ public class Desc extends SetCommand { @Override public boolean set(PlotPlayer plr, Plot plot, String desc) { - if (desc.length() == 0) { + if (desc.isEmpty()) { plot.removeFlag("description"); MainUtil.sendMessage(plr, C.DESC_UNSET); return true; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java index c99e830ec..eeeeb4aaf 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java @@ -20,10 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.flag.AbstractFlag; @@ -38,6 +34,11 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + @CommandDeclaration( command = "setflag", aliases = { "f", "flag", "setf", "setflag" }, @@ -81,7 +82,7 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag.other"); return false; } - if ((args.length > 1) && FlagManager.isReserved(args[1])) { + if (args.length > 1 && FlagManager.isReserved(args[1])) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } @@ -147,7 +148,7 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.remove"); return false; } - if ((args.length != 2) && (args.length != 3)) { + if (args.length != 2 && args.length != 3) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); return false; } @@ -173,7 +174,7 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.FLAG_NOT_IN_PLOT); return false; } - if ((args.length == 3) && flag.getAbstractFlag().isList()) { + if (args.length == 3 && flag.getAbstractFlag().isList()) { final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); ((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value); DBFunc.setFlags(plot, plot.getFlags().values()); @@ -214,7 +215,7 @@ public class FlagCmd extends SubCommand { return false; } Flag flag = FlagManager.getPlotFlag(plot, args[1].toLowerCase()); - if ((flag == null) || !flag.getAbstractFlag().isList()) { + if (flag == null || !flag.getAbstractFlag().isList()) { flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed); } else { ((FlagValue.ListValue) flag.getAbstractFlag().value).add(flag.getValue(), value); @@ -228,7 +229,7 @@ public class FlagCmd extends SubCommand { MainUtil.sendMessage(player, C.FLAG_ADDED); return true; } - case "list": { + case "list": if (!Permissions.hasPermission(player, "plots.flag.list")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.list"); return false; @@ -247,13 +248,12 @@ public class FlagCmd extends SubCommand { } String message = ""; String prefix = ""; - for (final String flag : flags.keySet()) { - message += prefix + "&6" + flag + ": &7" + StringMan.join(flags.get(flag), ", "); + for (final Map.Entry> stringArrayListEntry : flags.entrySet()) { + message += prefix + "&6" + stringArrayListEntry.getKey() + ": &7" + StringMan.join(stringArrayListEntry.getValue(), ", "); prefix = "\n"; } MainUtil.sendMessage(player, message); return true; - } } MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag "); return false; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java b/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java index 0348c766a..46d516390 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java @@ -1,5 +1,10 @@ package com.intellectualcrafters.plot.commands; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.StringMan; +import com.plotsquared.general.commands.Command; + import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -11,11 +16,6 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.Command; - public class GenerateDocs { public static void main(final String[] args) { MainCommand.getInstance().addCommand(new WE_Anywhere()); @@ -56,7 +56,7 @@ public class GenerateDocs { log("#### Description"); log("`" + command.getDescription() + "`"); - if (comment.length() > 0) { + if (!comment.isEmpty()) { log("##### Comments"); log("``` java"); log(comment); @@ -72,7 +72,7 @@ public class GenerateDocs { } final Set aliases = command.getAliases(); - if (aliases.size() > 0) { + if (!aliases.isEmpty()) { log("#### Aliases"); log("`" + StringMan.getString(command.getAliases()) + "`"); } @@ -80,7 +80,7 @@ public class GenerateDocs { log("#### Permissions"); log("##### Primary"); log(" - `" + command.getPermission() + "` "); - if (perms.size() > 0) { + if (!perms.isEmpty()) { log(""); log("##### Other"); log(" - `" + StringMan.join(perms, "`\n - `") + "`"); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Home.java b/src/main/java/com/intellectualcrafters/plot/commands/Home.java index 4a597d2b1..733ec44b7 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Home.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Home.java @@ -23,7 +23,8 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "home", aliases = { "h" }, description = "Go to your plot", usage = "/plot home [id|alias]", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) +@CommandDeclaration(command = "home", aliases = {"h"}, description = "Go to your plot", usage = "/plot home [type|alias]", + category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) public class Home extends SubCommand { @Override diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java index 2dce85fa2..1d0576f99 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java @@ -20,9 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.List; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; @@ -34,6 +31,9 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.List; + @CommandDeclaration( command = "inbox", description = "Review the comments for a plot", @@ -44,7 +44,7 @@ requiredType = RequiredType.NONE) public class Inbox extends SubCommand { public void displayComments(final PlotPlayer player, final List oldComments, int page) { - if ((oldComments == null) || (oldComments.size() == 0)) { + if ((oldComments == null) || (oldComments.isEmpty())) { MainUtil.sendMessage(player, C.INBOX_EMPTY); return; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/src/main/java/com/intellectualcrafters/plot/commands/Info.java index f9360cc8d..7bf0dcfcd 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Info.java @@ -20,8 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.UUID; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Plot; @@ -32,7 +30,10 @@ import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "info", aliases = { "i" }, description = "Display plot info", usage = "/plot info ", category = CommandCategory.INFO) +import java.util.UUID; + +@CommandDeclaration(command = "info", aliases = {"i"}, description = "Display plot info", usage = "/plot info ", + category = CommandCategory.INFO) public class Info extends SubCommand { @Override @@ -48,7 +49,7 @@ public class Info extends SubCommand { case "biome": case "denied": case "flags": - case "id": + case "type": case "size": case "members": case "owner": @@ -156,7 +157,7 @@ public class Info extends SubCommand { return C.PLOT_INFO_DENIED.s(); case "flags": return C.PLOT_INFO_FLAGS.s(); - case "id": + case "type": return C.PLOT_INFO_ID.s(); case "size": return C.PLOT_INFO_SIZE.s(); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Load.java b/src/main/java/com/intellectualcrafters/plot/commands/Load.java index 6514c3068..4b1c0d599 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Load.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Load.java @@ -1,9 +1,5 @@ package com.intellectualcrafters.plot.commands; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -18,6 +14,10 @@ import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + @CommandDeclaration( command = "load", aliases = { "restore" }, @@ -121,7 +121,7 @@ public class Load extends SubCommand { public void run() { final List schematics = SchematicHandler.manager.getSaves(plr.getUUID()); plot.removeRunning(); - if ((schematics == null) || (schematics.size() == 0)) { + if ((schematics == null) || (schematics.isEmpty())) { MainUtil.sendMessage(plr, C.LOAD_FAILED); return; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index 27bf94352..889ecea32 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -55,13 +55,6 @@ public class MainCommand extends CommandManager { private static MainCommand instance; private HashMap> setCommands; - public static MainCommand getInstance() { - if (instance == null) { - instance = new MainCommand(); - } - return instance; - } - private MainCommand() { super(null, new ArrayList>()); instance = this; @@ -141,6 +134,13 @@ public class MainCommand extends CommandManager { } } + public static MainCommand getInstance() { + if (instance == null) { + instance = new MainCommand(); + } + return instance; + } + public static boolean no_permission(final PlotPlayer player, final String permission) { MainUtil.sendMessage(player, C.NO_PERMISSION, permission); return false; @@ -347,9 +347,9 @@ public class MainCommand extends CommandManager { require = 0; } String[] split = usage[i].split("\\|| |\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/"); - for (int j = 0; j < split.length; j++) { + for (String aSplit : split) { for (String arg : args) { - if (StringMan.isEqualIgnoreCase(arg, split[j])) { + if (StringMan.isEqualIgnoreCase(arg, aSplit)) { count += 5 - i + require; } } @@ -395,7 +395,7 @@ public class MainCommand extends CommandManager { MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); { final List> cmds = getCommands(null, plr); - if ((label == null) || (cmds.size() == 0)) { + if ((label == null) || (cmds.isEmpty())) { MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); } else { final HashSet setargs = new HashSet<>(args.length + 1); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/src/main/java/com/intellectualcrafters/plot/commands/Merge.java index ebb92c895..3f013d6a0 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Merge.java @@ -20,9 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.HashSet; -import java.util.UUID; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.Location; @@ -37,14 +34,12 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( -command = "merge", -aliases = { "m" }, -description = "Merge the plot you are standing on, with another plot", -permission = "plots.merge", -usage = "/plot merge [removeroads]", -category = CommandCategory.SETTINGS, -requiredType = RequiredType.NONE) +import java.util.HashSet; +import java.util.UUID; + +@CommandDeclaration(command = "merge", aliases = "m", description = "Merge the plot you are standing on, with another plot", + permission = "plots.merge", usage = "/plot merge [removeroads]", category = CommandCategory.SETTINGS, + requiredType = RequiredType.NONE) public class Merge extends SubCommand { public final static String[] values = new String[] { "north", "east", "south", "west", "auto" }; public final static String[] aliases = new String[] { "n", "e", "s", "w", "all" }; @@ -93,17 +88,18 @@ public class Merge extends SubCommand { } } final PlotArea plotworld = plot.getArea(); - if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d && EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) { + if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d + && EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) { sendMessage(plr, C.CANNOT_AFFORD_MERGE, plotworld.MERGE_PRICE + ""); return false; } - int direction = -1; final int size = plot.getConnectedPlots().size(); final int maxSize = Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS); if (size - 1> maxSize) { MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.merge." + (size + 1)); return false; } + int direction = -1; if (args.length == 0) { // switch (direction(plr.getLocationFull().getYaw())) { // case "NORTH": @@ -120,13 +116,13 @@ public class Merge extends SubCommand { // break; // } } else { - if (args[0].equalsIgnoreCase("all") || args[0].equalsIgnoreCase("auto")) { + if ("all".equalsIgnoreCase(args[0]) || "auto".equalsIgnoreCase(args[0])) { boolean terrain = Settings.MERGE_REMOVES_ROADS; if (args.length == 2) { - terrain = args[1].equalsIgnoreCase("true"); + terrain = "true".equalsIgnoreCase(args[1]); } if (plot.autoMerge(-1, maxSize, uuid, terrain)) { - if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) { + if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) { EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE); sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + ""); } @@ -151,12 +147,12 @@ public class Merge extends SubCommand { } final boolean terrain; if (args.length == 2) { - terrain = args[1].equalsIgnoreCase("true"); + terrain = "true".equalsIgnoreCase(args[1]); } else { terrain = Settings.MERGE_REMOVES_ROADS; } if (plot.autoMerge(direction, maxSize - size, uuid, terrain)) { - if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) { + if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) { EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE); sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + ""); } @@ -191,7 +187,7 @@ public class Merge extends SubCommand { sendMessage(accepter, C.MERGE_NOT_VALID); return; } - if ((EconHandler.manager != null) && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) { + if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) { if (EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) { sendMessage(plr, C.CANNOT_AFFORD_MERGE, plotworld.MERGE_PRICE + ""); return; diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/src/main/java/com/intellectualcrafters/plot/commands/Purge.java index 36e0ef8e3..8ab74db54 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Purge.java @@ -39,7 +39,7 @@ import java.util.Set; import java.util.UUID; @CommandDeclaration( -usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", + usage = "/plot purge world: area: type: owner: shared: unknown:[true|false]", command = "purge", permission = "plots.admin", description = "Purge all plots for a world", @@ -80,7 +80,7 @@ public class Purge extends SubCommand { break; } case "plotid": - case "id": { + case "type": { id = PlotId.fromString(split[1]); if (id == null) { C.NOT_VALID_PLOT_ID.send(plr, split[1]); @@ -169,7 +169,7 @@ public class Purge extends SubCommand { } } } - if (toDelete.size() == 0) { + if (toDelete.isEmpty()) { C.FOUND_NO_PLOTS.send(plr); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index aebbba758..c062fcdc4 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -20,15 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.UUID; - -import org.apache.commons.lang.mutable.MutableInt; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -45,6 +36,14 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; +import org.apache.commons.lang.mutable.MutableInt; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map.Entry; +import java.util.UUID; @CommandDeclaration( command = "rate", @@ -113,7 +112,7 @@ public class Rate extends SubCommand { sendMessage(player, C.RATING_NOT_DONE); return false; } - if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() != 0)) { + if ((Settings.RATING_CATEGORIES != null) && (!Settings.RATING_CATEGORIES.isEmpty())) { final Runnable run = new Runnable() { @Override public void run() { @@ -183,7 +182,7 @@ public class Rate extends SubCommand { } final String arg = args[0]; final int rating; - if (MathMan.isInteger(arg) && (arg.length() < 3) && (arg.length() > 0)) { + if (MathMan.isInteger(arg) && (arg.length() < 3) && (!arg.isEmpty())) { rating = Integer.parseInt(arg); if (rating > 10 || rating < 1) { sendMessage(player, C.RATING_NOT_VALID); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java index beb50086c..29d97bd46 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java @@ -20,11 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.UUID; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -41,6 +36,11 @@ import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + @CommandDeclaration( command = "schematic", permission = "plots.schematic", @@ -153,7 +153,7 @@ public class SchematicCmd extends SubCommand { // } // final int l1 = schematic.getSchematicDimension().getX(); // final int l2 = schematic.getSchematicDimension().getZ(); -// final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.id); + // final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.type); // if ((l1 < length) || (l2 < length)) { // sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); // break; @@ -177,7 +177,7 @@ public class SchematicCmd extends SubCommand { return false; } final Collection plots = area.getPlots(); - if ((plots.size() == 0)) { + if ((plots.isEmpty())) { MainUtil.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall "); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/src/main/java/com/intellectualcrafters/plot/commands/Setup.java index de0055ea7..9dc3756e5 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Setup.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Setup.java @@ -20,11 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map.Entry; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.ConfigurationNode; @@ -39,6 +34,11 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map.Entry; + @CommandDeclaration( command = "setup", permission = "plots.admin.command.setup", @@ -172,14 +172,14 @@ public class Setup extends SubCommand { } break; } - case 2: { // area id + case 2: { // area type if (!StringMan.isAlphanumericUnd(args[0])) { - MainUtil.sendMessage(plr, "&cThe area id must be alphanumerical!"); + MainUtil.sendMessage(plr, "&cThe area type must be alphanumerical!"); return false; } for (PlotArea area : PS.get().getPlotAreas()) { if (area.id != null && area.id.equalsIgnoreCase(args[0])) { - MainUtil.sendMessage(plr, "&cYou must choose an area id that is not in use!"); + MainUtil.sendMessage(plr, "&cYou must choose an area type that is not in use!"); return false; } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java b/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java index 1042d986f..0b7fdd49b 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java @@ -20,20 +20,19 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.List; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotMessage; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal3; import com.intellectualcrafters.plot.util.MainUtil; +import java.util.List; + /** * SubCommand class * */ -@SuppressWarnings({ "deprecation" }) public abstract class SubCommand extends com.plotsquared.general.commands.Command { /** @@ -64,7 +63,7 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman if (page > totalPages) { page = totalPages; } - int max = (page * size) + size; + int max = page * size + size; if (max > c.size()) { max = c.size(); } @@ -81,18 +80,20 @@ public abstract class SubCommand extends com.plotsquared.general.commands.Comman msg.send(player); } // Send the footer - if ((page < totalPages) && (page > 0)) { // Back | Next - new PlotMessage().text("<-").color("$1").command(baseCommand + " " + (page)).text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)) + if (page < totalPages && page > 0) { // Back | Next + new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$1") + .command(baseCommand + " " + (page + 2)) .text(C.CLICKABLE.s()).color("$2").send(player); return; } - if ((page == 0) && (totalPages != 0)) { // Next + if (page == 0 && totalPages != 0) { // Next new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)).text(C.CLICKABLE.s()).color("$2").send(player); return; } - if ((page == totalPages) && (totalPages != 0)) { // Back - new PlotMessage().text("<-").color("$1").command(baseCommand + " " + (page)).text(" | ").color("$3").text("->").color("$3").text(C.CLICKABLE.s()).color("$2").send(player); - return; + if (page == totalPages && totalPages != 0) { // Back + new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$3") + .text(C.CLICKABLE.s()).color("$2").send(player); + } } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/src/main/java/com/intellectualcrafters/plot/commands/Template.java index 62b4561a2..c9f687052 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Template.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Template.java @@ -20,15 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.file.YamlConfiguration; import com.intellectualcrafters.plot.PS; @@ -46,6 +37,16 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + @CommandDeclaration( command = "template", permission = "plots.admin", @@ -55,7 +56,6 @@ category = CommandCategory.ADMINISTRATION) public class Template extends SubCommand { public static boolean extractAllFiles(final String world, final String template) { - final byte[] buffer = new byte[2048]; try { final File folder = new File(PS.get().IMP.getDirectory() + File.separator + "templates"); if (!folder.exists()) { @@ -66,24 +66,28 @@ public class Template extends SubCommand { if (!output.exists()) { output.mkdirs(); } - final ZipInputStream zis = new ZipInputStream(new FileInputStream(input)); - ZipEntry ze = zis.getNextEntry(); - while (ze != null) { - final String name = ze.getName().replace('\\', File.separatorChar).replace('/', File.separatorChar); - final File newFile = new File((output + File.separator + name).replaceAll("__TEMP_DIR__", world)); - new File(newFile.getParent()).mkdirs(); - final FileOutputStream fos = new FileOutputStream(newFile); - int len; - while ((len = zis.read(buffer)) > 0) { - fos.write(buffer, 0, len); + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input))) { + ZipEntry ze = zis.getNextEntry(); + final byte[] buffer = new byte[2048]; + while (ze != null) { + final String name = ze.getName().replace('\\', File.separatorChar).replace('/', File.separatorChar); + final File newFile = new File((output + File.separator + name).replaceAll("__TEMP_DIR__", world)); + new File(newFile.getParent()).mkdirs(); + try (FileOutputStream fos = new FileOutputStream(newFile)) { + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + } + ze = zis.getNextEntry(); } - fos.close(); - ze = zis.getNextEntry(); + zis.closeEntry(); } - zis.closeEntry(); - zis.close(); return true; - } catch (final Exception e) { + } catch (FileNotFoundException e) { + e.printStackTrace(); + return false; + } catch (IOException e) { e.printStackTrace(); return false; } @@ -105,21 +109,21 @@ public class Template extends SubCommand { public static void zipAll(final String world, final Set files) throws IOException { final File output = new File(PS.get().IMP.getDirectory() + File.separator + "templates"); output.mkdirs(); - final FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template"); - final ZipOutputStream zos = new ZipOutputStream(fos); - - for (final FileBytes file : files) { - final ZipEntry ze = new ZipEntry(file.path); - zos.putNextEntry(ze); - zos.write(file.data); + try (FileOutputStream fos = new FileOutputStream(output + File.separator + world + ".template"); + ZipOutputStream zos = new ZipOutputStream(fos)) { + + for (final FileBytes file : files) { + final ZipEntry ze = new ZipEntry(file.path); + zos.putNextEntry(ze); + zos.write(file.data); + } + zos.closeEntry(); } - zos.closeEntry(); - zos.close(); } @Override public boolean onCommand(final PlotPlayer plr, final String[] args) { - if ((args.length != 2) && (args.length != 3)) { + if (args.length != 2 && args.length != 3) { if (args.length == 1) { if (args[0].equalsIgnoreCase("export")) { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export "); @@ -186,7 +190,7 @@ public class Template extends SubCommand { }); return true; } - case "export": { + case "export": if (args.length != 2) { MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot template export "); return false; @@ -197,25 +201,22 @@ public class Template extends SubCommand { return false; } final PlotManager manager = area.getPlotManager(); - final PlotPlayer finalPlr = plr; TaskManager.runTaskAsync(new Runnable() { @Override public void run() { try { manager.exportTemplate(area); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); - MainUtil.sendMessage(finalPlr, "Failed: " + e.getMessage()); + MainUtil.sendMessage(plr, "Failed: " + e.getMessage()); return; } - MainUtil.sendMessage(finalPlr, "Done!"); + MainUtil.sendMessage(plr, "Done!"); } }); return true; - } - default: { + default: C.COMMAND_SYNTAX.send(plr, getUsage()); - } } return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java b/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java index b9ae86c7e..c6745053a 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java @@ -20,11 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map.Entry; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.PlotPlayer; @@ -34,6 +29,11 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map.Entry; + @CommandDeclaration( command = "toggle", aliases = { "attribute" }, @@ -44,25 +44,12 @@ requiredType = RequiredType.NONE, category = CommandCategory.SETTINGS) public class Toggle extends SubCommand { - public void noArgs(final PlotPlayer plr) { - MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot toggle "); - final ArrayList options = new ArrayList<>(); - for (final Entry> 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> toggles; public Toggle() { toggles = new HashMap<>(); toggles.put("titles", new Command("titles", "/plot toggle titles", "Toggle titles for yourself", C.PERMISSION_PLOT_TOGGLE_TITLES.s()) { - + @Override public boolean onCommand(final PlotPlayer player, final String[] args) { if (toggle(player, "disabletitles")) { @@ -74,7 +61,7 @@ public class Toggle extends SubCommand { } }); toggles.put("chatspy", new Command("chatspy", "/plot toggle chatspy", "Toggle chat spying", C.PERMISSION_COMMANDS_CHAT.s()) { - + @Override public boolean onCommand(final PlotPlayer player, final String[] args) { if (toggle(player, "chatspy")) { @@ -86,7 +73,7 @@ public class Toggle extends SubCommand { } }); toggles.put("chat", new Command("chat", "/plot toggle chat", "Toggle plot chat for yourself", C.PERMISSION_PLOT_TOGGLE_CHAT.s()) { - + @Override public boolean onCommand(final PlotPlayer player, final String[] args) { if (toggle(player, "chat")) { @@ -99,7 +86,7 @@ public class Toggle extends SubCommand { }); if (PS.get() != null && PS.get().worldedit != null) { toggles.put("worldedit", new Command("worldedit", "/plot toggle worldedit", "Toggle worldedit bypass", C.PERMISSION_WORLDEDIT_BYPASS.s()) { - + @Override public boolean onCommand(final PlotPlayer player, final String[] args) { if (toggle(player, "worldedit")) { @@ -111,7 +98,20 @@ public class Toggle extends SubCommand { } }); } - + + } + + public void noArgs(final PlotPlayer plr) { + MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot toggle "); + final ArrayList options = new ArrayList<>(); + for (final Entry> 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 diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Trim.java b/src/main/java/com/intellectualcrafters/plot/commands/Trim.java index ffce269ba..fdd1af3f9 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Trim.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Trim.java @@ -20,15 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.HashSet; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.ChunkLoc; @@ -43,6 +34,15 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.HashSet; + @CommandDeclaration( command = "trim", permission = "plots.admin", @@ -76,7 +76,7 @@ public class Trim extends SubCommand { final int z = Integer.parseInt(split[2]); final ChunkLoc loc = new ChunkLoc(x, z); empty.add(loc); - } catch (final Exception e) { + } catch (NumberFormatException e) { PS.debug("INVALID MCA: " + name); } } else { @@ -97,7 +97,7 @@ public class Trim extends SubCommand { PS.debug("INVALID MCA: " + name); } } - } catch (IOException e) { + } catch (IOException ignored) { } } } @@ -127,7 +127,7 @@ public class Trim extends SubCommand { public void run() { final long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 50) { - if (plots.size() == 0) { + if (plots.isEmpty()) { empty.addAll(chunks); Trim.TASK = false; TaskManager.runTaskAsync(whenDone); diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Visit.java b/src/main/java/com/intellectualcrafters/plot/commands/Visit.java index 3156ebfae..7d514ee7e 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Visit.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/Visit.java @@ -20,14 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Plot; @@ -39,11 +31,19 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + @CommandDeclaration( command = "visit", permission = "plots.visit", description = "Visit someones plot", -usage = "/plot visit [player|alias|world|id] [#]", + usage = "/plot visit [player|alias|world|type] [#]", aliases = { "v", "tp", "teleport", "goto" }, requiredType = RequiredType.NONE, category = CommandCategory.TELEPORT) @@ -110,7 +110,7 @@ public class Visit extends SubCommand { if (page == Integer.MIN_VALUE) { page = 1; } - if (unsorted == null || unsorted.size() == 0) { + if (unsorted == null || unsorted.isEmpty()) { sendMessage(player, C.FOUND_NO_PLOTS); return false; } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/list.java b/src/main/java/com/intellectualcrafters/plot/commands/list.java index 71dbc3fe2..1eb24f018 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/list.java +++ b/src/main/java/com/intellectualcrafters/plot/commands/list.java @@ -20,15 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.UUID; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS.SortType; import com.intellectualcrafters.plot.config.C; @@ -49,6 +40,15 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.UUID; + @CommandDeclaration( command = "list", aliases = { "l", "find", "search" }, @@ -346,8 +346,8 @@ public class list extends SubCommand { sendMessage(plr, C.DID_YOU_MEAN, new StringComparison(args[0], new String[] { "mine", "shared", "world", "all" }).getBestMatch()); return false; } - - if (plots.size() == 0) { + + if (plots.isEmpty()) { MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS); return false; } @@ -384,7 +384,7 @@ public class list extends SubCommand { final PlotMessage trusted = new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s().replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))).color("$1"); final PlotMessage members = new PlotMessage().text(C.color(C.PLOT_INFO_MEMBERS.s().replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))).color("$1"); String strFlags = StringMan.join(plot.getFlags().values(), ","); - if (strFlags.length() == 0) { + if (strFlags.isEmpty()) { strFlags = C.NONE.s(); } final PlotMessage flags = new PlotMessage().text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))).color("$1"); diff --git a/src/main/java/com/intellectualcrafters/plot/config/C.java b/src/main/java/com/intellectualcrafters/plot/config/C.java index 18c8dd099..1a26d023a 100644 --- a/src/main/java/com/intellectualcrafters/plot/config/C.java +++ b/src/main/java/com/intellectualcrafters/plot/config/C.java @@ -20,6 +20,13 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.config; +import com.intellectualcrafters.configuration.ConfigurationSection; +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.StringMan; +import com.plotsquared.general.commands.CommandCaller; + import java.io.File; import java.util.EnumSet; import java.util.HashMap; @@ -28,13 +35,6 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.CommandCaller; - /** * Captions class. * @@ -150,7 +150,7 @@ public enum C { CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"), CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"), CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"), - CLUSTER_INFO("$1Current cluster: $2%id%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", "Cluster"), + CLUSTER_INFO("$1Current cluster: $2%type%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", "Cluster"), /* * Border */ @@ -187,7 +187,7 @@ public enum C { */ SWAP_OVERLAP("$2The proposed areas are not allowed to overlap", "Swap"), SWAP_DIMENSIONS("$2The proposed areas must have comparable dimensions", "Swap"), - SWAP_SYNTAX("$2/plots swap ", "Swap"), + SWAP_SYNTAX("$2/plots swap ", "Swap"), SWAP_SUCCESS("$4Successfully swapped plots", "Swap"), STARTED_SWAP("$2Started plot swap task. You will be notified when it finishes", "Swap"), /* @@ -225,7 +225,7 @@ public enum C { PASTED("$4The plot selection was successfully pasted. It has been cleared from your clipboard.", "Clipboard"), PASTE_FAILED("$2Failed to paste the selection. Reason: $2%s", "Clipboard"), NO_CLIPBOARD("$2You don't have a selection in your clipboard", "Clipboard"), - CLIPBOARD_INFO("$2Current Selection - Plot ID: $1%id$2, Width: $1%width$2, Total Blocks: $1%total$2", "Clipboard"), + CLIPBOARD_INFO("$2Current Selection - Plot ID: $1%type$2, Width: $1%width$2, Total Blocks: $1%total$2", "Clipboard"), /* * Toggle */ @@ -298,8 +298,8 @@ public enum C { */ TITLE_ENTERED_PLOT("$1Plot: %world%;%x%;%z%", "Titles"), TITLE_ENTERED_PLOT_SUB("$4Owned by %s", "Titles"), - PREFIX_GREETING("$1%id%$2> ", "Titles"), - PREFIX_FAREWELL("$1%id%$2> ", "Titles"), + PREFIX_GREETING("$1%type%$2> ", "Titles"), + PREFIX_FAREWELL("$1%type%$2> ", "Titles"), /* * Core Stuff */ @@ -315,7 +315,7 @@ public enum C { /* * BarAPI */ - BOSSBAR_CLEARING("$2Clearing plot: $1%id%", "Bar API"), + BOSSBAR_CLEARING("$2Clearing plot: $1%type%", "Bar API"), DESC_SET("$2Plot description set", "Desc"), DESC_UNSET("$2Plot description unset", "Desc"), @@ -443,12 +443,12 @@ public enum C { /* * Invalid */ - NOT_VALID_DATA("$2That's not a valid data id.", "Invalid"), + NOT_VALID_DATA("$2That's not a valid data type.", "Invalid"), NOT_VALID_BLOCK("$2That's not a valid block: %s", "Invalid"), NOT_ALLOWED_BLOCK("$2That block is not allowed: %s", "Invalid"), NOT_VALID_NUMBER("$2That's not a valid number within the range: %s", "Invalid"), - NOT_VALID_PLOT_ID("$2That's not a valid plot id.", "Invalid"), - PLOT_ID_FORM("$2The plot id must be in the form: $1X;Y $2e.g. $1-5;7", "Invalid"), + NOT_VALID_PLOT_ID("$2That's not a valid plot type.", "Invalid"), + PLOT_ID_FORM("$2The plot type must be in the form: $1X;Y $2e.g. $1-5;7", "Invalid"), NOT_YOUR_PLOT("$2That is not your plot.", "Invalid"), NO_SUCH_PLOT("$2There is no such plot", "Invalid"), PLAYER_HAS_NOT_BEEN_ON("$2That player hasn't been in the plotworld", "Invalid"), @@ -463,7 +463,7 @@ public enum C { */ NEED_PLOT_NUMBER("$2You've got to specify a plot number or alias", "Need"), NEED_BLOCK("$2You've got to specify a block", "Need"), - NEED_PLOT_ID("$2You've got to specify a plot id.", "Need"), + NEED_PLOT_ID("$2You've got to specify a plot type.", "Need"), NEED_PLOT_WORLD("$2You've got to specify a plot area.", "Need"), NEED_USER("$2You need to specify a username", "Need"), /* @@ -475,7 +475,7 @@ public enum C { PLOT_UNOWNED("$2The current plot must have an owner to perform this action", "Info"), PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"), PLOT_INFO_HEADER("$3&m---------&r $1INFO $3&m---------", false, "Info"), - PLOT_INFO("$1ID: $2%id%$1&-" + PLOT_INFO("$1ID: $2%type%$1&-" + "$1Alias: $2%alias%$1&-" + "$1Owner: $2%owner%$1&-" + "$1Biome: $2%biome%$1&-" @@ -493,7 +493,7 @@ public enum C { PLOT_INFO_BIOME("$1Biome:$2 %biome%", "Info"), PLOT_INFO_RATING("$1Rating:$2 %rating%", "Info"), PLOT_INFO_OWNER("$1Owner:$2 %owner%", "Info"), - PLOT_INFO_ID("$1ID:$2 %id%", "Info"), + PLOT_INFO_ID("$1ID:$2 %type%", "Info"), PLOT_INFO_ALIAS("$1Alias:$2 %alias%", "Info"), PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"), PLOT_USER_LIST(" $1%user%$2,", "Info"), @@ -521,8 +521,8 @@ public enum C { AREA_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% areas", "List"), PLOT_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% plots", "List"), PLOT_LIST_HEADER("$1List of %word% plots", "List"), - PLOT_LIST_ITEM("$2>> $1%id$2:$1%world $2- $1%owner", "List"), - PLOT_LIST_ITEM_ORDERED("$2[$1%in$2] >> $1%id$2:$1%world $2- $1%owner", "List"), + PLOT_LIST_ITEM("$2>> $1%type$2:$1%world $2- $1%owner", "List"), + PLOT_LIST_ITEM_ORDERED("$2[$1%in$2] >> $1%type$2:$1%world $2- $1%owner", "List"), PLOT_LIST_FOOTER("$2>> $1%word% a total of $2%num% $1claimed %plot%.", "List"), /* * Left @@ -595,7 +595,7 @@ public enum C { /* * Signs */ - OWNER_SIGN_LINE_1("$1ID: $1%id%", "Signs"), + OWNER_SIGN_LINE_1("$1ID: $1%type%", "Signs"), OWNER_SIGN_LINE_2("$1Owner:", "Signs"), OWNER_SIGN_LINE_3("$2%plr%", "Signs"), OWNER_SIGN_LINE_4("$3Claimed", "Signs"), @@ -670,11 +670,6 @@ public enum C { this(d, true, cat.toLowerCase()); } - @Override - public String toString() { - return s; - } - public static String format(String m, final Object... args) { if (args.length == 0) { return m; @@ -683,7 +678,7 @@ public enum C { if (args.length > 0) { for (int i = args.length - 1; i >= 0; i--) { String arg = args[i].toString(); - if (arg == null || arg.length() == 0) { + if (arg == null || arg.isEmpty()) { map.put("%s" + i, ""); } else { arg = C.color(arg); @@ -784,6 +779,11 @@ public enum C { e.printStackTrace(); } } + + @Override + public String toString() { + return s; + } public String s() { return s; diff --git a/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java b/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java index 9ee60fcf4..f3fa33007 100644 --- a/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java +++ b/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java @@ -20,15 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.database; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotArea; @@ -38,6 +29,15 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.object.comment.PlotComment; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + /** @@ -123,7 +123,7 @@ public interface AbstractDB { int getId(final Plot plot); /** - * Get the id of a given plot cluster + * Get the type of a given plot cluster * * @param cluster PlotCluster Object * @@ -193,15 +193,14 @@ public interface AbstractDB { /** * Purgle a plot * - * @param world World in which the plot is located - * @param uniqueIds list of plot id (db) to be purged + * @param uniqueIds list of plot type (db) to be purged */ void purgeIds(final Set uniqueIds); /** * Purge a whole world * - * @param world World in which the plots should be purged + * @param area World in which the plots should be purged */ void purge(final PlotArea area, final Set plotIds); diff --git a/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java b/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java index 5d31ef608..1049a941c 100644 --- a/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java +++ b/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java @@ -20,6 +20,14 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.database; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.comment.PlotComment; + import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -30,14 +38,6 @@ import java.util.List; import java.util.Set; import java.util.UUID; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.comment.PlotComment; - /** * Database Functions * - These functions do not update the local plot objects and only make changes to the DB @@ -241,7 +241,7 @@ public class DBFunc { } /** - * Get a plot id + * Get a plot type * * @param plot Plot Object * @@ -250,10 +250,10 @@ public class DBFunc { /* * public static int getId(String plotId id2) { Statement stmt = * null; try { stmt = connection.createStatement(); ResultSet r = - * stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x + * stmt.executeQuery("SELECT `type` FROM `plot` WHERE `plot_id_x` = '" + id2.x * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + - * "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE; - * while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; } + * "' ORDER BY `timestamp` ASC"); int type = Integer.MAX_VALUE; + * while(r.next()) { type = r.getInt("type"); } stmt.close(); return type; } * catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE; * } */ diff --git a/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java b/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java index 655f56bc5..76f32387f 100644 --- a/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java +++ b/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java @@ -20,6 +20,24 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.database; +import com.intellectualcrafters.configuration.ConfigurationSection; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.BlockLoc; +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.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotSettings; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.comment.PlotComment; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.StringMan; +import com.intellectualcrafters.plot.util.TaskManager; + import java.sql.Blob; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -44,24 +62,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.BlockLoc; -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.PlotPlayer; -import com.intellectualcrafters.plot.object.PlotSettings; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.comment.PlotComment; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; - /** */ @@ -75,23 +75,17 @@ public class SQLManager implements AbstractDB { public final String CREATE_PLOT; public final String CREATE_CLUSTER; private final String prefix; - // Private - private Connection connection; - private boolean CLOSED = false; // Private Final private final Database database; private final boolean MYSQL; - /** * important tasks */ public volatile Queue globalTasks; - /** * Notify tasks */ public volatile Queue notifyTasks; - /** * plot * plot_denied @@ -102,12 +96,10 @@ public class SQLManager implements AbstractDB { * plot_rating */ public volatile ConcurrentHashMap> plotTasks; - /** * player_meta */ public volatile ConcurrentHashMap> playerTasks; - /** * cluster * cluster_helpers @@ -115,115 +107,10 @@ public class SQLManager implements AbstractDB { * cluster_settings */ public volatile ConcurrentHashMap> clusterTasks; - - public synchronized Queue getGlobalTasks() { - return globalTasks; - } - - public synchronized Queue getNotifyTasks() { - return notifyTasks; - } - - public synchronized void addPlotTask(Plot plot, UniqueStatement task) { - if (plot == null) { - plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE)); - } - Queue tasks = plotTasks.get(plot); - if (tasks == null) { - tasks = new ConcurrentLinkedQueue<>(); - plotTasks.put(plot, tasks); - } - if (task == null) { - task = new UniqueStatement(plot.hashCode() + "") { - - @Override - public PreparedStatement get() throws SQLException { - return null; - } - - @Override - public void set(final PreparedStatement stmt) throws SQLException {} - - @Override - public void addBatch(final PreparedStatement stmt) throws SQLException {} - - @Override - public void execute(final PreparedStatement stmt) throws SQLException {} - - }; - } - tasks.add(task); - } - - public synchronized void addPlayerTask(UUID uuid, UniqueStatement task) { - if (uuid == null) { - return; - } - Queue tasks = playerTasks.get(uuid); - if (tasks == null) { - tasks = new ConcurrentLinkedQueue<>(); - playerTasks.put(uuid, tasks); - } - if (task == null) { - task = new UniqueStatement(uuid.hashCode() + "") { - - @Override - public PreparedStatement get() throws SQLException { - return null; - } - - @Override - public void set(final PreparedStatement stmt) throws SQLException {} - - @Override - public void addBatch(final PreparedStatement stmt) throws SQLException {} - - @Override - public void execute(final PreparedStatement stmt) throws SQLException {} - - }; - } - tasks.add(task); - } + // Private + private Connection connection; + private boolean CLOSED = false; - public synchronized void addClusterTask(final PlotCluster cluster, UniqueStatement task) { - Queue tasks = clusterTasks.get(cluster); - if (tasks == null) { - tasks = new ConcurrentLinkedQueue<>(); - clusterTasks.put(cluster, tasks); - } - if (task == null) { - task = new UniqueStatement(cluster.hashCode() + "") { - - @Override - public PreparedStatement get() throws SQLException { - return null; - } - - @Override - public void set(final PreparedStatement stmt) throws SQLException {} - - @Override - public void addBatch(final PreparedStatement stmt) throws SQLException {} - - @Override - public void execute(final PreparedStatement stmt) throws SQLException {} - - }; - } - tasks.add(task); - } - - public synchronized void addGlobalTask(final Runnable task) { - getGlobalTasks().add(task); - } - - public synchronized void addNotifyTask(final Runnable task) { - if (task != null) { - getNotifyTasks().add(task); - } - } - /** * Constructor * @@ -231,11 +118,11 @@ public class SQLManager implements AbstractDB { * @param p prefix * @throws Exception */ - public SQLManager(final Database database, final String p, final boolean debug) throws Exception { + public SQLManager(final Database database, final String p, final boolean debug) throws SQLException, ClassNotFoundException { // Private final this.database = database; connection = database.openConnection(); - MYSQL = (database instanceof MySQL); + MYSQL = database instanceof MySQL; globalTasks = new ConcurrentLinkedQueue<>(); notifyTasks = new ConcurrentLinkedQueue<>(); plotTasks = new ConcurrentHashMap<>(); @@ -262,7 +149,7 @@ public class SQLManager implements AbstractDB { } if (!sendBatch()) { try { - if (getNotifyTasks().size() > 0) { + if (!getNotifyTasks().isEmpty()) { for (final Runnable task : getNotifyTasks()) { TaskManager.runTask(task); } @@ -281,7 +168,7 @@ public class SQLManager implements AbstractDB { // setTimout(); // Public final SET_OWNER = "UPDATE `" + prefix + "plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND `world` = ?"; - GET_ALL_PLOTS = "SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `" + prefix + "plot`"; + GET_ALL_PLOTS = "SELECT `type`, `plot_id_x`, `plot_id_z`, `world` FROM `" + prefix + "plot`"; CREATE_PLOTS = "INSERT INTO `" + prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) values "; CREATE_SETTINGS = "INSERT INTO `" + prefix + "plot_settings` (`plot_plot_id`) values "; CREATE_TIERS = "INSERT INTO `" + prefix + "plot_%tier%` (`plot_plot_id`, `user_uuid`) values "; @@ -290,10 +177,118 @@ public class SQLManager implements AbstractDB { updateTables(); createTables(); } + + public synchronized Queue getGlobalTasks() { + return globalTasks; + } + + public synchronized Queue getNotifyTasks() { + return notifyTasks; + } + + public synchronized void addPlotTask(Plot plot, UniqueStatement task) { + if (plot == null) { + plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE)); + } + Queue tasks = plotTasks.get(plot); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + plotTasks.put(plot, tasks); + } + if (task == null) { + task = new UniqueStatement(plot.hashCode() + "") { + + @Override + public PreparedStatement get() throws SQLException { + return null; + } + + @Override + public void set(final PreparedStatement stmt) throws SQLException {} + + @Override + public void addBatch(final PreparedStatement stmt) throws SQLException {} + + @Override + public void execute(final PreparedStatement stmt) throws SQLException {} + + }; + } + tasks.add(task); + } + + public synchronized void addPlayerTask(UUID uuid, UniqueStatement task) { + if (uuid == null) { + return; + } + Queue tasks = playerTasks.get(uuid); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + playerTasks.put(uuid, tasks); + } + if (task == null) { + task = new UniqueStatement(uuid.hashCode() + "") { + + @Override + public PreparedStatement get() throws SQLException { + return null; + } + + @Override + public void set(final PreparedStatement stmt) throws SQLException {} + + @Override + public void addBatch(final PreparedStatement stmt) throws SQLException {} + + @Override + public void execute(final PreparedStatement stmt) throws SQLException {} + + }; + } + tasks.add(task); + } + + public synchronized void addClusterTask(final PlotCluster cluster, UniqueStatement task) { + Queue tasks = clusterTasks.get(cluster); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + clusterTasks.put(cluster, tasks); + } + if (task == null) { + task = new UniqueStatement(cluster.hashCode() + "") { + + @Override + public PreparedStatement get() throws SQLException { + return null; + } + + @Override + public void set(final PreparedStatement stmt) throws SQLException {} + + @Override + public void addBatch(final PreparedStatement stmt) throws SQLException {} + + @Override + public void execute(final PreparedStatement stmt) throws SQLException {} + + }; + } + tasks.add(task); + } + + public synchronized void addGlobalTask(final Runnable task) { + getGlobalTasks().add(task); + } + + public synchronized void addNotifyTask(final Runnable task) { + if (task != null) { + getNotifyTasks().add(task); + } + } public boolean sendBatch() { try { - if (getGlobalTasks().size() > 0) { + if (!getGlobalTasks().isEmpty()) { if (connection.getAutoCommit()) { connection.setAutoCommit(false); } @@ -305,7 +300,7 @@ public class SQLManager implements AbstractDB { return true; } int count = -1; - if (plotTasks.size() > 0) { + if (!plotTasks.isEmpty()) { count = 0; if (connection.getAutoCommit()) { connection.setAutoCommit(false); @@ -316,14 +311,14 @@ public class SQLManager implements AbstractDB { UniqueStatement lastTask = null; for (final Entry> entry : plotTasks.entrySet()) { final Plot plot = entry.getKey(); - if (plotTasks.get(plot).size() == 0) { + if (plotTasks.get(plot).isEmpty()) { plotTasks.remove(plot); continue; } task = plotTasks.get(plot).remove(); count++; if (task != null) { - if ((task._method == null) || !task._method.equals(method)) { + if (task._method == null || !task._method.equals(method)) { if (stmt != null) { lastTask.execute(stmt); stmt.close(); @@ -336,12 +331,12 @@ public class SQLManager implements AbstractDB { } lastTask = task; } - if ((stmt != null) && (task != null)) { + if (stmt != null && task != null) { task.execute(stmt); stmt.close(); } } - if (playerTasks.size() > 0) { + if (!playerTasks.isEmpty()) { count = 0; if (connection.getAutoCommit()) { connection.setAutoCommit(false); @@ -352,14 +347,14 @@ public class SQLManager implements AbstractDB { UniqueStatement lastTask = null; for (final Entry> entry : playerTasks.entrySet()) { final UUID uuid = entry.getKey(); - if (playerTasks.get(uuid).size() == 0) { + if (playerTasks.get(uuid).isEmpty()) { playerTasks.remove(uuid); continue; } task = playerTasks.get(uuid).remove(); count++; if (task != null) { - if ((task._method == null) || !task._method.equals(method)) { + if (task._method == null || !task._method.equals(method)) { if (stmt != null) { lastTask.execute(stmt); stmt.close(); @@ -372,12 +367,12 @@ public class SQLManager implements AbstractDB { } lastTask = task; } - if ((stmt != null) && (task != null)) { + if (stmt != null && task != null) { task.execute(stmt); stmt.close(); } } - if (clusterTasks.size() > 0) { + if (!clusterTasks.isEmpty()) { count = 0; if (connection.getAutoCommit()) { connection.setAutoCommit(false); @@ -388,14 +383,14 @@ public class SQLManager implements AbstractDB { UniqueStatement lastTask = null; for (final Entry> entry : clusterTasks.entrySet()) { final PlotCluster cluster = entry.getKey(); - if (clusterTasks.get(cluster).size() == 0) { + if (clusterTasks.get(cluster).isEmpty()) { clusterTasks.remove(cluster); continue; } task = clusterTasks.get(cluster).remove(); count++; if (task != null) { - if ((task._method == null) || !task._method.equals(method)) { + if (task._method == null || !task._method.equals(method)) { if (stmt != null) { lastTask.execute(stmt); stmt.close(); @@ -408,7 +403,7 @@ public class SQLManager implements AbstractDB { } lastTask = task; } - if ((stmt != null) && (task != null)) { + if (stmt != null && task != null) { task.execute(stmt); stmt.close(); } @@ -421,38 +416,18 @@ public class SQLManager implements AbstractDB { connection.setAutoCommit(true); } } - if (clusterTasks.size() > 0) { + if (!clusterTasks.isEmpty()) { clusterTasks.clear(); } - if (plotTasks.size() > 0) { + if (!plotTasks.isEmpty()) { plotTasks.clear(); } - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } return false; } - public abstract class UniqueStatement { - public String _method; - - public UniqueStatement(final String method) { - _method = method; - } - - public void addBatch(final PreparedStatement stmt) throws SQLException { - stmt.addBatch(); - } - - public void execute(final PreparedStatement stmt) throws SQLException { - stmt.executeBatch(); - } - - public abstract PreparedStatement get() throws SQLException; - - public abstract void set(final PreparedStatement stmt) throws SQLException; - } - public Connection getConnection() { return connection; } @@ -473,7 +448,7 @@ public class SQLManager implements AbstractDB { statement.setInt(3, plot.getId().y); statement.setString(4, plot.getArea().toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement(SET_OWNER); @@ -501,12 +476,12 @@ public class SQLManager implements AbstractDB { final ArrayList helpers = new ArrayList<>(); final ArrayList trusted = new ArrayList<>(); final ArrayList denied = new ArrayList<>(); - + // Populating structures final PreparedStatement stmt = connection.prepareStatement(GET_ALL_PLOTS); try (ResultSet result = stmt.executeQuery()) { while (result.next()) { - final int id = result.getInt("id"); + final int id = result.getInt("type"); final int x = result.getInt("plot_id_x"); final int y = result.getInt("plot_id_z"); final PlotId plotId = new PlotId(x, y); @@ -594,29 +569,29 @@ public class SQLManager implements AbstractDB { public String getCreateMySQL(final int size) { return getCreateMySQL(size, CREATE_TIERS.replaceAll("%tier%", tier), 2); } - + @Override public String getCreateSQLite(final int size) { return getCreateSQLite(size, "INSERT INTO `" + prefix + "plot_" + tier + "` SELECT ? AS `plot_plot_id`, ? AS `user_uuid`", 2); } - + @Override public String getCreateSQL() { return "INSERT INTO `" + prefix + "plot_" + tier + "` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"; } - + @Override public void setMySQL(final PreparedStatement stmt, final int i, final UUIDPair pair) throws SQLException { stmt.setInt((i * 2) + 1, pair.id); stmt.setString((i * 2) + 2, pair.uuid.toString()); } - + @Override public void setSQLite(final PreparedStatement stmt, final int i, final UUIDPair pair) throws SQLException { stmt.setInt((i * 2) + 1, pair.id); stmt.setString((i * 2) + 2, pair.uuid.toString()); } - + @Override public void setSQL(final PreparedStatement stmt, final UUIDPair pair) throws SQLException { stmt.setInt(1, pair.id); @@ -637,30 +612,31 @@ public class SQLManager implements AbstractDB { public String getCreateMySQL(final int size) { return getCreateMySQL(size, CREATE_PLOTS, 5); } - + @Override public String getCreateSQLite(final int size) { - return getCreateSQLite(size, "INSERT INTO `" + prefix + "plot` SELECT ? AS `id`, ? AS `plot_id_x`, ? AS `plot_id_z`, ? AS `owner`, ? AS `world`, ? AS `timestamp` ", 6); + return getCreateSQLite(size, "INSERT INTO `" + prefix + + "plot` SELECT ? AS `type`, ? AS `plot_id_x`, ? AS `plot_id_z`, ? AS `owner`, ? AS `world`, ? AS `timestamp` ", 6); } - + @Override public String getCreateSQL() { return CREATE_PLOT; } - + @Override public void setMySQL(final PreparedStatement stmt, final int i, final Plot plot) throws SQLException { stmt.setInt((i * 5) + 1, plot.getId().x); stmt.setInt((i * 5) + 2, plot.getId().y); try { stmt.setString((i * 5) + 3, plot.owner.toString()); - } catch (final Exception e) { + } catch (SQLException e) { stmt.setString((i * 5) + 3, everyone.toString()); } stmt.setString((i * 5) + 4, plot.getArea().toString()); stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp())); } - + @Override public void setSQLite(final PreparedStatement stmt, final int i, final Plot plot) throws SQLException { stmt.setNull((i * 6) + 1, 4); @@ -668,13 +644,13 @@ public class SQLManager implements AbstractDB { stmt.setInt((i * 6) + 3, plot.getId().y); try { stmt.setString((i * 6) + 4, plot.owner.toString()); - } catch (final Exception e1) { + } catch (SQLException e1) { stmt.setString((i * 6) + 4, everyone.toString()); } stmt.setString((i * 6) + 5, plot.getArea().toString()); stmt.setTimestamp((i * 6) + 6, new Timestamp(plot.getTimestamp())); } - + @Override public void setSQL(final PreparedStatement stmt, final Plot plot) throws SQLException { stmt.setInt(1, plot.getId().x); @@ -682,7 +658,7 @@ public class SQLManager implements AbstractDB { stmt.setString(3, plot.owner.toString()); stmt.setString(4, plot.getArea().toString()); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); - + } }; setBulk(myList, mod, whenDone); @@ -706,13 +682,13 @@ public class SQLManager implements AbstractDB { try { int count = 0; PreparedStatement preparedStmt = null; - String statement; int last = -1; for (int j = 0; j <= amount; j++) { final List subList = objList.subList(j * packet, Math.min(size, (j + 1) * packet)); - if (subList.size() == 0) { + if (subList.isEmpty()) { break; } + String statement; if (last == -1) { last = subList.size(); statement = mod.getCreateMySQL(subList.size()); @@ -740,7 +716,7 @@ public class SQLManager implements AbstractDB { whenDone.run(); } return; - } catch (final Exception e) { + } catch (SQLException e) { if (MYSQL) { e.printStackTrace(); PS.debug("&cERROR 1: " + " | " + objList.get(0).getClass().getCanonicalName()); @@ -749,13 +725,13 @@ public class SQLManager implements AbstractDB { try { int count = 0; PreparedStatement preparedStmt = null; - String statement; int last = -1; for (int j = 0; j <= amount; j++) { final List subList = objList.subList(j * packet, Math.min(size, (j + 1) * packet)); - if (subList.size() == 0) { + if (subList.isEmpty()) { break; } + String statement; if (last == -1) { last = subList.size(); statement = mod.getCreateSQLite(subList.size()); @@ -779,26 +755,25 @@ public class SQLManager implements AbstractDB { preparedStmt.executeBatch(); preparedStmt.clearParameters(); preparedStmt.close(); - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); PS.debug("&cERROR 2: " + " | " + objList.get(0).getClass().getCanonicalName()); PS.debug("&6[WARN] " + "Could not bulk save!"); try { - PreparedStatement preparedStmt; final String nonBulk = mod.getCreateSQL(); - preparedStmt = connection.prepareStatement(nonBulk); + PreparedStatement preparedStmt = connection.prepareStatement(nonBulk); for (final T obj : objList) { try { mod.setSQL(preparedStmt, obj); preparedStmt.addBatch(); - } catch (final Exception e3) { + } catch (SQLException e3) { PS.debug("&c[ERROR] " + "Failed to save " + obj + "!"); } } PS.debug("&aBatch 3"); preparedStmt.executeBatch(); preparedStmt.close(); - } catch (final Exception e3) { + } catch (SQLException e3) { e3.printStackTrace(); PS.debug("&c[ERROR] " + "Failed to save all!"); } @@ -815,7 +790,7 @@ public class SQLManager implements AbstractDB { return getCreateMySQL(size, "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`,`biome`,`rain`,`custom_time`,`time`,`deny_entry`,`alias`,`flags`,`merged`,`position`) VALUES ", 10); } - + @Override public String getCreateSQLite(final int size) { return getCreateSQLite( @@ -825,15 +800,15 @@ public class SQLManager implements AbstractDB { + "plot_settings` SELECT ? AS `plot_plot_id`, ? AS `biome`, ? AS `rain`, ? AS `custom_time`, ? AS `time`, ? AS `deny_entry`, ? AS `alias`, ? AS `flags`, ? AS `merged`, ? AS `position`", 10); } - + @Override public String getCreateSQL() { return "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(?)"; } - + @Override public void setMySQL(final PreparedStatement stmt, final int i, final SettingsPair pair) throws SQLException { - stmt.setInt((i * 10) + 1, pair.id); // id + stmt.setInt((i * 10) + 1, pair.id); // type stmt.setNull((i * 10) + 2, 4); // biome stmt.setNull((i * 10) + 3, 4); // rain stmt.setNull((i * 10) + 4, 4); // custom_time @@ -870,10 +845,10 @@ public class SQLManager implements AbstractDB { } stmt.setString((i * 10) + 10, position); } - + @Override public void setSQLite(final PreparedStatement stmt, final int i, final SettingsPair pair) throws SQLException { - stmt.setInt((i * 10) + 1, pair.id); // id + stmt.setInt((i * 10) + 1, pair.id); // type stmt.setNull((i * 10) + 2, 4); // biome stmt.setNull((i * 10) + 3, 4); // rain stmt.setNull((i * 10) + 4, 4); // custom_time @@ -913,7 +888,7 @@ public class SQLManager implements AbstractDB { } stmt.setString((i * 10) + 10, position); } - + @Override public void setSQL(final PreparedStatement stmt, final SettingsPair pair) throws SQLException { stmt.setInt(1, pair.id); @@ -933,7 +908,7 @@ public class SQLManager implements AbstractDB { public String getCreateMySQL(final int size) { return getCreateMySQL(size, CREATE_SETTINGS, 1); } - + @Override public String getCreateSQLite(final int size) { return getCreateSQLite( @@ -943,17 +918,17 @@ public class SQLManager implements AbstractDB { + "plot_settings` SELECT ? AS `plot_plot_id`, ? AS `biome`, ? AS `rain`, ? AS `custom_time`, ? AS `time`, ? AS `deny_entry`, ? AS `alias`, ? AS `flags`, ? AS `merged`, ? AS `position` ", 10); } - + @Override public String getCreateSQL() { return "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(?)"; } - + @Override public void setMySQL(final PreparedStatement stmt, final int i, final Integer id) throws SQLException { stmt.setInt((i) + 1, id); } - + @Override public void setSQLite(final PreparedStatement stmt, final int i, final Integer id) throws SQLException { stmt.setInt((i * 10) + 1, id); @@ -967,7 +942,7 @@ public class SQLManager implements AbstractDB { stmt.setNull((i * 10) + 9, 4); stmt.setString((i * 10) + 10, "DEFAULT"); } - + @Override public void setSQL(final PreparedStatement stmt, final Integer id) throws SQLException { stmt.setInt(1, id); @@ -997,7 +972,7 @@ public class SQLManager implements AbstractDB { stmt.setString(4, plot.getArea().toString()); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement(CREATE_PLOT); @@ -1030,17 +1005,17 @@ public class SQLManager implements AbstractDB { stmt.setString(4, plot.getArea().toString()); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement(CREATE_PLOT, Statement.RETURN_GENERATED_KEYS); } - + @Override public void execute(final PreparedStatement stmt) throws SQLException { - + } - + @Override public void addBatch(final PreparedStatement stmt) throws SQLException { stmt.executeUpdate(); @@ -1055,7 +1030,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); @@ -1090,8 +1065,7 @@ public class SQLManager implements AbstractDB { if (create == 0) { return; } - boolean add_constraint; - add_constraint = create == tables.length; + boolean add_constraint = create == tables.length; PS.debug("Creating tables"); final Statement stmt = connection.createStatement(); if (MYSQL) { @@ -1296,7 +1270,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_settings` WHERE `plot_plot_id` = ?"); @@ -1306,7 +1280,7 @@ public class SQLManager implements AbstractDB { @Override public void deleteHelpers(final Plot plot) { - if (plot.getTrusted().size() == 0) { + if (plot.getTrusted().isEmpty()) { return; } addPlotTask(plot, new UniqueStatement("delete_plot_helpers") { @@ -1314,7 +1288,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = ?"); @@ -1324,7 +1298,7 @@ public class SQLManager implements AbstractDB { @Override public void deleteTrusted(final Plot plot) { - if (plot.getMembers().size() == 0) { + if (plot.getMembers().isEmpty()) { return; } addPlotTask(plot, new UniqueStatement("delete_plot_trusted") { @@ -1332,7 +1306,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = ?"); @@ -1342,7 +1316,7 @@ public class SQLManager implements AbstractDB { @Override public void deleteDenied(final Plot plot) { - if (plot.getDenied().size() == 0) { + if (plot.getDenied().isEmpty()) { return; } addPlotTask(plot, new UniqueStatement("delete_plot_denied") { @@ -1350,7 +1324,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = ?"); @@ -1366,7 +1340,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, plot.getArea().toString()); stmt.setInt(2, plot.hashCode()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ?"); @@ -1376,7 +1350,7 @@ public class SQLManager implements AbstractDB { @Override public void deleteRatings(final Plot plot) { - if (Settings.CACHE_RATINGS && plot.getSettings().getRatings().size() == 0) { + if (Settings.CACHE_RATINGS && plot.getSettings().getRatings().isEmpty()) { return; } addPlotTask(plot, new UniqueStatement("delete_plot_ratings") { @@ -1384,7 +1358,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_rating` WHERE `plot_plot_id` = ?"); @@ -1410,14 +1384,14 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot` WHERE `id` = ?"); } }); } - + /** * Create plot settings * @@ -1431,7 +1405,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); @@ -1444,15 +1418,14 @@ public class SQLManager implements AbstractDB { if (cluster.temp > 0) { return cluster.temp; } - PreparedStatement stmt = null; try { commit(); if (cluster.temp > 0) { return cluster.temp; } - stmt = connection.prepareStatement("SELECT `id` FROM `" - + prefix - + "cluster` WHERE `pos1_x` = ? AND `pos1_z` = ? AND `pos2_x` = ? AND `pos2_z` = ? AND `world` = ? ORDER BY `timestamp` ASC"); + PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" + + prefix + + "cluster` WHERE `pos1_x` = ? AND `pos1_z` = ? AND `pos2_x` = ? AND `pos2_z` = ? AND `world` = ? ORDER BY `timestamp` ASC"); stmt.setInt(1, cluster.getP1().x); stmt.setInt(2, cluster.getP1().y); stmt.setInt(3, cluster.getP2().x); @@ -1461,7 +1434,7 @@ public class SQLManager implements AbstractDB { final ResultSet r = stmt.executeQuery(); int c_id = Integer.MAX_VALUE; while (r.next()) { - c_id = r.getInt("id"); + c_id = r.getInt("type"); } stmt.close(); r.close(); @@ -1484,20 +1457,20 @@ public class SQLManager implements AbstractDB { if (plot.temp > 0) { return plot.temp; } - PreparedStatement stmt = null; try { commit(); if (plot.temp > 0) { return plot.temp; } - stmt = connection.prepareStatement("SELECT `id` FROM `" + prefix + "plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC"); + PreparedStatement stmt = connection.prepareStatement( + "SELECT `id` FROM `" + prefix + "plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC"); stmt.setInt(1, plot.getId().x); stmt.setInt(2, plot.getId().y); stmt.setString(3, plot.getArea().toString()); final ResultSet r = stmt.executeQuery(); int id = Integer.MAX_VALUE; while (r.next()) { - id = r.getInt("id"); + id = r.getInt("type"); } r.close(); stmt.close(); @@ -1514,7 +1487,7 @@ public class SQLManager implements AbstractDB { } return Integer.MAX_VALUE; } - + public void updateTables() { if (PS.get().getVersion().equals(PS.get().getLastVersion()) || (PS.get().getLastVersion() == null)) { return; @@ -1532,23 +1505,23 @@ public class SQLManager implements AbstractDB { statement.addBatch("DROP TABLE `" + prefix + "plot_comments`"); if (Settings.DB.USE_MYSQL) { statement.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_comments` (" - + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`inbox` VARCHAR(40) NOT NULL," - + "`timestamp` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + + prefix + + "plot_comments` (" + + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," + + "`comment` VARCHAR(40) NOT NULL," + + "`inbox` VARCHAR(40) NOT NULL," + + "`timestamp` INT(11) NOT NULL," + + "`sender` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); } else { statement.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_comments` (" - + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`inbox` VARCHAR(40) NOT NULL, `timestamp` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" - + ")"); + + prefix + + "plot_comments` (" + + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," + + "`comment` VARCHAR(40) NOT NULL," + + "`inbox` VARCHAR(40) NOT NULL, `timestamp` INT(11) NOT NULL," + + "`sender` VARCHAR(40) NOT NULL" + + ")"); } statement.executeBatch(); statement.close(); @@ -1566,20 +1539,23 @@ public class SQLManager implements AbstractDB { rs = data.getColumns(null, null, prefix + "plot_denied", "plot_plot_id"); if (rs.next()) { try (Statement statement = connection.createStatement()) { - statement.executeUpdate("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` NOT IN (SELECT `id` FROM `" + prefix + "plot`)"); + statement.executeUpdate( + "DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` NOT IN (SELECT `id` FROM `" + prefix + "plot`)"); statement.close(); - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } - + rs.close(); try (Statement statement = connection.createStatement()) { - for (final String table : new String[] { "plot_denied", "plot_helpers", "plot_trusted" }) { - final ResultSet result = statement.executeQuery("SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + prefix + table + " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1"); + for (final String table : new String[]{"plot_denied", "plot_helpers", "plot_trusted"}) { + final ResultSet result = statement.executeQuery("SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + prefix + table + + " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1"); if (result.next()) { PS.debug("BACKING UP: " + prefix + table); result.close(); - statement.executeUpdate("CREATE TABLE " + prefix + table + "_tmp AS SELECT * FROM " + prefix + table + " GROUP BY plot_plot_id, user_uuid"); + statement.executeUpdate("CREATE TABLE " + prefix + table + "_tmp AS SELECT * FROM " + prefix + table + + " GROUP BY plot_plot_id, user_uuid"); statement.executeUpdate("DROP TABLE " + prefix + table); statement.executeUpdate("CREATE TABLE " + prefix + table + " AS SELECT * FROM " + prefix + table + "_tmp"); statement.executeUpdate("DROP TABLE " + prefix + table + "_tmp"); @@ -1587,44 +1563,44 @@ public class SQLManager implements AbstractDB { } } statement.close(); - } catch (final Exception e2) { + } catch (SQLException e2) { e2.printStackTrace(); } } - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } - + } public void deleteRows(final ArrayList rowIds, final String table, final String column) { setBulk(rowIds, new StmtMod() { - + @Override public String getCreateMySQL(int size) { return getCreateMySQL(1, "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` IN ", size); } - + @Override public String getCreateSQLite(int size) { return getCreateMySQL(1, "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` IN ", size); } - + @Override public String getCreateSQL() { return "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` = ?"; } - + @Override public void setMySQL(PreparedStatement stmt, int i, Integer obj) throws SQLException { stmt.setInt((i) + 1, obj); } - + @Override public void setSQLite(PreparedStatement stmt, int i, Integer obj) throws SQLException { stmt.setInt((i) + 1, obj); } - + @Override public void setSQL(PreparedStatement stmt, Integer obj) throws SQLException { stmt.setInt(1, obj); @@ -1639,7 +1615,6 @@ public class SQLManager implements AbstractDB { public HashMap> getPlots() { final HashMap> newplots = new HashMap<>(); final HashMap plots = new HashMap<>(); - Statement stmt; try { HashSet areas = new HashSet<>();; if (PS.get().config.contains("worlds")) { @@ -1661,22 +1636,19 @@ public class SQLManager implements AbstractDB { } final HashMap uuids = new HashMap<>(); final HashMap noExist = new HashMap<>(); - - PlotId plot_id; - int id; - Plot p; - String o; - UUID user; - + /* * Getting plots */ - stmt = connection.createStatement(); + Statement stmt = connection.createStatement(); + int id; + String o; + UUID user; try (ResultSet r = stmt.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp` FROM `" + prefix + "plot`")) { ArrayList toDelete = new ArrayList<>(); while (r.next()) { - plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); - id = r.getInt("id"); + PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); + id = r.getInt("type"); final String areaid = r.getString("world"); if (!areas.contains(areaid)) { if (Settings.AUTO_PURGE) { @@ -1708,7 +1680,8 @@ public class SQLManager implements AbstractDB { } else { time = timestamp.getTime(); } - p = new Plot(plot_id, user, new HashSet(), new HashSet(), new HashSet(), "", null, null, null, new boolean[] { false, false, false, false }, time, id); + Plot p = new Plot(plot_id, user, new HashSet(), new HashSet(), new HashSet(), "", null, null, null, + new boolean[]{false, false, false, false}, time, id); HashMap map = newplots.get(areaid); if (map != null) { Plot last = map.put(p.getId(), p); @@ -1722,13 +1695,13 @@ public class SQLManager implements AbstractDB { continue; } } else { - map = new HashMap(); + map = new HashMap<>(); newplots.put(areaid, map); map.put(p.getId(), p); } plots.put(id, p); } - deleteRows(toDelete, "plot", "id"); + deleteRows(toDelete, "plot", "type"); } if (Settings.CACHE_RATINGS) { try (ResultSet r = stmt.executeQuery("SELECT `plot_plot_id`, `player`, `rating` FROM `" + prefix + "plot_rating`")) { @@ -1756,7 +1729,7 @@ public class SQLManager implements AbstractDB { deleteRows(toDelete, "plot_rating", "plot_plot_id"); } } - + /* * Getting helpers */ @@ -1781,7 +1754,7 @@ public class SQLManager implements AbstractDB { } deleteRows(toDelete, "plot_helpers", "plot_plot_id"); } - + /* * Getting trusted */ @@ -1806,7 +1779,7 @@ public class SQLManager implements AbstractDB { } deleteRows(toDelete, "plot_trusted", "plot_plot_id"); } - + /* * Getting denied */ @@ -1831,7 +1804,7 @@ public class SQLManager implements AbstractDB { } deleteRows(toDelete, "plot_denied", "plot_plot_id"); } - + try (ResultSet r = stmt.executeQuery("SELECT * FROM `" + prefix + "plot_settings`")) { ArrayList toDelete = new ArrayList<>(); while (r.next()) { @@ -1858,7 +1831,7 @@ public class SQLManager implements AbstractDB { final Integer m = r.getInt("merged"); final boolean[] merged = new boolean[4]; for (int i = 0; i < 4; i++) { - merged[3 - i] = ((m) & (1 << i)) != 0; + merged[3 - i] = (m & (1 << i)) != 0; } plot.getSettings().setMerged(merged); String[] flags_string; @@ -1866,7 +1839,7 @@ public class SQLManager implements AbstractDB { if (myflags == null) { flags_string = new String[] {}; } else { - if (myflags.length() > 0) { + if (!myflags.isEmpty()) { flags_string = myflags.split(","); } else { flags_string = new String[] {}; @@ -1910,7 +1883,7 @@ public class SQLManager implements AbstractDB { stmt.close(); deleteRows(toDelete, "plot_settings", "plot_plot_id"); } - if (plots.entrySet().size() > 0) { + if (!plots.entrySet().isEmpty()) { createEmptySettings(new ArrayList<>(plots.keySet()), null); for (Entry entry : plots.entrySet()) { entry.getValue().getSettings(); @@ -1931,7 +1904,7 @@ public class SQLManager implements AbstractDB { } return newplots; } - + @Override public void setMerged(final Plot plot, final boolean[] merged) { plot.getSettings().setMerged(merged); @@ -1942,7 +1915,7 @@ public class SQLManager implements AbstractDB { stmt.setInt(1, hash); stmt.setInt(2, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); @@ -1963,7 +1936,7 @@ public class SQLManager implements AbstractDB { stmt.setInt(2, pos2.y); stmt.setInt(3, id1); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?"); @@ -1976,7 +1949,7 @@ public class SQLManager implements AbstractDB { stmt.setInt(2, pos1.y); stmt.setInt(3, id2); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?"); @@ -1994,7 +1967,7 @@ public class SQLManager implements AbstractDB { stmt.setString(3, newPlot.getArea().toString()); stmt.setInt(4, getId(original)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ?, `world` = ? WHERE `id` = ?"); @@ -2020,7 +1993,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, flag_string.toString()); stmt.setInt(2, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); @@ -2036,7 +2009,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, alias); stmt.setInt(2, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); @@ -2052,13 +2025,13 @@ public class SQLManager implements AbstractDB { addGlobalTask(new Runnable() { @Override public void run() { - if (uniqueIds.size() > 0) { + if (!uniqueIds.isEmpty()) { try { String stmt_prefix = ""; final StringBuilder idstr2 = new StringBuilder(""); for (final Integer id : uniqueIds) { idstr2.append(stmt_prefix).append(id); - stmt_prefix = " OR `id` = "; + stmt_prefix = " OR `type` = "; } stmt_prefix = ""; final StringBuilder idstr = new StringBuilder(""); @@ -2097,17 +2070,16 @@ public class SQLManager implements AbstractDB { addGlobalTask(new Runnable() { @Override public void run() { - PreparedStatement stmt; try { - stmt = connection.prepareStatement("SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + prefix + "plot` WHERE `world` = ?"); + PreparedStatement stmt = + connection.prepareStatement("SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + prefix + "plot` WHERE `world` = ?"); stmt.setString(1, area.toString()); final ResultSet r = stmt.executeQuery(); - PlotId plot_id; final Set ids = new HashSet<>(); while (r.next()) { - plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); + PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); if (plots.contains(plot_id)) { - ids.add(r.getInt("id")); + ids.add(r.getInt("type")); } } purgeIds(ids); @@ -2135,7 +2107,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, position); stmt.setInt(2, getId(plot)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); @@ -2160,7 +2132,7 @@ public class SQLManager implements AbstractDB { statement.setString(3, comment.senderName); } } - + @Override public PreparedStatement get() throws SQLException { if (plot != null) { @@ -2184,7 +2156,7 @@ public class SQLManager implements AbstractDB { statement.setString(1, inbox); } } - + @Override public PreparedStatement get() throws SQLException { if (plot != null) { @@ -2208,7 +2180,7 @@ public class SQLManager implements AbstractDB { statement.setString(1, inbox); } } - + @Override public PreparedStatement get() throws SQLException { if (plot != null) { @@ -2216,15 +2188,14 @@ public class SQLManager implements AbstractDB { } return connection.prepareStatement("SELECT * FROM `" + prefix + "plot_comments` WHERE `inbox` = ?"); } - + @Override public void execute(final PreparedStatement stmt) throws SQLException {} - + @Override public void addBatch(final PreparedStatement statement) throws SQLException { final ArrayList comments = new ArrayList<>(); final ResultSet set = statement.executeQuery(); - PlotComment comment; while (set.next()) { final String sender = set.getString("sender"); final String world = set.getString("world"); @@ -2237,7 +2208,7 @@ public class SQLManager implements AbstractDB { } final String msg = set.getString("comment"); final long timestamp = set.getInt("timestamp") * 1000; - comment = new PlotComment(world, id, msg, sender, inbox, timestamp); + PlotComment comment = new PlotComment(world, id, msg, sender, inbox, timestamp); comments.add(comment); whenDone.value = comments; } @@ -2258,7 +2229,7 @@ public class SQLManager implements AbstractDB { statement.setInt(5, (int) (comment.timestamp / 1000)); statement.setString(6, comment.senderName); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_comments` (`world`, `hashcode`, `comment`, `inbox`, `timestamp`, `sender`) VALUES(?,?,?,?,?,?)"); @@ -2274,7 +2245,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getId(plot)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); @@ -2290,7 +2261,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getId(plot)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); @@ -2306,7 +2277,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getId(plot)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); @@ -2322,7 +2293,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getId(plot)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); @@ -2338,7 +2309,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getId(plot)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); @@ -2354,7 +2325,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getId(plot)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); @@ -2392,7 +2363,7 @@ public class SQLManager implements AbstractDB { statement.setInt(2, value); statement.setString(3, rater.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "plot_rating` (`plot_plot_id`, `rating`, `player`) VALUES(?,?,?)"); @@ -2408,7 +2379,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_settings` WHERE `cluster_id` = ?"); @@ -2419,7 +2390,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_helpers` WHERE `cluster_id` = ?"); @@ -2430,7 +2401,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_invited` WHERE `cluster_id` = ?"); @@ -2441,7 +2412,7 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "cluster` WHERE `id` = ?"); @@ -2465,7 +2436,7 @@ public class SQLManager implements AbstractDB { stmt.setBlob(3, blob); } } - + @Override public PreparedStatement get() throws SQLException { if (delete) { @@ -2500,34 +2471,34 @@ public class SQLManager implements AbstractDB { public void set(final PreparedStatement stmt) throws SQLException { stmt.setString(1, player.getUUID().toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("SELECT * FROM `" + prefix + "player_meta` WHERE `uuid` = ?"); } - + @Override public void execute(PreparedStatement stmt) throws SQLException {} - + @Override public void addBatch(PreparedStatement stmt) throws SQLException { ResultSet resultSet = stmt.executeQuery(); - + final Map metaMap = new HashMap<>(); - + while (resultSet.next()) { String key = resultSet.getString("key"); Blob rawValue = resultSet.getBlob("value"); byte[] bytes = rawValue.getBytes(1, (int) rawValue.length()); metaMap.put(key, bytes); } - + resultSet.close(); stmt.close(); - + result.run(metaMap); } - + }); } @@ -2535,7 +2506,6 @@ public class SQLManager implements AbstractDB { public HashMap> getClusters() { final LinkedHashMap> newClusters = new LinkedHashMap<>(); final HashMap clusters = new HashMap<>(); - Statement stmt = null; try { HashSet areas = new HashSet<>();; if (PS.get().config.contains("worlds")) { @@ -2560,20 +2530,17 @@ public class SQLManager implements AbstractDB { /* * Getting clusters */ - stmt = connection.createStatement(); + Statement stmt = connection.createStatement(); ResultSet r = stmt.executeQuery("SELECT * FROM `" + prefix + "cluster`"); - PlotId pos1; - PlotId pos2; PlotCluster cluster; String owner; - String areaid; UUID user; int id; while (r.next()) { - pos1 = new PlotId(r.getInt("pos1_x"), r.getInt("pos1_z")); - pos2 = new PlotId(r.getInt("pos2_x"), r.getInt("pos2_z")); - id = r.getInt("id"); - areaid = r.getString("world"); + PlotId pos1 = new PlotId(r.getInt("pos1_x"), r.getInt("pos1_z")); + PlotId pos2 = new PlotId(r.getInt("pos2_x"), r.getInt("pos2_z")); + id = r.getInt("type"); + String areaid = r.getString("world"); if (!areas.contains(areaid)) { if (noExist.containsKey(areaid)) { noExist.put(areaid, noExist.get(areaid) + 1); @@ -2667,7 +2634,7 @@ public class SQLManager implements AbstractDB { if (myflags == null) { flags_string = new String[] {}; } else { - if (myflags.length() > 0) { + if (!myflags.isEmpty()) { flags_string = myflags.split(","); } else { flags_string = new String[] {}; @@ -2717,7 +2684,7 @@ public class SQLManager implements AbstractDB { } return newClusters; } - + @Override public void setFlags(final PlotCluster cluster, final Collection flags) { final StringBuilder flag_string = new StringBuilder(); @@ -2735,7 +2702,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, flag_string.toString()); stmt.setInt(2, getClusterId(cluster)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `flags` = ? WHERE `cluster_id` = ?"); @@ -2751,7 +2718,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, name); stmt.setInt(2, getClusterId(cluster)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `alias` = ? WHERE `cluster_id` = ?"); @@ -2768,7 +2735,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getClusterId(cluster)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_helpers` WHERE `cluster_id` = ? AND `user_uuid` = ?"); @@ -2784,7 +2751,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getClusterId(cluster)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_helpers` (`cluster_id`, `user_uuid`) VALUES(?,?)"); @@ -2804,17 +2771,17 @@ public class SQLManager implements AbstractDB { stmt.setString(5, cluster.owner.toString()); stmt.setString(6, cluster.area.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement(CREATE_CLUSTER, Statement.RETURN_GENERATED_KEYS); } - + @Override public void execute(final PreparedStatement stmt) throws SQLException { - + } - + @Override public void addBatch(final PreparedStatement stmt) throws SQLException { stmt.executeUpdate(); @@ -2830,7 +2797,7 @@ public class SQLManager implements AbstractDB { stmt.setInt(1, getClusterId(cluster)); stmt.setString(2, cluster.settings.getAlias()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_settings`(`cluster_id`, `alias`) VALUES(?, ?" + ")"); @@ -2844,7 +2811,7 @@ public class SQLManager implements AbstractDB { final PlotId pos2 = new PlotId(current.getP2().x, current.getP2().y); current.setP1(min); current.setP2(max); - + addClusterTask(current, new UniqueStatement("resizeCluster") { @Override public void set(final PreparedStatement stmt) throws SQLException { @@ -2854,7 +2821,7 @@ public class SQLManager implements AbstractDB { stmt.setInt(4, pos2.y); stmt.setInt(5, getClusterId(current)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "cluster` SET `pos1_x` = ?, `pos1_z` = ?, `pos2_x` = ?, `pos2_z` = ? WHERE `id` = ?"); @@ -2870,7 +2837,7 @@ public class SQLManager implements AbstractDB { stmt.setString(1, position); stmt.setInt(2, getClusterId(cluster)); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `position` = ? WHERE `cluster_id` = ?"); @@ -2886,7 +2853,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getClusterId(cluster)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_invited` WHERE `cluster_id` = ? AND `user_uuid` = ?"); @@ -2902,7 +2869,7 @@ public class SQLManager implements AbstractDB { statement.setInt(1, getClusterId(cluster)); statement.setString(2, uuid.toString()); } - + @Override public PreparedStatement get() throws SQLException { return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_invited` (`cluster_id`, `user_uuid`) VALUES(?,?)"); @@ -2929,36 +2896,16 @@ public class SQLManager implements AbstractDB { stmt.executeBatch(); stmt.clearBatch(); stmt.close(); - + final PreparedStatement statement = connection.prepareStatement("DROP TABLE `" + prefix + "plot`"); statement.executeUpdate(); statement.close(); - } catch (final Exception e) { + } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return true; } - private class UUIDPair { - public final int id; - public final UUID uuid; - - public UUIDPair(final int id, final UUID uuid) { - this.id = id; - this.uuid = uuid; - } - } - - private class SettingsPair { - public final int id; - public final PlotSettings settings; - - public SettingsPair(final int id, final PlotSettings settings) { - this.id = id; - this.settings = settings; - } - } - @Override public void validateAllPlots(final Set toValidate) { try { @@ -2966,7 +2913,7 @@ public class SQLManager implements AbstractDB { CLOSED = false; connection = database.forceConnection(); } - } catch (final Exception e) { + } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } PS.debug("$1All DB transactions during this session are being validated (This may take a while if corrections need to be made)"); @@ -3013,12 +2960,12 @@ public class SQLManager implements AbstractDB { toRemove.removeAll(plot.getTrusted()); toAdd.removeAll(dataplot.getTrusted()); PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " trusted for: " + plot); - if (toRemove.size() > 0) { + if (!toRemove.isEmpty()) { for (final UUID uuid : toRemove) { removeTrusted(plot, uuid); } } - if (toAdd.size() > 0) { + if (!toAdd.isEmpty()) { for (final UUID uuid : toAdd) { setTrusted(plot, uuid); } @@ -3030,12 +2977,12 @@ public class SQLManager implements AbstractDB { toRemove.removeAll(plot.getMembers()); toAdd.removeAll(dataplot.getMembers()); PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " members for: " + plot); - if (toRemove.size() > 0) { + if (!toRemove.isEmpty()) { for (final UUID uuid : toRemove) { removeMember(plot, uuid); } } - if (toAdd.size() > 0) { + if (!toAdd.isEmpty()) { for (final UUID uuid : toAdd) { setMember(plot, uuid); } @@ -3047,38 +2994,36 @@ public class SQLManager implements AbstractDB { toRemove.removeAll(plot.getDenied()); toAdd.removeAll(dataplot.getDenied()); PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " denied for: " + plot); - if (toRemove.size() > 0) { + if (!toRemove.isEmpty()) { for (final UUID uuid : toRemove) { removeDenied(plot, uuid); } } - if (toAdd.size() > 0) { + if (!toAdd.isEmpty()) { for (final UUID uuid : toAdd) { setDenied(plot, uuid); } } } - final PlotSettings ps = plot.getSettings(); - final PlotSettings ds = dataplot.getSettings(); - final boolean[] pm = ps.getMerged(); - final boolean[] dm = ds.getMerged(); - if ((pm[0] != dm[0]) || (pm[1] != dm[1])) { + final boolean[] pm = plot.getMerged(); + final boolean[] dm = dataplot.getMerged(); + if (pm[0] != dm[0] || pm[1] != dm[1]) { PS.debug("&8 - &7Correcting merge for: " + plot); - setMerged(dataplot, ps.getMerged()); + setMerged(dataplot, plot.getMerged()); } final HashMap pf = plot.getFlags(); final HashMap df = dataplot.getFlags(); - if ((pf.size() != 0) && (df.size() != 0)) { - if ((pf.size() != df.size()) || !StringMan.isEqual(StringMan.joinOrdered(pf.values(), ","), StringMan.joinOrdered(df.values(), ","))) { + if (!pf.isEmpty() && !df.isEmpty()) { + if (pf.size() != df.size() || !StringMan.isEqual(StringMan.joinOrdered(pf.values(), ","), StringMan.joinOrdered(df.values(), ","))) { PS.debug("&8 - &7Correcting flags for: " + plot); setFlags(plot, pf.values()); } } } - + for (final Entry> entry : database.entrySet()) { final HashMap map = entry.getValue(); - if (map.size() > 0) { + if (!map.isEmpty()) { for (final Entry entry2 : map.entrySet()) { PS.debug("$1Plot was deleted: " + entry2.getValue() + "// TODO implement this when sure safe"); } @@ -3093,15 +3038,26 @@ public class SQLManager implements AbstractDB { @Override public void run() { try (Statement stmt = connection.createStatement()) { - stmt.executeUpdate("UPDATE `" + prefix + "cluster` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); - stmt.executeUpdate("UPDATE `" + prefix + "cluster_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + "'"); - stmt.executeUpdate("UPDATE `" + prefix + "cluster_invited` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "cluster` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "cluster_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "cluster_invited` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); stmt.executeUpdate("UPDATE `" + prefix + "plot` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); - stmt.executeUpdate("UPDATE `" + prefix + "plot_denied` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + "'"); - stmt.executeUpdate("UPDATE `" + prefix + "plot_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + "'"); - stmt.executeUpdate("UPDATE `" + prefix + "plot_trusted` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "plot_denied` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "plot_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "plot_trusted` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); stmt.close(); - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -3117,4 +3073,47 @@ public class SQLManager implements AbstractDB { e.printStackTrace(); } } + + public abstract class UniqueStatement { + + public String _method; + + public UniqueStatement(final String method) { + _method = method; + } + + public void addBatch(final PreparedStatement stmt) throws SQLException { + stmt.addBatch(); + } + + public void execute(final PreparedStatement stmt) throws SQLException { + stmt.executeBatch(); + } + + public abstract PreparedStatement get() throws SQLException; + + public abstract void set(final PreparedStatement stmt) throws SQLException; + } + + private class UUIDPair { + + public final int id; + public final UUID uuid; + + public UUIDPair(final int id, final UUID uuid) { + this.id = id; + this.uuid = uuid; + } + } + + private class SettingsPair { + + public final int id; + public final PlotSettings settings; + + public SettingsPair(final int id, final PlotSettings settings) { + this.id = id; + this.settings = settings; + } + } } diff --git a/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java b/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java index 57819f038..eea9c2740 100644 --- a/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java +++ b/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java @@ -24,7 +24,9 @@ import com.intellectualcrafters.plot.util.StringMan; /** * Created 2014-09-23 for PlotSquared - * + * + + */ public class AbstractFlag { public final String key; @@ -105,6 +107,6 @@ public class AbstractFlag { return false; } final AbstractFlag otherObj = (AbstractFlag) other; - return (otherObj.key.equals(key)); + return otherObj.key.equals(key); } } diff --git a/src/main/java/com/intellectualcrafters/plot/flag/Flag.java b/src/main/java/com/intellectualcrafters/plot/flag/Flag.java index a8a976e00..6fbc6a071 100644 --- a/src/main/java/com/intellectualcrafters/plot/flag/Flag.java +++ b/src/main/java/com/intellectualcrafters/plot/flag/Flag.java @@ -20,10 +20,11 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.flag; -import java.lang.reflect.Method; - import com.intellectualcrafters.plot.util.StringMan; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + public class Flag implements Cloneable { private AbstractFlag key; private Object value; @@ -51,13 +52,6 @@ public class Flag implements Cloneable { } } - public void setKey(final AbstractFlag key) { - this.key = key; - if (value instanceof String) { - value = key.parseValueRaw((String) value); - } - } - /** * Warning: Unchecked */ @@ -83,7 +77,14 @@ public class Flag implements Cloneable { public String getKey() { return key.getKey(); } - + + public void setKey(final AbstractFlag key) { + this.key = key; + if (value instanceof String) { + value = key.parseValueRaw((String) value); + } + } + /** * Get the value * @@ -99,7 +100,7 @@ public class Flag implements Cloneable { @Override public String toString() { - if (value.equals("")) { + if ("".equals(value)) { return key.getKey(); } return key + ":" + getValueString(); @@ -117,7 +118,7 @@ public class Flag implements Cloneable { return false; } final Flag other = (Flag) obj; - return (key.getKey().equals(other.key.getKey()) && value.equals(other.value)); + return key.getKey().equals(other.key.getKey()) && value.equals(other.value); } @Override @@ -139,7 +140,22 @@ public class Flag implements Cloneable { return new Flag(key, method.invoke(value)); } return new Flag(key, key.parseValueRaw(value.toString())); - } catch (Exception e) { + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + return this; + } catch (IllegalAccessException e) { + e.printStackTrace(); + return this; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return this; + } catch (NoSuchMethodException e) { + e.printStackTrace(); + return this; + } catch (SecurityException e) { + e.printStackTrace(); + return this; + } catch (InvocationTargetException e) { e.printStackTrace(); return this; } diff --git a/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java b/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java index b8c772b78..f9d91200d 100644 --- a/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java +++ b/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java @@ -115,7 +115,7 @@ public class FlagManager { } } }); - if ((getFlag(af.getKey()) == null) && flags.add(af)) { + if (getFlag(af.getKey()) == null && flags.add(af)) { if (reserved) { reserveFlag(af.getKey()); } @@ -126,11 +126,11 @@ public class FlagManager { public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) { Flag flag; - if ((settings.flags.size() == 0) || ((flag = settings.flags.get(id)) == null)) { + if (settings.flags.isEmpty() || (flag = settings.flags.get(id)) == null) { if (area == null) { return null; } - if (area.DEFAULT_FLAGS.size() == 0) { + if (area.DEFAULT_FLAGS.isEmpty()) { return null; } return area.DEFAULT_FLAGS.get(id); @@ -181,7 +181,7 @@ public class FlagManager { return false; } final Flag flag = getPlotFlagRaw(plot, strFlag); - return !((flag == null) || !((Boolean) flag.getValue())); + return !(flag == null || !((Boolean) flag.getValue())); } public static boolean isPlotFlagFalse(final Plot plot, final String strFlag) { @@ -189,7 +189,7 @@ public class FlagManager { return false; } final Flag flag = getPlotFlagRaw(plot, strFlag); - if ((flag == null) || ((Boolean) flag.getValue())) { + if (flag == null || (Boolean) flag.getValue()) { return false; } return false; @@ -206,7 +206,7 @@ public class FlagManager { } public static Flag getSettingFlagAbs(final PlotSettings settings, final String flag) { - if ((settings.flags == null) || (settings.flags.size() == 0)) { + if (settings.flags == null || settings.flags.isEmpty()) { return null; } return settings.flags.get(flag); @@ -260,7 +260,7 @@ public class FlagManager { public static HashMap getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) { final HashMap flags = new HashMap<>(); - if ((area != null) && (area.DEFAULT_FLAGS.size() != 0)) { + if (area != null && !area.DEFAULT_FLAGS.isEmpty()) { flags.putAll(area.DEFAULT_FLAGS); } if (ignorePluginflags) { @@ -312,12 +312,12 @@ public class FlagManager { public static void setPlotFlags(final Plot origin, final Set flags) { for (Plot plot : origin.getConnectedPlots()) { - if ((flags != null) && (flags.size() != 0)) { + if (flags != null && !flags.isEmpty()) { plot.getFlags().clear(); for (final Flag flag : flags) { plot.getFlags().put(flag.getKey(), flag); } - } else if (plot.getFlags().size() == 0) { + } else if (plot.getFlags().isEmpty()) { return; } else { plot.getFlags().clear(); @@ -328,12 +328,12 @@ public class FlagManager { } public static void setClusterFlags(final PlotCluster cluster, final Set flags) { - if ((flags != null) && (flags.size() != 0)) { + if (flags != null && !flags.isEmpty()) { cluster.settings.flags.clear(); for (final Flag flag : flags) { cluster.settings.flags.put(flag.getKey(), flag); } - } else if (cluster.settings.flags.size() == 0) { + } else if (cluster.settings.flags.isEmpty()) { return; } else { cluster.settings.flags.clear(); @@ -413,7 +413,7 @@ public class FlagManager { * @return AbstractFlag */ public static AbstractFlag getFlag(final String string, final boolean create) { - if ((getFlag(string) == null) && create) { + if (getFlag(string) == null && create) { return new AbstractFlag(string); } return getFlag(string); diff --git a/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java b/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java index 4464fc05c..23462ac94 100644 --- a/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java +++ b/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java @@ -1,7 +1,5 @@ package com.intellectualcrafters.plot.generator; -import java.util.Set; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.PlotArea; import com.intellectualcrafters.plot.object.PlotBlock; @@ -12,6 +10,8 @@ import com.intellectualcrafters.plot.util.PlotChunk; import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; +import java.util.Set; + public class AugmentedUtils { private static boolean enabled = true; @@ -30,7 +30,7 @@ public class AugmentedUtils { final int bz = cz << 4; RegionWrapper region = new RegionWrapper(bx, bx + 15, bz, bz + 15); Set areas = PS.get().getPlotAreas(world, region); - if (areas.size() == 0) { + if (areas.isEmpty()) { return; } final PseudoRandom r = new PseudoRandom(); diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java b/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java index bdb9d6ceb..92f6070ed 100644 --- a/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java +++ b/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java @@ -20,14 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.generator; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map.Entry; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.commands.Template; import com.intellectualcrafters.plot.object.ChunkLoc; @@ -44,6 +36,14 @@ import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.WorldUtil; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map.Entry; + public class HybridPlotManager extends ClassicPlotManager { @Override @@ -66,7 +66,7 @@ public class HybridPlotManager extends ClassicPlotManager { if (plot.exists()) { files.add(new FileBytes(newDir + "plot.schematic", Files.readAllBytes(plot.toPath()))); } - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); } Template.zipAll(plotworld.worldname, files); diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java b/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java index 79122d4f3..83306b2fb 100644 --- a/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java +++ b/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java @@ -20,9 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.generator; -import java.util.HashMap; -import java.util.HashSet; - import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; @@ -35,21 +32,133 @@ import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler.Dimension; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; -public class HybridPlotWorld extends ClassicPlotWorld { - public HybridPlotWorld(String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) { - super(worldname, id, generator, min, max); - } +import java.util.HashMap; +import java.util.HashSet; +public class HybridPlotWorld extends ClassicPlotWorld { public boolean ROAD_SCHEMATIC_ENABLED; public short SCHEMATIC_HEIGHT; public boolean PLOT_SCHEMATIC = false; public short REQUIRED_CHANGES = 0; public short PATH_WIDTH_LOWER; public short PATH_WIDTH_UPPER; - public HashMap> G_SCH; public HashMap> G_SCH_STATE; - + + public HybridPlotWorld(String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) { + super(worldname, id, generator, min, max); + } + + public static byte wrap(byte data, final int start) { + if ((data >= start) && (data < (start + 4))) { + data = (byte) ((((data - start) + 2) & 3) + start); + } + return data; + } + + public static byte wrap2(byte data, final int start) { + if ((data >= start) && (data < (start + 2))) { + data = (byte) ((((data - start) + 1) & 1) + start); + } + return data; + } + + // FIXME depends on block ids + // Possibly make abstract? + public static byte rotate(final short id, byte data) { + switch (id) { + case 162: + case 17: + if (data >= 4 && data < 12) { + if (data >= 8) { + return (byte) (data - 4); + } + return (byte) (data + 4); + } + return data; + case 183: + case 184: + case 185: + case 186: + case 187: + case 107: + case 53: + case 67: + case 108: + case 109: + case 114: + case 128: + case 134: + case 135: + case 136: + case 156: + case 163: + case 164: + case 180: + data = wrap(data, 0); + data = wrap(data, 4); + return data; + + case 26: + case 86: + data = wrap(data, 0); + return data; + case 64: + case 71: + case 193: + case 194: + case 195: + case 196: + case 197: + case 93: + case 94: + case 131: + case 145: + case 149: + case 150: + case 96: + case 167: + data = wrap(data, 0); + data = wrap(data, 4); + data = wrap(data, 8); + data = wrap(data, 12); + return data; + case 28: + case 66: + case 157: + case 27: + data = wrap2(data, 0); + data = wrap2(data, 3); + if (data == 2) { + data = 5; + } else if (data == 5) { + data = 2; + } + return data; + + case 23: + case 29: + case 33: + case 158: + case 54: + case 130: + case 146: + case 61: + case 62: + case 65: + case 68: + case 144: + data = wrap(data, 2); + return data; + case 143: + case 77: + data = wrap(data, 1); + return data; + default: + return data; + } + } + /** * This method is called when a world loads. Make sure you set all your constants here. You are provided with the * configuration section for that specific world. @@ -72,10 +181,10 @@ public class HybridPlotWorld extends ClassicPlotWorld { @Override public boolean isCompatible(PlotArea plotworld) { - if (plotworld == null || !(plotworld instanceof SquarePlotWorld)) { + if (!(plotworld instanceof SquarePlotWorld)) { return false; } - return ((ClassicPlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH; + return ((SquarePlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH; } public void setupSchematics() { @@ -99,11 +208,11 @@ public class HybridPlotWorld extends ClassicPlotWorld { final short w3 = (short) d3.getX(); final short l3 = (short) d3.getZ(); final short h3 = (short) d3.getY(); - int center_shift_x = 0; int center_shift_z = 0; if (l3 < PLOT_WIDTH) { center_shift_z = (PLOT_WIDTH - l3) / 2; } + int center_shift_x = 0; if (w3 < PLOT_WIDTH) { center_shift_x = (PLOT_WIDTH - w3) / 2; } @@ -114,7 +223,8 @@ public class HybridPlotWorld extends ClassicPlotWorld { final short id = ids[index]; final byte data = datas[index]; if (id != 0) { - addOverlayBlock((short) (x + shift + oddshift + center_shift_x), (y), (short) (z + shift + oddshift + center_shift_z), id, data, false); + addOverlayBlock((short) (x + shift + oddshift + center_shift_x), y, (short) (z + shift + oddshift + center_shift_z), id, + data, false); } } } @@ -136,20 +246,20 @@ public class HybridPlotWorld extends ClassicPlotWorld { } } } - if ((schem1 == null) || (schem2 == null) || (ROAD_WIDTH == 0)) { + if (schem1 == null || schem2 == null || ROAD_WIDTH == 0) { PS.debug(C.PREFIX.s() + "&3 - schematic: &7false"); return; } ROAD_SCHEMATIC_ENABLED = true; // Do not populate road if using schematic population ROAD_BLOCK = new PlotBlock(ROAD_BLOCK.id, (byte) 0); - + final short[] ids1 = schem1.getIds(); final byte[] datas1 = schem1.getDatas(); - + final short[] ids2 = schem2.getIds(); final byte[] datas2 = schem2.getDatas(); - + final Dimension d1 = schem1.getSchematicDimension(); final short w1 = (short) d1.getX(); final short l1 = (short) d1.getZ(); @@ -166,8 +276,8 @@ public class HybridPlotWorld extends ClassicPlotWorld { final short id = ids1[index]; final byte data = datas1[index]; if (id != 0) { - addOverlayBlock((short) (x - (shift)), (y), (short) (z + shift + oddshift), id, data, false); - addOverlayBlock((short) (z + shift + oddshift), (y), (short) (x - shift), id, data, true); + addOverlayBlock((short) (x - shift), y, (short) (z + shift + oddshift), id, data, false); + addOverlayBlock((short) (z + shift + oddshift), y, (short) (x - shift), id, data, true); } } } @@ -179,130 +289,13 @@ public class HybridPlotWorld extends ClassicPlotWorld { final short id = ids2[index]; final byte data = datas2[index]; if (id != 0) { - addOverlayBlock((short) (x - shift), (y), (short) (z - shift), id, data, false); + addOverlayBlock((short) (x - shift), y, (short) (z - shift), id, data, false); } } } } } - public static byte wrap(byte data, final int start) { - if ((data >= start) && (data < (start + 4))) { - data = (byte) ((((data - start) + 2) & 3) + start); - } - return data; - } - - public static byte wrap2(byte data, final int start) { - if ((data >= start) && (data < (start + 2))) { - data = (byte) ((((data - start) + 1) & 1) + start); - } - return data; - } - - // FIXME depends on block ids - // Possibly make abstract? - public static byte rotate(final short id, byte data) { - switch (id) { - case 162: - case 17: { - if ((data >= 4) && (data < 12)) { - if (data >= 8) { - return (byte) (data - 4); - } - return (byte) (data + 4); - } - return data; - } - case 183: - case 184: - case 185: - case 186: - case 187: - case 107: - case 53: - case 67: - case 108: - case 109: - case 114: - case 128: - case 134: - case 135: - case 136: - case 156: - case 163: - case 164: - case 180: { - data = wrap(data, 0); - data = wrap(data, 4); - return data; - } - - case 26: - case 86: { - data = wrap(data, 0); - return data; - } - case 64: - case 71: - case 193: - case 194: - case 195: - case 196: - case 197: - case 93: - case 94: - case 131: - case 145: - case 149: - case 150: - case 96: - case 167: { - data = wrap(data, 0); - data = wrap(data, 4); - data = wrap(data, 8); - data = wrap(data, 12); - return data; - } - case 28: - case 66: - case 157: - case 27: { - data = wrap2(data, 0); - data = wrap2(data, 3); - if (data == 2) { - data = 5; - } else if (data == 5) { - data = 2; - } - return data; - } - - case 23: - case 29: - case 33: - case 158: - case 54: - case 130: - case 146: - case 61: - case 62: - case 65: - case 68: - case 144: { - data = wrap(data, 2); - return data; - } - case 143: - case 77: { - data = wrap(data, 1); - return data; - } - default: - return data; - } - } - public void addOverlayBlock(short x, final short y, short z, final short id, byte data, final boolean rotate) { if (z < 0) { z += SIZE; @@ -312,7 +305,7 @@ public class HybridPlotWorld extends ClassicPlotWorld { } if (rotate) { final byte newdata = rotate(id, data); - if ((data == 0) && (newdata == 0)) { + if (data == 0 && newdata == 0) { return; } data = newdata; diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java b/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java index 88f0a0ed6..ea54ca7cc 100644 --- a/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java +++ b/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java @@ -36,17 +36,21 @@ import java.util.concurrent.atomic.AtomicInteger; public abstract class HybridUtils { public static HybridUtils manager; - + public static Set regions; + public static Set chunks = new HashSet<>(); + public static PlotArea area; + public static boolean UPDATE = false; + public abstract void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal whenDone); - + public void analyzePlot(final Plot origin, final RunnableVal whenDone) { final ArrayDeque zones = new ArrayDeque<>(origin.getRegions()); final ArrayList analysis = new ArrayList<>(); Runnable run = new Runnable() { @Override public void run() { - if (zones.size() == 0) { - if (analysis.size() > 0) { + if (zones.isEmpty()) { + if (!analysis.isEmpty()) { whenDone.value = new PlotAnalysis(); for (PlotAnalysis data : analysis) { whenDone.value.air += data.air; @@ -80,7 +84,7 @@ public abstract class HybridUtils { result.add(whenDone.value.data); result.add(whenDone.value.air); result.add(whenDone.value.variety); - + result.add(whenDone.value.changes_sd); result.add(whenDone.value.faces_sd); result.add(whenDone.value.data_sd); @@ -104,14 +108,9 @@ public abstract class HybridUtils { }; run.run(); } - + public abstract int checkModified(final String world, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks); - public static Set regions; - public static Set chunks = new HashSet<>(); - public static PlotArea area; - public static boolean UPDATE = false; - public final ArrayList getChunks(final ChunkLoc region) { final ArrayList chunks = new ArrayList<>(); final int sx = region.x << 5; @@ -145,7 +144,7 @@ public abstract class HybridUtils { Runnable run = new Runnable() { @Override public void run() { - if (zones.size() == 0) { + if (zones.isEmpty()) { TaskManager.runTask(whenDone); return; @@ -209,7 +208,7 @@ public abstract class HybridUtils { if ((count.intValue() % 20) == 0) { PS.debug("PROGRESS: " + ((100 * (2048 - chunks.size())) / 2048) + "%"); } - if ((regions.size() == 0) && (chunks.size() == 0)) { + if ((regions.isEmpty()) && (chunks.isEmpty())) { HybridUtils.UPDATE = false; PS.debug(C.PREFIX.s() + "Finished road conversion"); // CANCEL TASK @@ -223,7 +222,7 @@ public abstract class HybridUtils { last.set((int) (System.currentTimeMillis() - baseTime)); } if (chunks.size() < 1024) { - if (regions.size() > 0) { + if (!regions.isEmpty()) { Iterator iter = regions.iterator(); final ChunkLoc loc = iter.next(); iter.remove(); @@ -233,7 +232,7 @@ public abstract class HybridUtils { System.gc(); } } - if (chunks.size() > 0) { + if (!chunks.isEmpty()) { final long diff = System.currentTimeMillis() + 1; if (((System.currentTimeMillis() - baseTime - last.get()) > 2000) && (last.get() != 0)) { last.set(0); @@ -252,7 +251,7 @@ public abstract class HybridUtils { return; } if ((((System.currentTimeMillis() - baseTime) - last.get()) < 1500) && (last.get() != 0)) { - while ((System.currentTimeMillis() < diff) && (chunks.size() > 0)) { + while ((System.currentTimeMillis() < diff) && (!chunks.isEmpty())) { Iterator iter = chunks.iterator(); final ChunkLoc chunk = iter.next(); iter.remove(); diff --git a/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java b/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java index 6dc5db703..cc521a230 100644 --- a/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java +++ b/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java @@ -29,8 +29,8 @@ public abstract class IndependentPlotGenerator { * Return a new PlotArea object * @param world world name * @param id (May be null) Area name - * @param min Min plot id (may be null) - * @param max Max plot id (may be null) + * @param min Min plot type (may be null) + * @param max Max plot type (may be null) * @return */ public abstract PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max); diff --git a/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java b/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java index aa5597c6c..cb6186564 100644 --- a/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java +++ b/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java @@ -23,7 +23,7 @@ public abstract class SquarePlotManager extends GridPlotManager { Runnable run = new Runnable() { @Override public void run() { - if (regions.size() == 0) { + if (regions.isEmpty()) { whenDone.run(); return; } diff --git a/src/main/java/com/intellectualcrafters/plot/object/Location.java b/src/main/java/com/intellectualcrafters/plot/object/Location.java index 0c73ff1a1..f4cf4e56f 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/Location.java +++ b/src/main/java/com/intellectualcrafters/plot/object/Location.java @@ -4,20 +4,15 @@ import com.intellectualcrafters.plot.PS; /** * Created 2015-02-11 for PlotSquared - * + * + */ public class Location implements Cloneable, Comparable { private int x, y, z; private float yaw, pitch; private String world; private boolean built; - private final Object o; - - @Override - public Location clone() { - return new Location(world, x, y, z, yaw, pitch); - } - + public Location(final String world, final int x, final int y, final int z, final float yaw, final float pitch) { this.world = world; this.x = x; @@ -26,7 +21,6 @@ public class Location implements Cloneable, Comparable { this.yaw = yaw; this.pitch = pitch; built = false; - o = null; } public Location() { @@ -36,7 +30,12 @@ public class Location implements Cloneable, Comparable { public Location(final String world, final int x, final int y, final int z) { this(world, x, y, z, 0f, 0f); } - + + @Override + public Location clone() { + return new Location(world, x, y, z, yaw, pitch); + } + public int getX() { return x; } @@ -67,7 +66,12 @@ public class Location implements Cloneable, Comparable { public String getWorld() { return world; } - + + public void setWorld(final String world) { + this.world = world; + built = false; + } + public PlotArea getPlotArea() { return PS.get().getPlotAreaAbs(this); } @@ -76,7 +80,7 @@ public class Location implements Cloneable, Comparable { PlotArea area = PS.get().getPlotAreaAbs(this); return area != null ? area.getOwnedPlot(this) : null; } - + public Plot getOwnedPlotAbs() { PlotArea area = PS.get().getPlotAreaAbs(this); return area != null ? area.getOwnedPlotAbs(this) : null; @@ -88,25 +92,19 @@ public class Location implements Cloneable, Comparable { public boolean isPlotRoad() { PlotArea area = PS.get().getPlotAreaAbs(this); - if (area == null) { - return false; - } - return area.getPlotAbs(this) == null; + return area != null && area.getPlotAbs(this) == null; } - + public boolean isUnownedPlotArea() { PlotArea area = PS.get().getPlotAreaAbs(this); - if (area == null) { - return false; - } - return area.getOwnedPlotAbs(this) == null; + return area != null && area.getOwnedPlotAbs(this) == null; } public PlotManager getPlotManager() { PlotArea pa = getPlotArea(); return pa != null ? pa.getPlotManager() : null; } - + public Plot getPlotAbs() { PlotArea area = PS.get().getPlotAreaAbs(this); return area != null ? area.getPlotAbs(this) : null; @@ -116,15 +114,10 @@ public class Location implements Cloneable, Comparable { PlotArea area = PS.get().getPlotAreaAbs(this); return area != null ? area.getPlot(this) : null; } - + public ChunkLoc getChunkLoc() { return new ChunkLoc(x >> 4, z >> 4); } - - public void setWorld(final String world) { - this.world = world; - built = false; - } public float getYaw() { return yaw; @@ -156,7 +149,7 @@ public class Location implements Cloneable, Comparable { final double x = getX() - l2.getX(); final double y = getY() - l2.getY(); 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) { @@ -164,32 +157,31 @@ public class Location implements Cloneable, Comparable { } public boolean isInSphere(final Location origin, final int radius) { - return getEuclideanDistanceSquared(origin) < (radius * radius); + return getEuclideanDistanceSquared(origin) < radius * radius; } @Override public int hashCode() { int hash = 127; - hash = (hash * 31) + x; - hash = (hash * 31) + y; - hash = (hash * 31) + z; - hash = (int) ((hash * 31) + getYaw()); - hash = (int) ((hash * 31) + getPitch()); - return (hash * 31) + (world == null ? 127 : world.hashCode()); + hash = hash * 31 + x; + hash = hash * 31 + y; + hash = hash * 31 + z; + hash = (int) (hash * 31 + getYaw()); + hash = (int) (hash * 31 + getPitch()); + return hash * 31 + (world == null ? 127 : world.hashCode()); } public boolean isInAABB(final Location min, final Location max) { - 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) { final double l = this.x - x; - final double w = z - z; - final double c = Math.sqrt((l * l) + (w * w)); - if (((Math.asin(w / c) / Math.PI) * 180) > 90) { - setYaw((float) (180 - ((-Math.asin(l / c) / Math.PI) * 180))); + final double c = Math.sqrt(l * l + 0.0); + if (Math.asin((double) 0 / c) / Math.PI * 180 > 90) { + setYaw((float) (180 - -Math.asin(l / c) / Math.PI * 180)); } else { - setYaw((float) ((-Math.asin(l / c) / Math.PI) * 180)); + setYaw((float) (-Math.asin(l / c) / Math.PI * 180)); } built = false; } @@ -211,7 +203,7 @@ public class Location implements Cloneable, Comparable { return false; } 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 @@ -219,10 +211,10 @@ public class Location implements Cloneable, Comparable { if (o == 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; } - if ((x < o.getX()) && (y < o.getY()) && (z < o.getZ())) { + if (x < o.getX() && y < o.getY() && z < o.getZ()) { return -1; } return 1; diff --git a/src/main/java/com/intellectualcrafters/plot/object/Plot.java b/src/main/java/com/intellectualcrafters/plot/object/Plot.java index 4793fbe26..411c47ebd 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/Plot.java +++ b/src/main/java/com/intellectualcrafters/plot/object/Plot.java @@ -62,17 +62,18 @@ import java.util.concurrent.atomic.AtomicInteger; */ @SuppressWarnings("javadoc") public class Plot { + /** + * @deprecated raw access is deprecated + */ + @Deprecated + private static HashSet connected_cache; + private static HashSet regions_cache; /** * plot ID * Direct access is Deprecated: use getId() */ @Deprecated public final PlotId id; - /** - * plot world - * Direct access is Deprecated: use getWorld() - */ - private PlotArea area; /** * plot owner * (Merged plots can have multiple owners) @@ -80,7 +81,6 @@ public class Plot { */ @Deprecated public UUID owner; - /** * Plot creation timestamp (not accurate if the plot was created before this was implemented)
* - Milliseconds since the epoch
@@ -88,7 +88,6 @@ public class Plot { */ @Deprecated public long timestamp; - /** * List of trusted (with plot permissions) * Direct access is Deprecated: use getTrusted() @@ -127,7 +126,11 @@ public class Plot { */ @Deprecated public int temp; - + /** + * plot world + * Direct access is Deprecated: use getWorld() + */ + private PlotArea area; /** * Session only plot metadata (session is until the server stops)
*
@@ -135,15 +138,19 @@ public class Plot { * @see FlagManager */ private ConcurrentHashMap meta; - + /** + * The cached origin plot
+ * - The origin plot is used for plot grouping and relational data + */ + private Plot origin; + /** * Constructor for a new plot
* (Only changes after plot.create() will be properly set in the database) * - * @see Plot#getPlot(String, PlotId) for existing plots * @see Plot#getPlot(Location) for existing plots * - * @param world + * @param area * @param id * @param owner */ @@ -157,9 +164,9 @@ public class Plot { * Constructor for an unowned plot
* (Only changes after plot.create() will be properly set in the database) * - * @see Plot#getPlot(String, PlotId) for existing plots + * @see Plot#getPlot(Location) for existing plots * - * @param world + * @param area * @param id */ public Plot(final PlotArea area, final PlotId id) { @@ -167,6 +174,57 @@ public class Plot { this.id = id; } + /** + * Constructor for a temporary plot (use -1 for temp)
+ * The database will ignore any queries regarding temporary plots. + * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this) + * + * @see Plot#getPlot(Location) for existing plots + * + * @param area + * @param id + * @param owner + * @param temp + */ + public Plot(final PlotArea area, final PlotId id, final UUID owner, final int temp) { + this.area = area; + this.id = id; + this.owner = owner; + this.temp = temp; + } + + /** + * Constructor for a saved plots (Used by the database manager when plots are fetched) + * + * @see Plot#getPlot(Location) for existing plots + * + * @param id + * @param owner + * @param trusted + * @param denied + * @param merged + */ + public Plot(final PlotId id, final UUID owner, final HashSet trusted, final HashSet members, final HashSet denied, final String alias, final BlockLoc position, + final Collection flags, final PlotArea area, final boolean[] merged, final long timestamp, final int temp) { + this.id = id; + this.area = area; + this.owner = owner; + settings = new PlotSettings(); + this.members = members; + this.trusted = trusted; + this.denied = denied; + settings.setAlias(alias); + settings.setPosition(position); + settings.setMerged(merged); + if (flags != null) { + for (final Flag flag : flags) { + settings.flags.put(flag.getKey(), flag); + } + } + this.timestamp = timestamp; + this.temp = temp; + } + public static Plot fromString(PlotArea defaultArea, String string) { final String[] split = string.split(";|,"); if (split.length == 2) { @@ -205,58 +263,7 @@ public class Plot { } return null; } - - /** - * Constructor for a temporary plot (use -1 for temp)
- * The database will ignore any queries regarding temporary plots. - * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this) - * - * @see Plot#getPlot(String, PlotId) for existing plots - * - * @param world - * @param id - * @param owner - * @param temp - */ - public Plot(final PlotArea area, final PlotId id, final UUID owner, final int temp) { - this.area = area; - this.id = id; - this.owner = owner; - this.temp = temp; - } - - /** - * Constructor for a saved plots (Used by the database manager when plots are fetched) - * - * @see Plot#getPlot(String, PlotId) for existing plots - * - * @param id - * @param owner - * @param trusted - * @param denied - * @param merged - */ - public Plot(final PlotId id, final UUID owner, final HashSet trusted, final HashSet members, final HashSet denied, final String alias, final BlockLoc position, - final Collection flags, final PlotArea area, final boolean[] merged, final long timestamp, final int temp) { - this.id = id; - this.area = area; - this.owner = owner; - settings = new PlotSettings(); - this.members = members; - this.trusted = trusted; - this.denied = denied; - settings.setAlias(alias); - settings.setPosition(position); - settings.setMerged(merged); - if (flags != null) { - for (final Flag flag : flags) { - settings.flags.put(flag.getKey(), flag); - } - } - this.timestamp = timestamp; - this.temp = temp; - } - + /** * Session only plot metadata (session is until the server stops)
*
@@ -267,7 +274,7 @@ public class Plot { */ public void setMeta(final String key, final Object value) { if (meta == null) { - meta = new ConcurrentHashMap(); + meta = new ConcurrentHashMap<>(); } meta.put(key, value); } @@ -368,9 +375,9 @@ public class Plot { * @return boolean false if the player is allowed to enter */ public boolean isDenied(final UUID uuid) { - return (denied != null) && ((denied.contains(DBFunc.everyone) && !isAdded(uuid)) || (!isAdded(uuid) && denied.contains(uuid))); + return denied != null && (denied.contains(DBFunc.everyone) && !isAdded(uuid) || !isAdded(uuid) && denied.contains(uuid)); } - + /** * Get the plot ID */ @@ -428,12 +435,6 @@ public class Plot { return equals(getBasePlot(false)); } - /** - * The cached origin plot
- * - The origin plot is used for plot grouping and relational data - */ - private Plot origin; - /** * The base plot is an arbitrary but specific connected plot. It is useful for the following:
* - Merged plots need to be treated as a single plot for most purposes
@@ -443,7 +444,7 @@ public class Plot { * @return base Plot */ public Plot getBasePlot(boolean recalculate) { - if ((origin != null && !recalculate)) { + if (origin != null && !recalculate) { if (this.equals(origin)) { return this; } @@ -456,7 +457,7 @@ public class Plot { origin = this; PlotId min = id; for (Plot plot : getConnectedPlots()) { - if (plot.id.y < min.y || (plot.id.y.equals(min.y) && plot.id.x < min.x)) { + if (plot.id.y < min.y || plot.id.y.equals(min.y) && plot.id.x < min.x) { origin = plot; min = plot.id; } @@ -521,24 +522,24 @@ public class Plot { case 7: int i = direction - 4; int i2 = 0; - return settings.getMerged(i2) - && settings.getMerged(i) - && area.getPlotAbs(id.getRelative(i)).getMerged(i2) - && settings.getMerged(i) - && settings.getMerged(i2) - && area.getPlotAbs(id.getRelative(i2)).getMerged(i); + if (settings.getMerged(i2)) { + if (settings.getMerged(i)) { + if (area.getPlotAbs(id.getRelative(i)).getMerged(i2)) { + if (area.getPlotAbs(id.getRelative(i2)).getMerged(i)) { + return true; + } + } + } + } + return false; case 4: case 5: case 6: i = direction - 4; i2 = direction - 3; - return settings.getMerged(i2) - && settings.getMerged(i) - && area.getPlotAbs(id.getRelative(i)).getMerged(i2) - && settings.getMerged(i) - && settings.getMerged(i2) - && area.getPlotAbs(id.getRelative(i2)).getMerged(i); - + return settings.getMerged(i2) && settings.getMerged(i) && area.getPlotAbs(id.getRelative(i)).getMerged(i2) && area + .getPlotAbs(id.getRelative(i2)).getMerged(i); + } return false; } @@ -554,6 +555,14 @@ public class Plot { return denied; } + /** + * Set the denied users for this plot + * @param uuids + */ + public void setDenied(final Set uuids) { + PlotHandler.setDenied(this, uuids); + } + /** * Get the trusted users * @return @@ -565,6 +574,14 @@ public class Plot { return trusted; } + /** + * Set the trusted users for this plot + * @param uuids + */ + public void setTrusted(final Set uuids) { + PlotHandler.setTrusted(this, uuids); + } + /** * Get the members * @return @@ -576,6 +593,14 @@ public class Plot { return members; } + /** + * Set the members for this plot + * @param uuids + */ + public void setMembers(final Set uuids) { + PlotHandler.setMembers(this, uuids); + } + /** * Deny someone (updates database as well) * @param uuid @@ -610,34 +635,10 @@ public class Plot { PlotHandler.setOwner(this, owner); } - /** - * Set the trusted users for this plot - * @param uuids - */ - public void setTrusted(final Set uuids) { - PlotHandler.setTrusted(this, uuids); - } - - /** - * Set the members for this plot - * @param uuids - */ - public void setMembers(final Set uuids) { - PlotHandler.setMembers(this, uuids); - } - - /** - * Set the denied users for this plot - * @param uuids - */ - public void setDenied(final Set uuids) { - PlotHandler.setDenied(this, uuids); - } - /** * Clear a plot - * @see this#clear(Plot, boolean, Runnable) - * @see this#clearAsPlayer(Plot, boolean, Runnable) + * @see this#clear(Runnable) + * @see this#clear(boolean, boolean, Runnable) * @see #deletePlot(Runnable) to clear and delete a plot * @param whenDone A runnable to execute when clearing finishes, or null */ @@ -663,7 +664,7 @@ public class Plot { Runnable run = new Runnable() { @Override public void run() { - if (queue.size() == 0) { + if (queue.isEmpty()) { final AtomicInteger finished = new AtomicInteger(0); final Runnable run = new Runnable() { @Override @@ -690,7 +691,7 @@ public class Plot { return; } final Plot current = queue.poll(); - if ((area.TERRAIN != 0) || Settings.FAST_CLEAR) { + if (area.TERRAIN != 0 || Settings.FAST_CLEAR) { ChunkManager.manager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); return; } @@ -703,7 +704,6 @@ public class Plot { /** * Set the biome for a plot asynchronously - * @param plot * @param biome The biome e.g. "forest" * @param whenDone The task to run when finished, or null */ @@ -712,7 +712,7 @@ public class Plot { Runnable run = new Runnable() { @Override public void run() { - if (regions.size() == 0) { + if (regions.isEmpty()) { Plot.this.refreshChunks(); TaskManager.runTask(whenDone); return; @@ -729,15 +729,15 @@ public class Plot { ChunkManager.manager.unloadChunk(Plot.this.area.worldname, loc, true, true); } }, this, 5); - + } }; run.run(); } - + /** * Unlink the plot and all connected plots - * @param plot + * @param createSign * @param createRoad * @return */ @@ -763,7 +763,7 @@ public class Plot { if (createRoad) { manager.startPlotUnlink(area, ids); } - if ((area.TERRAIN != 3) && createRoad) { + if (area.TERRAIN != 3 && createRoad) { for (Plot current : plots) { if (current.getMerged(1)) { manager.createRoadEast(area, current); @@ -794,7 +794,6 @@ public class Plot { /** * Set the sign for a plot to a specific name * @param name - * @param p */ public void setSign(final String name) { if (!PS.get().isMainThread(Thread.currentThread())) { @@ -841,14 +840,6 @@ public class Plot { FlagManager.addPlotFlag(this, new Flag(FlagManager.getFlag(flag), value)); } - /** - * Set a flag for this plot - * @param flags - */ - public void setFlags(Set flags) { - FlagManager.setPlotFlags(this, flags); - } - /** * Remove a flag from this plot * @param flag @@ -867,7 +858,7 @@ public class Plot { /** * Delete a plot (use null for the runnable if you don't need to be notified on completion) - * @see PS#removePlot(String, PlotId, boolean) + * @see PS#removePlot(Plot, boolean) * @see #clear(Runnable) to simply clear a plot */ public boolean deletePlot(final Runnable whenDone) { @@ -896,7 +887,6 @@ public class Plot { * 3 = Mob * 4 = Boat * 5 = Misc - * @param plot * @return */ public int[] countEntities() { @@ -951,13 +941,13 @@ public class Plot { /** * Unlink a plot and remove the roads - * @see this#unlinkPlot(Plot, boolean, boolean) + * @see this#unlinkPlot(boolean, boolean) * @return true if plot was linked */ public boolean unlink() { return unlinkPlot(true, true); } - + public Location getCenter() { Location top = getTop(); Location bot = getBottom(); @@ -966,12 +956,11 @@ public class Plot { /** * Return the home location for the plot - * @see this#getPlotHome(Plot) * @return Home location */ public Location getHome() { final BlockLoc home = getPosition(); - if ((home == null) || ((home.x == 0) && (home.z == 0))) { + if (home == null || home.x == 0 && home.z == 0) { return getDefaultHome(); } else { Location bot = getBottomAbs(); @@ -983,6 +972,24 @@ public class Plot { } } + /** + * Set the home location + * @param loc + */ + public void setHome(BlockLoc loc) { + final BlockLoc pos = getSettings().getPosition(); + if ((pos == null || pos.equals(new BlockLoc(0, 0, 0))) && loc == null || pos != null && pos.equals(loc)) { + return; + } + Plot plot = getBasePlot(false); + plot.getSettings().setPosition(loc); + if (plot.getSettings().getPosition() == null) { + DBFunc.setPosition(plot, ""); + } else { + DBFunc.setPosition(plot, getSettings().getPosition().toString()); + } + } + /** * Get the default home location for a plot
* - Ignores any home location set for that specific plot @@ -993,11 +1000,11 @@ public class Plot { if (area.DEFAULT_HOME != null) { final int x; final int z; - if ((area.DEFAULT_HOME.x == Integer.MAX_VALUE) && (area.DEFAULT_HOME.z == Integer.MAX_VALUE)) { + if (area.DEFAULT_HOME.x == Integer.MAX_VALUE && area.DEFAULT_HOME.z == Integer.MAX_VALUE) { // center RegionWrapper largest = plot.getLargestRegion(); - x = ((largest.maxX - largest.minX) / 2) + largest.minX; - z = ((largest.maxZ - largest.minZ) / 2) + largest.minZ; + x = (largest.maxX - largest.minX) / 2 + largest.minX; + z = (largest.maxZ - largest.minZ) / 2 + largest.minZ; } else { // specific Location bot = plot.getBottomAbs(); @@ -1009,7 +1016,7 @@ public class Plot { } // Side RegionWrapper largest = plot.getLargestRegion(); - final int x = ((largest.maxX - largest.minX) / 2) + largest.minX; + final int x = (largest.maxX - largest.minX) / 2 + largest.minX; final int z = largest.minZ - 1; final PlotManager manager = plot.getManager(); final int y = Math.max(WorldUtil.IMP.getHeighestBlock(plot.area.worldname, x, z), manager.getSignLoc(plot.area, plot).getY()); @@ -1026,9 +1033,9 @@ public class Plot { for (final Rating rating : ratings) { sum += rating.getAverageRating(); } - return (sum / ratings.size()); + return sum / ratings.size(); } - + /** * Set a rating for a user
* - If the user has already rated, the following will return false @@ -1053,7 +1060,7 @@ public class Plot { public void clearRatings() { Plot base = getBasePlot(false); PlotSettings baseSettings = base.getSettings(); - if (baseSettings.ratings != null && baseSettings.ratings.size() > 0) { + if (baseSettings.ratings != null && !baseSettings.ratings.isEmpty()) { DBFunc.deleteRatings(base); baseSettings.ratings = null; } @@ -1066,7 +1073,7 @@ public class Plot { */ public HashMap getRatings() { Plot base = getBasePlot(false); - final HashMap map = new HashMap(); + final HashMap map = new HashMap<>(); if (base.getSettings().ratings == null) { return map; } @@ -1076,46 +1083,9 @@ public class Plot { return map; } - /** - * Set the home location - * @param loc - */ - public void setHome(BlockLoc loc) { - final BlockLoc pos = getSettings().getPosition(); - if (((pos == null || pos.equals(new BlockLoc(0, 0, 0))) && (loc == null)) || ((pos != null) && pos.equals(loc))) { - return; - } - Plot plot = getBasePlot(false); - plot.getSettings().setPosition(loc); - if (plot.getSettings().getPosition() == null) { - DBFunc.setPosition(plot, ""); - } else { - DBFunc.setPosition(plot, getSettings().getPosition().toString()); - } - } - - /** - * Set the plot alias - * @param alias - */ - public void setAlias(String alias) { - for (Plot current : getConnectedPlots()) { - final String name = getSettings().getAlias(); - if (alias == null) { - alias = ""; - } - if (name.equals(alias)) { - return; - } - current.getSettings().setAlias(alias); - DBFunc.setAlias(current, alias); - } - } - /** * Resend all chunks inside the plot to nearby players
* This should not need to be called - * @see this#update(Plot) */ public void refreshChunks() { TaskManager.runTask(new Runnable() { @@ -1245,25 +1215,21 @@ public class Plot { /** * Swap the settings for two plots - * @param p1 * @param p2 * @param whenDone * @return */ public boolean swapData(Plot p2, final Runnable whenDone) { if (owner == null) { - if ((p2 != null) && (p2.owner != null)) { + if (p2 != null && p2.hasOwner()) { p2.moveData(this, whenDone); return true; } return false; } - if ((p2 == null) || (p2.owner == null)) { - if (owner != null) { - moveData(p2, whenDone); - return true; - } - return false; + if (p2 == null || p2.owner == null) { + moveData(p2, whenDone); + return true; } // Swap cached final PlotId temp = new PlotId(this.getId().x, this.getId().y); @@ -1285,7 +1251,6 @@ public class Plot { /** * Move the settings for a plot - * @param pos1 * @param pos2 * @param whenDone * @return @@ -1315,7 +1280,6 @@ public class Plot { * Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like each plot treated as * a small plot use getPlotTopLocAbs(...) * - * @param plot * @return Location top of mega plot */ public Location getExtendedTopAbs() { @@ -1337,8 +1301,6 @@ public class Plot { * - Does not respect mega plots
* - Merged plots, only the road will be considered part of the plot
* - * @param plot - * * @return Location bottom of mega plot */ public Location getExtendedBottomAbs() { @@ -1361,7 +1323,6 @@ public class Plot { * - the returned locations will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape * @deprecated as merged plots no longer need to be rectangular * @return new Location[] { bottom, top } - * @see this#getCorners(Plot) */ @Deprecated public Location[] getCorners() { @@ -1374,11 +1335,9 @@ public class Plot { /** * Remove the east road section of a plot
* - Used when a plot is merged
- * @param plotworld - * @param plot */ public void removeRoadEast() { - if ((area.TYPE != 0) && (area.TERRAIN > 1)) { + if (area.TYPE != 0 && area.TERRAIN > 1) { if (area.TERRAIN == 3) { return; } @@ -1394,12 +1353,11 @@ public class Plot { } /** - * Returns the top and bottom plot id.
+ * Returns the top and bottom plot type.
* - If the plot is not connected, it will return itself for the top/bottom
* - the returned ids will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape * @deprecated as merged plots no longer need to be rectangular * @return new Plot[] { bottom, top } - * @see this#getCornerIds(Plot) */ @Deprecated public PlotId[] getCornerIds() { @@ -1445,11 +1403,10 @@ public class Plot { * Swap the plot contents and settings with another location
* - The destination must correspond to a valid plot of equal dimensions * @see ChunkManager#swap(Location, Location, Location, Location, Runnable) to swap terrain - * @see this#getPlotSelectionIds(PlotId, PlotId) to get the plots inside a selection - * @see this#swapData(Plot, Plot, Runnable) to swap plot settings + * @see this#swapData(Plot, Runnable) to swap plot settings * @param destination The other plot to swap with * @param whenDone A task to run when finished, or null - * @see this#swapData(Plot, Plot, Runnable) + * @see this#swapData(Plot, Runnable) * @return boolean if swap was successful */ public boolean swap(final Plot destination, final Runnable whenDone) { @@ -1470,11 +1427,11 @@ public class Plot { /** * Get plot display name * - * @return alias if set, else id + * @return alias if set, else type */ @Override public String toString() { - if ((settings != null) && (settings.getAlias().length() > 1)) { + if (settings != null && settings.getAlias().length() > 1) { return settings.getAlias(); } return area + ";" + id.x + ";" + id.y; @@ -1610,10 +1567,7 @@ public class Plot { return false; } final Plot other = (Plot) obj; - if (hashCode() != other.hashCode()) { - return false; - } - return ((id.x.equals(other.id.x)) && (id.y.equals(other.id.y)) && area == other.area); + return hashCode() == other.hashCode() && id.x.equals(other.id.x) && id.y.equals(other.id.y) && area == other.area; } /** @@ -1638,6 +1592,14 @@ public class Plot { return settings.flags; } + /** + * Set a flag for this plot + * @param flags + */ + public void setFlags(Set flags) { + FlagManager.setPlotFlags(this, flags); + } + /** * Get the plot Alias
* - Returns an empty string if no alias is set @@ -1651,27 +1613,20 @@ public class Plot { } /** - * Set the raw merge data
- * - Updates DB
- * - Does not modify terrain
- * Get if the plot is merged in a direction
- * ----------
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * ----------
- * Note: Diagonal merging (4-7) must be done by merging the corresponding plots. - * @param merged + * Set the plot alias + * @param alias */ - public void setMerged(boolean[] merged) { - getSettings().setMerged(merged); - DBFunc.setMerged(this, merged); - connected_cache = null; - regions_cache = null; - if (origin != null) { - origin.origin = null; - origin = null; + public void setAlias(String alias) { + for (Plot current : getConnectedPlots()) { + final String name = getSettings().getAlias(); + if (alias == null) { + alias = ""; + } + if (name.equals(alias)) { + return; + } + current.getSettings().setAlias(alias); + DBFunc.setAlias(current, alias); } } @@ -1693,7 +1648,7 @@ public class Plot { if (value) { Plot other = getRelative(direction).getBasePlot(false); if (!other.equals(getBasePlot(false))) { - Plot base = ((other.id.y < id.y) || ((other.id.y.equals(id.y)) && (other.id.x < id.x))) ? other : origin; + Plot base = other.id.y < id.y || other.id.y.equals(id.y) && other.id.x < id.x ? other : origin; origin.origin = base; other.origin = base; origin = base; @@ -1723,10 +1678,34 @@ public class Plot { return settings.getMerged(); } + /** + * Set the raw merge data
+ * - Updates DB
+ * - Does not modify terrain
+ * Get if the plot is merged in a direction
+ * ----------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----------
+ * Note: Diagonal merging (4-7) must be done by merging the corresponding plots. + * @param merged + */ + public void setMerged(boolean[] merged) { + getSettings().setMerged(merged); + DBFunc.setMerged(this, merged); + connected_cache = null; + regions_cache = null; + if (origin != null) { + origin.origin = null; + origin = null; + } + } + /** * Get the set home location or 0,0,0 if no location is set
* - Does not take the default home location into account - * @see this#getPlotHome(Plot) * @see #getHome() * @return */ @@ -1750,7 +1729,7 @@ public class Plot { } public UUID guessOwner() { - if (this.owner != null) { + if (this.hasOwner()) { return this.owner; } if (!area.ALLOW_SIGNS) { @@ -1763,14 +1742,15 @@ public class Plot { if (lines == null) { return null; } - loop: for (int i = 4; i > 0; i--) { + loop: + for (int i = 4; i > 0; i--) { String caption = C.valueOf("OWNER_SIGN_LINE_" + i).s(); int index = caption.indexOf("%plr%"); if (index == -1) { continue; } String name = lines[i - 1].substring(index); - if (name.length() == 0) { + if (name.isEmpty()) { return null; } UUID owner = UUIDHandler.getUUID(name, null); @@ -1791,11 +1771,11 @@ public class Plot { this.owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); break; } - if (this.owner != null) { + if (this.hasOwner()) { this.create(); } return this.owner; - } catch (Exception e) { + } catch (IllegalArgumentException e) { return null; } } @@ -1803,11 +1783,9 @@ public class Plot { /** * Remove the south road section of a plot
* - Used when a plot is merged
- * @param plotworld - * @param plot */ public void removeRoadSouth() { - if ((area.TYPE != 0) && (area.TERRAIN > 1)) { + if (area.TYPE != 0 && area.TERRAIN > 1) { if (area.TERRAIN == 3) { return; } @@ -1821,10 +1799,9 @@ public class Plot { getManager().removeRoadSouth(area, this); } } - + /** * Auto merge a plot in a specific direction
- * @param plot The plot to merge * @param dir The direction to merge
* -1 = All directions
* 0 = north
@@ -1849,12 +1826,12 @@ public class Plot { ArrayDeque frontier = new ArrayDeque<>(connected); Plot current; boolean toReturn = false; - Set plots; while ((current = frontier.poll()) != null && max >= 0) { if (visited.contains(current)) { continue; } visited.add(current); + Set plots; if (max >= 0 && (dir == -1 || dir == 0) && !current.getMerged(0)) { Plot other = current.getRelative(0); if (other != null @@ -1910,13 +1887,12 @@ public class Plot { /** * Merge the plot settings
* - Used when a plot is merged
- * @param a * @param b */ public void mergeData(Plot b) { HashMap flags1 = getFlags(); HashMap flags2 = b.getFlags(); - if ((flags1.size() != 0 || flags2.size() != 0) && !flags1.equals(flags2)) { + if ((!flags1.isEmpty() || !flags2.isEmpty()) && !flags1.equals(flags2)) { boolean greater = flags1.size() > flags2.size(); if (greater) { flags1.putAll(flags2); @@ -1927,9 +1903,9 @@ public class Plot { setFlags(net); b.setFlags(net); } - if (getAlias().length() > 0) { + if (!getAlias().isEmpty()) { b.setAlias(getAlias()); - } else if (b.getAlias().length() > 0) { + } else if (!b.getAlias().isEmpty()) { setAlias(b.getAlias()); } for (UUID uuid : getTrusted()) { @@ -1944,7 +1920,7 @@ public class Plot { for (UUID uuid : b.getMembers()) { addMember(uuid); } - + for (UUID uuid : getDenied()) { b.addDenied(uuid); } @@ -1954,7 +1930,7 @@ public class Plot { } public void removeRoadSouthEast() { - if ((area.TYPE != 0) && (area.TERRAIN > 1)) { + if (area.TYPE != 0 && area.TERRAIN > 1) { if (area.TERRAIN == 3) { return; } @@ -1972,22 +1948,14 @@ public class Plot { public Plot getRelative(int x, int y) { return area.getPlotAbs(id.getRelative(x, y)); } - + public Plot getRelative(int direction) { return area.getPlotAbs(id.getRelative(direction)); } - /** - * @deprecated raw access is deprecated - */ - @Deprecated - private static HashSet connected_cache; - private static HashSet regions_cache; - /** * Get a set of plots connected (and including) this plot
* - This result is cached globally - * @see this#getConnectedPlots(Plot) * @return */ public HashSet getConnectedPlots() { @@ -2003,7 +1971,7 @@ public class Plot { return connected_cache; } regions_cache = null; - connected_cache = new HashSet(); + connected_cache = new HashSet<>(); ArrayDeque frontier = new ArrayDeque<>(); HashSet queuecache = new HashSet<>(); connected_cache.add(this); @@ -2119,7 +2087,6 @@ public class Plot { * This will combine each plot into effective rectangular regions
* - This result is cached globally
* - Useful for handling non rectangular shapes - * @see this#getRegions(Plot) * @return */ public HashSet getRegions() { @@ -2137,22 +2104,20 @@ public class Plot { HashSet plots = getConnectedPlots(); regions_cache = new HashSet<>(); HashSet visited = new HashSet<>(); - ArrayList ids; for (Plot current : plots) { if (visited.contains(current.getId())) { continue; } boolean merge = true; - boolean tmp = true; PlotId bot = new PlotId(current.getId().x, current.getId().y); PlotId top = new PlotId(current.getId().x, current.getId().y); while (merge) { merge = false; - ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, bot.y - 1), new PlotId(top.x, bot.y - 1)); - tmp = true; + ArrayList ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, bot.y - 1), new PlotId(top.x, bot.y - 1)); + boolean tmp = true; for (PlotId id : ids) { Plot plot = area.getPlotAbs(id); - if (plot == null || !plot.getMerged(2) || (visited.contains(plot.getId()))) { + if (plot == null || !plot.getMerged(2) || visited.contains(plot.getId())) { tmp = false; } } @@ -2164,7 +2129,7 @@ public class Plot { tmp = true; for (PlotId id : ids) { Plot plot = area.getPlotAbs(id); - if (plot == null || !plot.getMerged(3) || (visited.contains(plot.getId()))) { + if (plot == null || !plot.getMerged(3) || visited.contains(plot.getId())) { tmp = false; } } @@ -2176,7 +2141,7 @@ public class Plot { tmp = true; for (PlotId id : ids) { Plot plot = area.getPlotAbs(id); - if (plot == null || !plot.getMerged(0) || (visited.contains(plot.getId()))) { + if (plot == null || !plot.getMerged(0) || visited.contains(plot.getId())) { tmp = false; } } @@ -2188,7 +2153,7 @@ public class Plot { tmp = true; for (PlotId id : ids) { Plot plot = area.getPlotAbs(id); - if (plot == null || !plot.getMerged(1) || (visited.contains(plot.getId()))) { + if (plot == null || !plot.getMerged(1) || visited.contains(plot.getId())) { tmp = false; } } @@ -2218,7 +2183,7 @@ public class Plot { } for (int y = bot.y; y <= top.y; y++) { - Plot plot = area.getPlotAbs(new PlotId(top.x, y));; + Plot plot = area.getPlotAbs(new PlotId(top.x, y)); if (plot.getMerged(1)) { // east wedge Location toploc = plot.getExtendedTopAbs(); @@ -2238,7 +2203,6 @@ public class Plot { /** * Attempt to find the largest rectangular region in a plot (as plots can form non rectangular shapes) - * @param plot * @return */ public RegionWrapper getLargestRegion() { @@ -2270,8 +2234,6 @@ public class Plot { /** * Teleport a player to a plot and send them the teleport message. * @param player - * @param from - * @param plot * @return If the teleportation is allowed. */ public boolean teleportPlayer(final PlotPlayer player) { @@ -2284,7 +2246,7 @@ public class Plot { } else { location = getDefaultHome(); } - if ((Settings.TELEPORT_DELAY == 0) || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) { + if (Settings.TELEPORT_DELAY == 0 || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) { MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); player.teleport(location); return true; @@ -2316,7 +2278,6 @@ public class Plot { * Set a component for a plot to the provided blocks
* - E.g. floor, wall, border etc.
* - The available components depend on the generator being used
- * @param plot * @param component * @param blocks * @return @@ -2327,7 +2288,6 @@ public class Plot { /** * Expand the world border to include the provided plot (if applicable) - * @param plot */ public void updateWorldBorder() { if (owner == null) { @@ -2352,9 +2312,8 @@ public class Plot { /** * Merges 2 plots Removes the road inbetween
- Assumes plots are directly next to each other
- saves to DB * - * @param world * @param lesserPlot - * @param greaterPlot + * @param removeRoads */ public void mergePlot(Plot lesserPlot, final boolean removeRoads) { Plot greaterPlot = this; @@ -2411,7 +2370,6 @@ public class Plot { /** * Move a plot physically, as well as the corresponding settings. - * @param origin * @param destination * @param whenDone * @param allowSwap @@ -2431,7 +2389,7 @@ public class Plot { HashSet plots = this.getConnectedPlots(); for (Plot plot : plots) { Plot other = plot.getRelative(offset.x, offset.y); - if (other.owner != null) { + if (other.hasOwner()) { if (!allowSwap) { TaskManager.runTaskLater(whenDone, 1); return false; @@ -2451,7 +2409,7 @@ public class Plot { Runnable move = new Runnable() { @Override public void run() { - if (regions.size() == 0) { + if (regions.isEmpty()) { TaskManager.runTask(whenDone); return; } @@ -2468,7 +2426,7 @@ public class Plot { Runnable swap = new Runnable() { @Override public void run() { - if (regions.size() == 0) { + if (regions.isEmpty()) { TaskManager.runTask(whenDone); return; } @@ -2493,7 +2451,6 @@ public class Plot { /** * Copy a plot to a location, both physically and the settings - * @param origin * @param destination * @param whenDone * @return @@ -2511,7 +2468,7 @@ public class Plot { HashSet plots = this.getConnectedPlots(); for (Plot plot : plots) { Plot other = plot.getRelative(offset.x, offset.y); - if (other.owner != null) { + if (other.hasOwner()) { TaskManager.runTaskLater(whenDone, 1); return false; } @@ -2522,26 +2479,26 @@ public class Plot { for (Plot plot : plots) { Plot other = plot.getRelative(offset.x, offset.y); other.create(other.owner, false); - if ((plot.getFlags() != null) && (plot.getFlags().size() > 0)) { + if (plot.getFlags() != null && !plot.getFlags().isEmpty()) { other.getSettings().flags = plot.getFlags(); DBFunc.setFlags(other, plot.getFlags().values()); } if (plot.isMerged()) { other.setMerged(plot.getMerged()); } - if ((plot.members != null) && (plot.members.size() > 0)) { + if (plot.members != null && !plot.members.isEmpty()) { other.members = plot.members; for (final UUID member : other.members) { DBFunc.setMember(other, member); } } - if ((plot.trusted != null) && (plot.trusted.size() > 0)) { + if (plot.trusted != null && !plot.trusted.isEmpty()) { other.trusted = plot.trusted; for (final UUID trusted : other.trusted) { DBFunc.setTrusted(other, trusted); } } - if ((plot.denied != null) && (plot.denied.size() > 0)) { + if (plot.denied != null && !plot.denied.isEmpty()) { other.denied = plot.denied; for (final UUID denied : other.denied) { DBFunc.setDenied(other, denied); @@ -2554,7 +2511,7 @@ public class Plot { Runnable run = new Runnable() { @Override public void run() { - if (regions.size() == 0) { + if (regions.isEmpty()) { TaskManager.runTask(whenDone); return; } diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java b/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java index 98c653e8c..063af1a0e 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java +++ b/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java @@ -1,5 +1,13 @@ package com.intellectualcrafters.plot.object; +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.generator.HybridUtils; +import com.intellectualcrafters.plot.util.MathMan; +import com.intellectualcrafters.plot.util.TaskManager; + import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayDeque; @@ -9,31 +17,22 @@ import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.TaskManager; - public class PlotAnalysis { + + public static PlotAnalysis MODIFIERS = new PlotAnalysis(); + public static boolean running = false; public int changes; public int faces; public int data; public int air; public int variety; - public int changes_sd; public int faces_sd; public int data_sd; public int air_sd; public int variety_sd; - private int complexity; - public static PlotAnalysis MODIFIERS = new PlotAnalysis(); - public static PlotAnalysis getAnalysis(final Plot plot) { final Flag flag = FlagManager.getPlotFlagRaw(plot, "analysis"); if (flag != null) { @@ -44,46 +43,23 @@ public class PlotAnalysis { analysis.data = values.get(2); // 0 analysis.air = values.get(3); // 19100 analysis.variety = values.get(4); // 266 - + analysis.changes_sd = values.get(5); // 2104 analysis.faces_sd = values.get(6); // 89 analysis.data_sd = values.get(7); // 0 analysis.air_sd = values.get(8); // 18909 analysis.variety_sd = values.get(9); // 263 - + analysis.complexity = analysis.getComplexity(); return analysis; } return null; } - public List 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 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
* - Will be used to calibrate the threshold for plot clearing @@ -108,14 +84,14 @@ public class PlotAnalysis { PS.debug(" - $1Reducing " + plots.size() + " plots to those with sufficient data"); while (iter.hasNext()) { final Plot plot = iter.next(); - if ((plot.getSettings().ratings == null) || (plot.getSettings().ratings.size() == 0)) { + if ((plot.getSettings().ratings == null) || (plot.getSettings().ratings.isEmpty())) { iter.remove(); } else { plot.addRunning(); } } PS.debug(" - | Reduced to " + plots.size() + " plots"); - + if (plots.size() < 3) { PS.debug("Calibration cancelled due to insufficient comparison data, please try again later"); running = false; @@ -124,25 +100,25 @@ public class PlotAnalysis { } return; } - + PS.debug(" - $1Analyzing plot contents (this may take a while)"); - + final int[] changes = new int[plots.size()]; final int[] faces = new int[plots.size()]; final int[] data = new int[plots.size()]; final int[] air = new int[plots.size()]; final int[] variety = new int[plots.size()]; - + final int[] changes_sd = new int[plots.size()]; final int[] faces_sd = new int[plots.size()]; final int[] data_sd = new int[plots.size()]; final int[] air_sd = new int[plots.size()]; final int[] variety_sd = new int[plots.size()]; - + final int[] ratings = new int[plots.size()]; - + final AtomicInteger mi = new AtomicInteger(0); - + final Thread ratingAnalysis = new Thread(new Runnable() { @Override public void run() { @@ -155,7 +131,7 @@ public class PlotAnalysis { } }); ratingAnalysis.start(); - + final ArrayDeque plotsQueue = new ArrayDeque<>(plots); while (true) { final Plot queuePlot = plotsQueue.poll(); @@ -193,44 +169,44 @@ public class PlotAnalysis { e.printStackTrace(); } } - + PS.debug(" - $1Waiting on plot rating thread: " + ((mi.intValue() * 100) / plots.size()) + "%"); try { ratingAnalysis.join(); } catch (final InterruptedException e) { e.printStackTrace(); } - + PS.debug(" - $1Processing and grouping single plot analysis for bulk processing"); for (int i = 0; i < plots.size(); i++) { final Plot plot = plots.get(i); PS.debug(" | " + plot); final PlotAnalysis analysis = plot.getComplexity(); - + changes[i] = analysis.changes; faces[i] = analysis.faces; data[i] = analysis.data; air[i] = analysis.air; variety[i] = analysis.variety; - + changes_sd[i] = analysis.changes_sd; faces_sd[i] = analysis.faces_sd; data_sd[i] = analysis.data_sd; air_sd[i] = analysis.air_sd; variety_sd[i] = analysis.variety_sd; } - + PS.debug(" - $1Calculating rankings"); - + final int[] rank_ratings = rank(ratings); final int n = rank_ratings.length; - + final int optimal_index = (int) Math.round((1 - threshold) * (n - 1)); - + PS.debug(" - $1Calculating rank correlation: "); PS.debug(" - The analyzed plots which were processed and put into bulk data will be compared and correlated to the plot ranking"); PS.debug(" - The calculated correlation constant will then be used to calibrate the threshold for auto plot clearing"); - + final int[] rank_changes = rank(changes); final int[] sd_changes = getSD(rank_changes, rank_ratings); final int[] variance_changes = square(sd_changes); @@ -238,7 +214,7 @@ public class PlotAnalysis { final double factor_changes = getCC(n, sum_changes); PlotAnalysis.MODIFIERS.changes = factor_changes == 1 ? 0 : (int) ((factor_changes * 1000) / MathMan.getMean(changes)); PS.debug(" - | changes " + factor_changes); - + final int[] rank_faces = rank(faces); final int[] sd_faces = getSD(rank_faces, rank_ratings); final int[] variance_faces = square(sd_faces); @@ -246,7 +222,7 @@ public class PlotAnalysis { final double factor_faces = getCC(n, sum_faces); PlotAnalysis.MODIFIERS.faces = factor_faces == 1 ? 0 : (int) ((factor_faces * 1000) / MathMan.getMean(faces)); PS.debug(" - | faces " + factor_faces); - + final int[] rank_data = rank(data); final int[] sd_data = getSD(rank_data, rank_ratings); final int[] variance_data = square(sd_data); @@ -254,7 +230,7 @@ public class PlotAnalysis { final double factor_data = getCC(n, sum_data); PlotAnalysis.MODIFIERS.data = factor_data == 1 ? 0 : (int) ((factor_data * 1000) / MathMan.getMean(data)); PS.debug(" - | data " + factor_data); - + final int[] rank_air = rank(air); final int[] sd_air = getSD(rank_air, rank_ratings); final int[] variance_air = square(sd_air); @@ -262,7 +238,7 @@ public class PlotAnalysis { final double factor_air = getCC(n, sum_air); PlotAnalysis.MODIFIERS.air = factor_air == 1 ? 0 : (int) ((factor_air * 1000) / MathMan.getMean(air)); PS.debug(" - | air " + factor_air); - + final int[] rank_variety = rank(variety); final int[] sd_variety = getSD(rank_variety, rank_ratings); final int[] variance_variety = square(sd_variety); @@ -270,7 +246,7 @@ public class PlotAnalysis { final double factor_variety = getCC(n, sum_variety); PlotAnalysis.MODIFIERS.variety = factor_variety == 1 ? 0 : (int) ((factor_variety * 1000) / MathMan.getMean(variety)); PS.debug(" - | variety " + factor_variety); - + final int[] rank_changes_sd = rank(changes_sd); final int[] sd_changes_sd = getSD(rank_changes_sd, rank_ratings); final int[] variance_changes_sd = square(sd_changes_sd); @@ -278,7 +254,7 @@ public class PlotAnalysis { final double factor_changes_sd = getCC(n, sum_changes_sd); PlotAnalysis.MODIFIERS.changes_sd = factor_changes_sd == 1 ? 0 : (int) ((factor_changes_sd * 1000) / MathMan.getMean(changes_sd)); PS.debug(" - | changes_sd " + factor_changes_sd); - + final int[] rank_faces_sd = rank(faces_sd); final int[] sd_faces_sd = getSD(rank_faces_sd, rank_ratings); final int[] variance_faces_sd = square(sd_faces_sd); @@ -286,7 +262,7 @@ public class PlotAnalysis { final double factor_faces_sd = getCC(n, sum_faces_sd); PlotAnalysis.MODIFIERS.faces_sd = factor_faces_sd == 1 ? 0 : (int) ((factor_faces_sd * 1000) / MathMan.getMean(faces_sd)); PS.debug(" - | faces_sd " + factor_faces_sd); - + final int[] rank_data_sd = rank(data_sd); final int[] sd_data_sd = getSD(rank_data_sd, rank_ratings); final int[] variance_data_sd = square(sd_data_sd); @@ -294,7 +270,7 @@ public class PlotAnalysis { final double factor_data_sd = getCC(n, sum_data_sd); PlotAnalysis.MODIFIERS.data_sd = factor_data_sd == 1 ? 0 : (int) ((factor_data_sd * 1000) / MathMan.getMean(data_sd)); PS.debug(" - | data_sd " + factor_data_sd); - + final int[] rank_air_sd = rank(air_sd); final int[] sd_air_sd = getSD(rank_air_sd, rank_ratings); final int[] variance_air_sd = square(sd_air_sd); @@ -302,7 +278,7 @@ public class PlotAnalysis { final double factor_air_sd = getCC(n, sum_air_sd); PlotAnalysis.MODIFIERS.air_sd = factor_air_sd == 1 ? 0 : (int) ((factor_air_sd * 1000) / MathMan.getMean(air_sd)); PS.debug(" - | air_sd " + factor_air_sd); - + final int[] rank_variety_sd = rank(variety_sd); final int[] sd_variety_sd = getSD(rank_variety_sd, rank_ratings); final int[] variance_variety_sd = square(sd_variety_sd); @@ -310,9 +286,9 @@ public class PlotAnalysis { final double factor_variety_sd = getCC(n, sum_variety_sd); PlotAnalysis.MODIFIERS.variety_sd = factor_variety_sd == 1 ? 0 : (int) ((factor_variety_sd * 1000) / MathMan.getMean(variety_sd)); PS.debug(" - | variety_sd " + factor_variety_sd); - + final int[] complexity = new int[n]; - + PS.debug(" $1Calculating threshold"); int max = 0; int min = 0; @@ -358,7 +334,7 @@ public class PlotAnalysis { logln("Ratings: "); logln(rank_ratings); } - + // Save calibration PS.debug(" $1Saving calibration"); final YamlConfiguration config = PS.get().config; @@ -378,7 +354,7 @@ public class PlotAnalysis { } catch (final IOException e) { e.printStackTrace(); } - + PS.debug("$1Done!"); running = false; for (final Plot plot : plots) { @@ -397,7 +373,7 @@ public class PlotAnalysis { String result = ""; if (obj.getClass().isArray()) { String prefix = ""; - + for (int i = 0; i < Array.getLength(obj); i++) { result += prefix + log(Array.get(obj, i)); prefix = ","; @@ -520,7 +496,7 @@ public class PlotAnalysis { } } } - + final int[] ranks = new int[input.length]; for (int i = 0; i < input.length; i++) { final int index = input[i]; @@ -557,4 +533,25 @@ public class PlotAnalysis { placement *= SIZE; } } + + public List 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; + } } diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java b/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java index 3ea5efae8..2be6df560 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java +++ b/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java @@ -20,18 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.object; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; @@ -50,10 +38,31 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.area.QuadMap; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + /** * @author Jesse Boyd */ public abstract class PlotArea { + + public final String worldname; + public final String id; + public final PlotManager manager; + public final int worldhash; + private final PlotId min; + private final PlotId max; + private final ConcurrentHashMap plots = new ConcurrentHashMap<>(); + private final IndependentPlotGenerator generator; public int MAX_PLOT_MEMBERS = 128; public boolean AUTO_MERGE = false; public boolean ALLOW_SIGNS = true; @@ -80,33 +89,22 @@ public abstract class PlotArea { public int MAX_BUILD_HEIGHT = 256; public int MIN_BUILD_HEIGHT = 1; public PlotGamemode GAMEMODE = PlotGamemode.CREATIVE; - - public final String worldname; - public final String id; - public final PlotManager manager; - private final PlotId min; - private final PlotId max; + int hash; private RegionWrapper region; - /** * Please ignore */ @Deprecated private int compatibility_id; - private ConcurrentHashMap meta; - - private final ConcurrentHashMap plots = new ConcurrentHashMap<>(); - private QuadMap clusters; - private final IndependentPlotGenerator generator; public PlotArea(final String worldname, String id, IndependentPlotGenerator generator, PlotId min, PlotId max) { this.worldname = worldname; this.id = id; this.manager = generator != null ? generator.getNewPlotManager() : null; this.generator = generator; - if ((min == null) || (max == null)) { + if (min == null || max == null) { if (min != max) { throw new IllegalArgumentException("None of the ids can be null for this constructor"); } @@ -127,7 +125,7 @@ public abstract class PlotArea { public ConfigurationNode[] getSettingNodes() {return null;} }; } - + /** * Returns the region for this PlotArea * @return @@ -158,7 +156,7 @@ public abstract class PlotArea { public PlotId getMin() { return min == null ? new PlotId(Integer.MIN_VALUE, Integer.MIN_VALUE) : min; } - + /** * Returns the max PlotId * @return @@ -171,8 +169,6 @@ public abstract class PlotArea { return generator; } - public final int worldhash; - @Override public boolean equals(final Object obj) { if (this == obj) { @@ -187,7 +183,7 @@ public abstract class PlotArea { final PlotArea plotarea = (PlotArea) obj; return this.worldhash == plotarea.worldhash && this.worldname.equals(plotarea.worldname) && StringMan.isEqual(this.id, plotarea.id); } - + public Set getClusters() { return clusters == null ? new HashSet() : clusters.getAll(); } @@ -238,7 +234,7 @@ public abstract class PlotArea { SCHEMATIC_FILE = config.getString("schematic.file"); SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim"); SCHEMATICS = config.getStringList("schematic.schematics"); - USE_ECONOMY = config.getBoolean("economy.use") && (EconHandler.manager != null); + USE_ECONOMY = config.getBoolean("economy.use") && EconHandler.manager != null; PLOT_PRICE = config.getDouble("economy.prices.claim"); MERGE_PRICE = config.getDouble("economy.prices.merge"); SELL_PRICE = config.getDouble("economy.prices.sell"); @@ -246,7 +242,7 @@ public abstract class PlotArea { WORLD_BORDER = config.getBoolean("world.border"); MAX_BUILD_HEIGHT = config.getInt("world.max_height"); MIN_BUILD_HEIGHT = config.getInt("min.max_height"); - + switch (config.getString("world.gamemode").toLowerCase()) { case "survival": case "s": @@ -271,10 +267,10 @@ public abstract class PlotArea { PS.debug("&cInvalid gamemode set for: " + worldname); break; } - + HOME_ALLOW_NONMEMBER = config.getBoolean("home.allow-nonmembers"); final String homeDefault = config.getString("home.default"); - if (homeDefault.equalsIgnoreCase("side")) { + if ("side".equalsIgnoreCase(homeDefault)) { DEFAULT_HOME = null; } else if (StringMan.isEqualIgnoreCaseToAny(homeDefault, "center", "middle")) { DEFAULT_HOME = new PlotLoc(Integer.MAX_VALUE, Integer.MAX_VALUE); @@ -282,20 +278,20 @@ public abstract class PlotArea { try { final String[] split = homeDefault.split(","); DEFAULT_HOME = new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1])); - } catch (final Exception e) { + } catch (NumberFormatException e) { DEFAULT_HOME = null; } } - + List flags = config.getStringList("flags.default"); - if ((flags == null) || (flags.size() == 0)) { + if (flags == null || flags.isEmpty()) { flags = config.getStringList("flags"); - if ((flags == null) || (flags.size() == 0)) { + if (flags == null || flags.isEmpty()) { flags = new ArrayList<>(); final ConfigurationSection section = config.getConfigurationSection("flags"); final Set keys = section.getKeys(false); for (final String key : keys) { - if (!key.equals("default")) { + if (!"default".equals(key)) { flags.add(key + ";" + section.get(key)); } } @@ -347,8 +343,8 @@ public abstract class PlotArea { options.put("world.max_height", MAX_BUILD_HEIGHT); options.put("world.min_height", MIN_BUILD_HEIGHT); options.put("world.gamemode", GAMEMODE.name().toLowerCase()); - - if ((TYPE != 0)) { + + if (TYPE != 0) { options.put("generator.terrain", TERRAIN); options.put("generator.type", TYPE); } @@ -359,9 +355,9 @@ public abstract class PlotArea { for (final ConfigurationNode setting : settings) { options.put(setting.getConstant(), setting.getValue()); } - for (final String option : options.keySet()) { - if (!config.contains(option)) { - config.set(option, options.get(option)); + for (final Entry stringObjectEntry : options.entrySet()) { + if (!config.contains(stringObjectEntry.getKey())) { + config.set(stringObjectEntry.getKey(), stringObjectEntry.getValue()); } } if (!config.contains("flags")) { @@ -371,11 +367,9 @@ public abstract class PlotArea { @Override public String toString() { - return (compatibility_id == 1 || id == null) ? worldname : worldname + ";" + id; + return compatibility_id == 1 || id == null ? worldname : worldname + ";" + id; } - int hash; - @Override public int hashCode() { if (hash != 0) { @@ -559,7 +553,7 @@ public abstract class PlotArea { */ public void setMeta(final String key, final Object value) { if (meta == null) { - meta = new ConcurrentHashMap(); + meta = new ConcurrentHashMap<>(); } meta.put(key, value); } @@ -716,7 +710,7 @@ public abstract class PlotArea { } public boolean mergePlots(final PlotPlayer player, final ArrayList plotIds) { - if ((EconHandler.manager != null) && USE_ECONOMY) { + if (EconHandler.manager != null && USE_ECONOMY) { final double cost = plotIds.size() * MERGE_PRICE; if (cost > 0d) { if (EconHandler.manager.getMoney(player) < cost) { @@ -746,10 +740,10 @@ public abstract class PlotArea { if (!result) { return false; } - - final HashSet trusted = new HashSet(); - final HashSet members = new HashSet(); - final HashSet denied = new HashSet(); + + final HashSet trusted = new HashSet<>(); + final HashSet members = new HashSet<>(); + final HashSet denied = new HashSet<>(); manager.startPlotMerge(this, plotIds); for (int x = pos1.x; x <= pos2.x; x++) { @@ -767,7 +761,6 @@ public abstract class PlotArea { members.removeAll(trusted); denied.removeAll(trusted); denied.removeAll(members); - Plot plot2; for (int x = pos1.x; x <= pos2.x; x++) { for (int y = pos1.y; y <= pos2.y; y++) { final boolean lx = x < pos2.x; @@ -777,6 +770,7 @@ public abstract class PlotArea { plot.setTrusted(trusted); plot.setMembers(members); plot.setDenied(denied); + Plot plot2; if (lx) { if (ly) { if (!plot.getMerged(1) || !plot.getMerged(2)) { @@ -810,20 +804,20 @@ public abstract class PlotArea { * @return */ public HashSet 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 result = new HashSet<>(); if (size < 16 || size < getPlotCount()) { for (final PlotId pid : MainUtil.getPlotSelectionIds(pos1, pos2)) { final Plot plot = getPlotAbs(pid); if (plot.hasOwner()) { - if ((plot.getId().x > pos1.x) || (plot.getId().y > pos1.y) || (plot.getId().x < pos2.x) || (plot.getId().y < pos2.y)) { + if (plot.getId().x > pos1.x || plot.getId().y > pos1.y || plot.getId().x < pos2.x || plot.getId().y < pos2.y) { result.add(plot); } } } } else { for (final Plot plot : getPlots()) { - if ((plot.getId().x > pos1.x) || (plot.getId().y > pos1.y) || (plot.getId().x < pos2.x) || (plot.getId().y < pos2.y)) { + if (plot.getId().x > pos1.x || plot.getId().y > pos1.y || plot.getId().x < pos2.x || plot.getId().y < pos2.y) { result.add(plot); } } diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java b/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java index a6b182173..eac5c4185 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java +++ b/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java @@ -5,7 +5,6 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import java.util.UUID; @@ -41,9 +40,8 @@ public class PlotHandler { return false; } HashSet connected = plot.getConnectedPlots(); - Iterator iter = connected.iterator(); - while (iter.hasNext()) { - if (uuid.equals(iter.next().owner)) { + for (Plot aConnected : connected) { + if (aConnected.isOwner(uuid)) { return true; } } @@ -58,7 +56,7 @@ public class PlotHandler { return UUIDHandler.getPlayer(plot.owner) != null; } for (Plot current : plot.getConnectedPlots()) { - if (current.owner != null && UUIDHandler.getPlayer(current.owner) != null) { + if (current.hasOwner() && UUIDHandler.getPlayer(current.owner) != null) { return true; } } @@ -92,7 +90,7 @@ public class PlotHandler { } final HashSet owners = getOwners(plot1); owners.retainAll(getOwners(plot2)); - return owners.size() > 0; + return !owners.isEmpty(); } public static boolean isAdded(final Plot plot, final UUID uuid) { diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotId.java b/src/main/java/com/intellectualcrafters/plot/object/PlotId.java index e162a052c..507a168da 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotId.java +++ b/src/main/java/com/intellectualcrafters/plot/object/PlotId.java @@ -29,6 +29,7 @@ public class PlotId { * y value */ public Integer y; + private int hash; /** * PlotId class (PlotId x,y values do not correspond to Block locations) @@ -44,7 +45,7 @@ public class PlotId { /** * Get a Plot Id based on a string * - * @param string to create id from + * @param string to create type from * * @return null if the string is invalid */ @@ -65,7 +66,11 @@ public class PlotId { } return new PlotId(x, y); } - + + public static PlotId unpair(int hash) { + return new PlotId(hash >> 16, hash & 0xFFFF); + } + public PlotId getRelative(final int direction) { switch (direction) { case 0: @@ -104,12 +109,6 @@ public class PlotId { return x + ";" + y; } - public static PlotId unpair(int hash) { - return new PlotId(hash >> 16, hash & 0xFFFF); - } - - private int hash; - public void recalculateHash() { hash = 0; hashCode(); diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java b/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java index 1508d6cae..5511927ea 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java +++ b/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java @@ -20,16 +20,16 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.object; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.comment.PlotComment; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.comment.PlotComment; - /** * Generic settings class * - Does not keep a reference to a parent class @@ -98,7 +98,7 @@ public class PlotSettings { * Returns true if the plot is merged (i.e. if it's a mega plot) */ public boolean isMerged() { - return (merged[0] || merged[1] || merged[2] || merged[3]); + return merged[0] || merged[1] || merged[2] || merged[3]; } public boolean[] getMerged() { diff --git a/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java b/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java index 07d198844..0cef07b34 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java +++ b/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java @@ -51,12 +51,12 @@ public class SetupObject { public String id; /** - * Minimum plot id (may be null) + * Minimum plot type (may be null) */ public PlotId min; /** - * Max plot id (may be null) + * Max plot type (may be null) */ public PlotId max; diff --git a/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java b/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java index 5d76a799e..662b18c4d 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java +++ b/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java @@ -1,11 +1,5 @@ package com.intellectualcrafters.plot.util; -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.ConsolePlayer; @@ -15,19 +9,24 @@ import com.intellectualcrafters.plot.object.RegionWrapper; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + public abstract class ChunkManager { public static ChunkManager manager = null; - + private static RunnableVal> CURRENT_FORCE_CHUNK; + private static RunnableVal> CURRENT_ADD_CHUNK; + public static ChunkLoc getChunkChunk(final Location loc) { final int x = loc.getX() >> 9; final int z = loc.getZ() >> 9; return new ChunkLoc(x, z); } - private static RunnableVal> CURRENT_FORCE_CHUNK; - private static RunnableVal> CURRENT_ADD_CHUNK; - public static void setChunkInPlotArea(RunnableVal> force, RunnableVal> add, String world, ChunkLoc loc) { if (PS.get().isAugmented(world)) { ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); @@ -131,7 +130,7 @@ public abstract class ChunkManager { @Override public void run() { final long start = System.currentTimeMillis(); - while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < allocate)) { + while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < allocate)) { final ChunkLoc chunk = chunks.remove(0); task.value = new int[7]; task.value[0] = chunk.x; @@ -158,7 +157,7 @@ public abstract class ChunkManager { } task.run(); } - if (chunks.size() != 0) { + if (!chunks.isEmpty()) { TaskManager.runTaskLater(this, 1); } else { TaskManager.runTask(whenDone); diff --git a/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java b/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java index be930da5e..133a05c73 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java +++ b/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java @@ -1,9 +1,5 @@ package com.intellectualcrafters.plot.util; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.UUID; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.flag.Flag; @@ -19,6 +15,10 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.Rating; import com.plotsquared.listener.PlayerBlockEventType; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.UUID; + public abstract class EventUtil { public static EventUtil manager = null; @@ -64,18 +64,16 @@ public abstract class EventUtil { return true; } switch (type) { - case TELEPORT_OBJECT: { + case TELEPORT_OBJECT: return false; - } case EAT: - case READ: { + case READ: return true; - } - case BREAK_BLOCK: { + case BREAK_BLOCK: if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } final Flag use = FlagManager.getPlotFlagRaw(plot, "use"); @@ -96,7 +94,6 @@ public abstract class EventUtil { return true; } return !(!notifyPerms || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_USE.s() + "/" + C.FLAG_BREAK.s())); - } case BREAK_HANGING: if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); @@ -143,12 +140,12 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } @@ -160,12 +157,12 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED.s(), notifyPerms); } final Flag flag = FlagManager.getPlotFlagRaw(plot, "place"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER.s(), notifyPerms)) { return true; } @@ -177,7 +174,7 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), false); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), false); } if (FlagManager.isPlotFlagTrue(plot, "device-interact")) { @@ -185,10 +182,7 @@ public abstract class EventUtil { } final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), false)) { - return true; - } + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { // TODO: fix the commented dead code return true; //!(!false || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_USE.s() + "/" + C.FLAG_DEVICE_INTERACT.s())); } @@ -198,7 +192,7 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } if (FlagManager.isPlotFlagTrue(plot, "hanging-interact")) { @@ -206,7 +200,7 @@ public abstract class EventUtil { } final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } @@ -218,7 +212,7 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } if (FlagManager.isPlotFlagTrue(plot, "misc-interact")) { @@ -226,7 +220,7 @@ public abstract class EventUtil { } final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } @@ -238,7 +232,7 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } if (FlagManager.isPlotFlagTrue(plot, "vehicle-use")) { @@ -246,7 +240,7 @@ public abstract class EventUtil { } final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } @@ -258,7 +252,7 @@ public abstract class EventUtil { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } @@ -267,7 +261,7 @@ public abstract class EventUtil { } final Flag flag = FlagManager.getPlotFlagRaw(plot, "place"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } @@ -275,7 +269,7 @@ public abstract class EventUtil { } return true; } - case PLACE_HANGING: { + case PLACE_HANGING: // if (plot == null) { // return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); // } @@ -292,12 +286,11 @@ public abstract class EventUtil { // return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); // } return true; - } case PLACE_MISC: { if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } @@ -306,7 +299,7 @@ public abstract class EventUtil { } final Flag flag = FlagManager.getPlotFlagRaw(plot, "place"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } @@ -314,27 +307,26 @@ public abstract class EventUtil { } return true; } - case PLACE_VEHICLE: { + case PLACE_VEHICLE: if (plot == null) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); } - if (plot.owner == null) { + if (!plot.hasOwner()) { return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); } - + if (FlagManager.isPlotFlagTrue(plot, "vehicle-place")) { return true; } final Flag flag = FlagManager.getPlotFlagRaw(plot, "place"); final HashSet value = flag == null ? null : (HashSet) flag.getValue(); - if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { + if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) { return true; } return !(!notifyPerms || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_VEHICLE_PLACE.s() + "/" + C.FLAG_PLACE.s())); } return true; - } default: break; } diff --git a/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java b/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java index 7a9c30f8e..882747ea6 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java +++ b/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java @@ -78,7 +78,7 @@ public class ExpireManager { updateExpired(area); return; } - if ((plots.size() == 0)) { + if ((plots.isEmpty())) { if (updateExpired(area)) { PS.debug("$2[&5Expire&dManager$2] $4Re-evaluating expired plots for: " + area); return; @@ -168,7 +168,7 @@ public class ExpireManager { final String name = UUIDHandler.getName(uuid); if (name != null) { long last; - if (dates.contains(uuid)) { + if (dates.containsKey(uuid)) { last = dates.get(uuid); } else { OfflinePlotPlayer opp; @@ -207,9 +207,7 @@ public class ExpireManager { public static List getOldPlots(final PlotArea area) { final ArrayList plots = new ArrayList<>(area.getPlots()); final List toRemove = new ArrayList<>(); - final Iterator iter = plots.iterator(); - while (iter.hasNext()) { - final Plot plot = iter.next(); + for (Plot plot : plots) { final Flag keepFlag = FlagManager.getPlotFlagRaw(plot, "keep"); if ((keepFlag != null) && (Boolean) keepFlag.getValue()) { continue; diff --git a/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java b/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java index cd33304fc..2fa5e0fad 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java +++ b/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java @@ -80,9 +80,9 @@ public class MainUtil { for (int i = 0; i < 16; i++) { final int i4 = i << 4; for (int j = 0; j < 4096; j++) { - final int y = (i4) + (j >> 8); - final int a = (j - ((y & 0xF) << 8)); - final int z1 = (a >> 4); + final int y = i4 + (j >> 8); + final int a = j - ((y & 0xF) << 8); + final int z1 = a >> 4; final int x1 = a - (z1 << 4); x_loc[i][j] = (short) x1; y_loc[i][j] = (short) y; @@ -97,7 +97,7 @@ public class MainUtil { for (int z = 0; z < 16; z++) { for (int y = 0; y < 256; y++) { final short i = (short) (y >> 4); - final short j = (short) (((y & 0xF) << 8) | (z << 4) | x); + final short j = (short) ((y & 0xF) << 8 | z << 4 | x); CACHE_I[y][x][z] = i; CACHE_J[y][x][z] = j; } @@ -120,8 +120,8 @@ public class MainUtil { return ((array[0] ? 1 : 0) << 3) + ((array[1] ? 1 : 0) << 2) + ((array[2] ? 1 : 0) << 1) + (array[3] ? 1 : 0); } int n = 0; - for (int j = 0; j < array.length; ++j) { - n = (n << 1) + (array[j] ? 1 : 0); + for (boolean anArray : array) { + n = (n << 1) + (anArray ? 1 : 0); } return n; } @@ -197,7 +197,7 @@ public class MainUtil { /** * Fuzzy plot search with spaces separating terms
- * - Terms: id, alias, world, owner, trusted, member + * - Terms: type, alias, world, owner, trusted, member * @param search * @return */ @@ -236,7 +236,7 @@ public class MainUtil { for (final Plot plot : PS.get().getPlots()) { int count = 0; - if (uuids.size() > 0) { + if (!uuids.isEmpty()) { for (final UUID uuid : uuids) { if (plot.isOwner(uuid)) { count += 2; @@ -250,20 +250,20 @@ public class MainUtil { count++; } } - if ((area != null) && plot.getArea().equals(area)) { + if (area != null && plot.getArea().equals(area)) { count++; } - if ((alias != null) && alias.equals(plot.getAlias())) { + if (alias != null && alias.equals(plot.getAlias())) { count += 2; } if (count != 0) { plotList.get(count - 1).add(plot); } } - - final List plots = new ArrayList(); + + final List plots = new ArrayList<>(); for (int i = plotList.size() - 1; i >= 0; i--) { - if (plotList.get(i).size() > 0) { + if (!plotList.get(i).isEmpty()) { plots.addAll(plotList.get(i)); } } @@ -287,8 +287,7 @@ public class MainUtil { } return player.getLocation().getPlotAbs(); } - PlotArea area = null; - PlotId id = null; + PlotArea area; if (player != null) { area = player.getApplicablePlotArea(); } @@ -296,6 +295,7 @@ public class MainUtil { area = ConsolePlayer.getConsole().getApplicablePlotArea(); } final String[] split = arg.split(";|,"); + PlotId id; if (split.length == 4) { area = PS.get().getPlotAreaByString(split[0] + ";" + split[1]); id = PlotId.fromString(split[2] + ";" + split[3]); @@ -314,7 +314,7 @@ public class MainUtil { } else { for (final Plot p : area.getPlots()) { final String name = p.getAlias(); - if ((name.length() != 0) && StringMan.isEqualIgnoreCase(name, arg)) { + if (!name.isEmpty() && StringMan.isEqualIgnoreCase(name, arg)) { return p; } } @@ -325,12 +325,10 @@ public class MainUtil { } } if (id == null) { - if (id == null) { - if (message) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); - } - return null; + if (message) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); } + return null; } if (area == null) { if (message) { @@ -490,7 +488,7 @@ public class MainUtil { * @return */ public static boolean sendMessage(final PlotPlayer plr, final String msg, final boolean prefix) { - if ((msg.length() > 0) && !msg.equals("")) { + if (!msg.isEmpty()) { if (plr == null) { ConsolePlayer.getConsole().sendMessage((prefix ? C.PREFIX.s() : "") + msg); } else { @@ -521,7 +519,7 @@ public class MainUtil { * @return boolean success */ public static boolean sendMessage(final PlotPlayer plr, final C c, final Object... args) { - if (c.s().length() == 0) { + if (c.s().isEmpty()) { return true; } TaskManager.runTaskAsync(new Runnable() { @@ -529,10 +527,10 @@ public class MainUtil { public void run() { String msg = c.s(); if (args.length != 0) { - msg = c.format(c, args); + msg = C.format(c, args); } if (plr != null) { - plr.sendMessage((c.usePrefix() ? C.PREFIX.s() + msg : msg)); + plr.sendMessage(c.usePrefix() ? C.PREFIX.s() + msg : msg); } else { ConsolePlayer.getConsole().sendMessage((c.usePrefix() ? C.PREFIX.s() : "") + msg); } @@ -556,19 +554,19 @@ public class MainUtil { } else { rating = DBFunc.getRatings(plot); } - if ((rating == null) || (rating.size() == 0)) { + if (rating == null || rating.isEmpty()) { return 0; } double val = 0; int size = 0; for (final Entry entry : rating.entrySet()) { int current = entry.getValue(); - if ((Settings.RATING_CATEGORIES == null) || (Settings.RATING_CATEGORIES.size() == 0)) { + if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) { val += current; size++; } else { for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) { - val += (current % 10) - 1; + val += current % 10 - 1; current /= 10; size++; } @@ -597,16 +595,16 @@ public class MainUtil { size = Math.max(1, Settings.RATING_CATEGORIES.size()); } final double[] ratings = new double[size]; - if ((rating == null) || (rating.size() == 0)) { + if (rating == null || rating.isEmpty()) { return ratings; } for (final Entry entry : rating.entrySet()) { int current = entry.getValue(); - if ((Settings.RATING_CATEGORIES == null) || (Settings.RATING_CATEGORIES.size() == 0)) { + if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) { ratings[0] += current; } else { for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) { - ratings[i] += (current % 10) - 1; + ratings[i] += current % 10 - 1; current /= 10; } } @@ -619,7 +617,7 @@ public class MainUtil { /** * Format a string with plot information:
- * %id%, %alias%, %num%, %desc%, %biome%, %owner%, %members%, %trusted%, %helpers%, %denied%, %flags%, %build%, %desc%, %rating% + * %type%, %alias%, %num%, %desc%, %biome%, %owner%, %members%, %trusted%, %helpers%, %denied%, %flags%, %build%, %desc%, %rating% * @param info * @param plot * @param player @@ -628,7 +626,7 @@ public class MainUtil { */ public static void format(String info, final Plot plot, final PlotPlayer player, final boolean full, final RunnableVal whenDone) { final int num = plot.getConnectedPlots().size(); - final String alias = plot.getAlias().length() > 0 ? plot.getAlias() : C.NONE.s(); + final String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : C.NONE.s(); final Location bot = plot.getCorners()[0]; final String biome = WorldUtil.IMP.getBiome(plot.getArea().worldname, bot.getX(), bot.getZ()); final String trusted = getPlayerList(plot.getTrusted()); @@ -640,7 +638,8 @@ public class MainUtil { final String flags = StringMan.replaceFromMap( "$2" - + (StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "").length() > 0 ? StringMan.join(FlagManager.getPlotFlags( + + (!StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "").isEmpty() ? + StringMan.join(FlagManager.getPlotFlags( plot.getArea(), plot.getSettings(), true) .values(), "$1, $2") : C.NONE.s()), C.replacements); @@ -655,7 +654,7 @@ public class MainUtil { info = info.replaceAll("%biome%", biome); info = info.replaceAll("%owner%", owner); info = info.replaceAll("%members%", members); - info = info.replaceAll("%player%", player != null ? player.getName() : C.NONE.s()); + info = info.replaceAll("%player%", player.getName()); info = info.replaceAll("%trusted%", trusted); info = info.replaceAll("%helpers%", members); info = info.replaceAll("%denied%", denied); @@ -668,11 +667,11 @@ public class MainUtil { @Override public void run() { int max = 10; - if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() > 0)) { + if (Settings.RATING_CATEGORIES != null && !Settings.RATING_CATEGORIES.isEmpty()) { max = 8; } String info; - if (full && (Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() > 1)) { + if (full && Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 1) { String rating = ""; String prefix = ""; final double[] ratings = MainUtil.getAverageRatings(plot); @@ -706,7 +705,7 @@ public class MainUtil { final String c = C.PLOT_USER_LIST.s(); final StringBuilder list = new StringBuilder(); for (int x = 0; x < l.size(); x++) { - if ((x + 1) == l.size()) { + if (x + 1 == l.size()) { list.append(c.replace("%user%", getName(l.get(x))).replace(",", "")); } else { list.append(c.replace("%user%", getName(l.get(x)))); diff --git a/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java b/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java index 5993469e5..9c67b4f96 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java +++ b/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java @@ -36,13 +36,6 @@ import java.util.List; public class ReflectionUtils { private static String version; - - public ReflectionUtils(final String version) { - ReflectionUtils.version = version; - preClassB += "." + version; - preClassM += "." + version; - } - /** * prefix of bukkit classes */ @@ -51,6 +44,12 @@ public class ReflectionUtils { * prefix of minecraft classes */ private static String preClassM = "net.minecraft.server"; + + public ReflectionUtils(final String version) { + ReflectionUtils.version = version; + preClassB += "." + version; + preClassM += "." + version; + } public static Class getNmsClass(final String name) { final String className = "net.minecraft.server." + version + "." + name; @@ -252,7 +251,7 @@ public class ReflectionUtils { * * @throws RuntimeException if method not found */ - public RefMethod getMethod(final String name, final Object... types) throws NoSuchMethodException { + public RefMethod getMethod(final String name, final Object... types) { try { final Class[] classes = new Class[types.length]; int i = 0; diff --git a/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java b/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java index adbaf34c3..70d4e8afc 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java +++ b/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java @@ -11,6 +11,7 @@ import com.intellectualcrafters.jnbt.ShortTag; import com.intellectualcrafters.jnbt.StringTag; import com.intellectualcrafters.jnbt.Tag; import com.intellectualcrafters.json.JSONArray; +import com.intellectualcrafters.json.JSONException; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.generator.ClassicPlotWorld; @@ -26,6 +27,7 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -61,7 +63,7 @@ public abstract class SchematicHandler { if (exportAll) { return false; } - if (collection.size() == 0) { + if (collection.isEmpty()) { return false; } exportAll = true; @@ -69,7 +71,7 @@ public abstract class SchematicHandler { TaskManager.runTask(new Runnable() { @Override public void run() { - if (plots.size() == 0) { + if (plots.isEmpty()) { exportAll = false; TaskManager.runTask(ifSuccess); return; @@ -162,7 +164,7 @@ public abstract class SchematicHandler { TaskManager.runTask(whenDone); return; } - // block id and data arrays + // block type and data arrays final short[] ids = schematic.ids; final byte[] datas = schematic.datas; // Calculate the optimal height to paste the schematic at @@ -198,7 +200,7 @@ public abstract class SchematicHandler { @Override public void run() { int count = 0; - while ((chunks.size() > 0) && (count < 256)) { + while (!chunks.isEmpty() && count < 256) { count++; final ChunkLoc chunk = chunks.remove(0); final int x = chunk.x; @@ -220,8 +222,7 @@ public abstract class SchematicHandler { zzt = p2z; } // Paste schematic here - int id; - + for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { final int yy = y_offset + ry; if (yy > 255) { @@ -235,9 +236,9 @@ public abstract class SchematicHandler { final int xx = p1x + rx; final int zz = p1z + rz; - - id = ids[i]; - + + int id = ids[i]; + switch (id) { case 0: case 2: @@ -305,20 +306,18 @@ public abstract class SchematicHandler { case 189: case 190: case 191: - case 192: { + case 192: SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, id); break; - } - default: { + default: SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, new PlotBlock((short) id, datas[i])); break; - } } } } } } - if (chunks.size() != 0) { + if (!chunks.isEmpty()) { final Runnable task = this; // Run when the queue is free SetQueue.IMP.addTask(new Runnable() { @@ -367,7 +366,7 @@ public abstract class SchematicHandler { final int sy = MainUtil.getHeighestBlock(plot.getArea().worldname, l1.getX() + 1, l1.getZ() + 1); final Dimension demensions = schematic.getSchematicDimension(); final int HEIGHT = demensions.getY(); - if ((HEIGHT < 255)) { + if (HEIGHT < 255) { l1 = l1.add(0, sy - 1, 0); } final int X = l1.getX() + x_offset; @@ -459,12 +458,10 @@ public abstract class SchematicHandler { * @return schematic if found, else null */ public Schematic getSchematic(final String name) { - { - final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics"); - if (!parent.exists()) { - if (!parent.mkdir()) { - throw new RuntimeException("Could not create schematic parent directory"); - } + final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics"); + if (!parent.exists()) { + if (!parent.mkdir()) { + throw new RuntimeException("Could not create schematic parent directory"); } } final File file = new File(PS.get().IMP.getDirectory() + File.separator + "schematics" + File.separator + name + (name.endsWith(".schematic") ? "" : ".schematic")); @@ -484,7 +481,7 @@ public abstract class SchematicHandler { } try { return getSchematic(new FileInputStream(file)); - } catch (final Exception e) { + } catch (FileNotFoundException e) { e.printStackTrace(); } return null; @@ -495,7 +492,7 @@ public abstract class SchematicHandler { final ReadableByteChannel rbc = Channels.newChannel(url.openStream()); final InputStream is = Channels.newInputStream(rbc); return getSchematic(is); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); } return null; @@ -511,7 +508,7 @@ public abstract class SchematicHandler { is.close(); stream.close(); return getSchematic(tag); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); PS.debug(is.toString() + " | " + is.getClass().getCanonicalName() + " is not in GZIP format : " + e.getMessage()); } @@ -538,7 +535,7 @@ public abstract class SchematicHandler { schematics.add(schematic); } return Lists.reverse(schematics); - } catch (final Exception e) { + } catch (JSONException | IOException e) { e.printStackTrace(); PS.debug("ERROR PARSING: " + rawJSON); } @@ -559,17 +556,17 @@ public abstract class SchematicHandler { } else { website = Settings.WEB_URL + "save.php?" + uuid; } - final String charset = "UTF-8"; - final String param = "value"; final String boundary = Long.toHexString(System.currentTimeMillis()); - final String CRLF = "\r\n"; final URLConnection con = new URL(website).openConnection(); con.setDoOutput(true); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); - try (OutputStream output = con.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true)) { + try (OutputStream output = con.getOutputStream(); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { + final String CRLF = "\r\n"; writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); - writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); + writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF); + final String param = "value"; writer.append(CRLF).append(param).append(CRLF).flush(); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + file + ".schematic" + "\"").append(CRLF); @@ -585,7 +582,6 @@ public abstract class SchematicHandler { writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); nos.close(); - output.close(); } try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) { final char[] buffer = new char[256]; @@ -600,7 +596,7 @@ public abstract class SchematicHandler { if (!result.toString().equals("The file plot.schematic has been uploaded.")) { PS.debug(result); } - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); } final int responseCode = ((HttpURLConnection) con).getResponseCode(); @@ -608,7 +604,7 @@ public abstract class SchematicHandler { return null; } return new URL(Settings.WEB_URL + "?key=" + uuid + "&ip=" + Settings.WEB_IP); - } catch (final Exception e) { + } catch (IOException e) { e.printStackTrace(); } return null; @@ -630,11 +626,9 @@ public abstract class SchematicHandler { try { final File tmp = new File(path); tmp.getParentFile().mkdirs(); - final OutputStream stream = new FileOutputStream(path); - final NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream)); - output.writeTag(tag); - output.close(); - stream.close(); + try (OutputStream stream = new FileOutputStream(path); NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream))) { + output.writeTag(tag); + } } catch (final IOException e) { e.printStackTrace(); return false; @@ -675,6 +669,36 @@ public abstract class SchematicHandler { getCompoundTag(plot.getArea().worldname, plot.getRegions(), whenDone); } + /** + * Schematic Dimensions + * + + */ + public static class Dimension { + + private final int x; + private final int y; + private final int z; + + public Dimension(final int x, final int y, final int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getZ() { + return z; + } + } + /** * Schematic Class * @@ -693,7 +717,7 @@ public abstract class SchematicHandler { datas = b; schematicDimension = d; } - + /** * Add an item to the schematic * @param item @@ -704,7 +728,7 @@ public abstract class SchematicHandler { } items.add(item); } - + /** * Get any items associated with this schematic * @return @@ -712,7 +736,7 @@ public abstract class SchematicHandler { public HashSet getItems() { return items; } - + /** * Get the schematic dimensions * @return @@ -720,15 +744,15 @@ public abstract class SchematicHandler { public Dimension getSchematicDimension() { return schematicDimension; } - + /** - * Get the block id array + * Get the block type array * @return */ public short[] getIds() { return ids; } - + /** * Get the block data array * @return @@ -741,24 +765,24 @@ public abstract class SchematicHandler { int x1 = region.minX; int x2 = region.maxX; - + int z1 = region.minZ; int z2 = region.maxZ; - + int y1 = region.minY; int y2 = Math.min(region.maxY, 255); - + int width = x2 - x1 + 1; int length = z2 - z1 + 1; int height = y2 - y1 + 1; - + short[] ids2 = new short[width * length * height]; byte[] datas2 = new byte[width * length * height]; int dx = schematicDimension.getX(); int dy = schematicDimension.getY(); int dz = schematicDimension.getZ(); - + for (int y = y1; y <= y2; y++) { int yy = y >= 0 ? (y < dy ? y : y - dy) : y + dy; int i1 = yy * dx * dz; @@ -778,7 +802,7 @@ public abstract class SchematicHandler { } return new Schematic(ids2, datas2, new Dimension(width, height, length)); } - + public void save(final File file) { byte[] ids2 = new byte[ids.length]; for (int i = 0; i < ids.length; i++) { @@ -788,34 +812,5 @@ public abstract class SchematicHandler { SchematicHandler.this.save(tag, file.toString()); } } - - /** - * Schematic Dimensions - * - - */ - public static class Dimension { - private final int x; - private final int y; - private final int z; - - public Dimension(final int x, final int y, final int z) { - this.x = x; - this.y = y; - this.z = z; - } - - public int getX() { - return x; - } - - public int getY() { - return y; - } - - public int getZ() { - return z; - } - } } diff --git a/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java b/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java index f7b9e2738..2cbe44286 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java +++ b/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java @@ -1,19 +1,17 @@ package com.intellectualcrafters.plot.util; +import com.intellectualcrafters.plot.object.PlotBlock; + import java.util.ArrayDeque; import java.util.concurrent.atomic.AtomicInteger; -import com.intellectualcrafters.plot.object.PlotBlock; - public class SetQueue { public static final SetQueue IMP = new SetQueue(); - - public PlotQueue queue; - private final AtomicInteger time_waiting = new AtomicInteger(2); private final AtomicInteger time_current = new AtomicInteger(0); private final ArrayDeque runnables = new ArrayDeque<>(); + public PlotQueue queue; private long last; private long last2; @@ -72,7 +70,7 @@ public class SetQueue { } public boolean tasks() { - if (runnables.size() == 0) { + if (runnables.isEmpty()) { return false; } final ArrayDeque tmp = runnables.clone(); @@ -106,8 +104,7 @@ public class SetQueue { * @param x * @param y * @param z - * @param id - * @param data + * @param block * @return */ public boolean setBlock(final String world, final int x, final int y, final int z, PlotBlock block) { diff --git a/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java b/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java index aa993169f..2de8697e6 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java +++ b/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java @@ -1,9 +1,5 @@ package com.intellectualcrafters.plot.util; -import java.util.HashSet; -import java.util.Map; -import java.util.UUID; - import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.OfflinePlotPlayer; @@ -13,6 +9,10 @@ import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper; +import java.util.HashSet; +import java.util.Map; +import java.util.UUID; + public class UUIDHandler { public static UUIDHandlerImplementation implementation; @@ -61,7 +61,7 @@ public class UUIDHandler { public static HashSet getAllUUIDS() { final HashSet uuids = new HashSet<>(); for (final Plot plot : PS.get().getPlots()) { - if (plot.owner != null) { + if (plot.hasOwner()) { uuids.add(plot.owner); uuids.addAll(plot.getTrusted()); uuids.addAll(plot.getMembers()); diff --git a/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java b/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java index 5d61de8ec..b66397298 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java +++ b/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java @@ -7,18 +7,28 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.object.ConsolePlayer; +import com.intellectualcrafters.plot.object.OfflinePlotPlayer; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public abstract class UUIDHandlerImplementation { - - private BiMap uuidMap = HashBiMap.create(new HashMap()); + + public final ConcurrentHashMap players; public boolean CACHED = false; public UUIDWrapper uuidWrapper = null; - public final ConcurrentHashMap players; + public HashSet unknown = new HashSet<>(); + private BiMap uuidMap = HashBiMap.create(new HashMap()); public UUIDHandlerImplementation(final UUIDWrapper wrapper) { uuidWrapper = wrapper; @@ -57,7 +67,7 @@ public abstract class UUIDHandlerImplementation { } public void add(final BiMap toAdd) { - if (uuidMap.size() == 0) { + if (uuidMap.isEmpty()) { uuidMap = toAdd; } for (final Map.Entry entry : toAdd.entrySet()) { @@ -79,8 +89,6 @@ public abstract class UUIDHandlerImplementation { PS.debug(C.PREFIX.s() + "&6Cached a total of: " + uuidMap.size() + " UUIDs"); } - public HashSet unknown = new HashSet<>(); - public boolean add(final StringWrapper name, final UUID uuid) { if ((uuid == null)) { return false; @@ -99,7 +107,7 @@ public abstract class UUIDHandlerImplementation { * lazy UUID conversion: * - Useful if the person misconfigured the database, or settings before PlotMe conversion */ - if (!Settings.OFFLINE_MODE && unknown.size() > 0) { + if (!Settings.OFFLINE_MODE && !unknown.isEmpty()) { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { @@ -113,7 +121,7 @@ public abstract class UUIDHandlerImplementation { if (offline != null && !offline.equals(uuid)) { unknown.remove(offline); final Set plots = PS.get().getPlotsAbs(offline); - if (plots.size() > 0) { + if (!plots.isEmpty()) { for (final Plot plot : plots) { plot.owner = uuid; } @@ -131,7 +139,7 @@ public abstract class UUIDHandlerImplementation { if (offline != null) { if (!offline.equals(uuid)) { final Set plots = PS.get().getPlots(offline); - if (plots.size() > 0) { + if (!plots.isEmpty()) { for (final Plot plot : plots) { plot.owner = uuid; } @@ -194,7 +202,7 @@ public abstract class UUIDHandlerImplementation { } public UUID getUUID(final String name, final RunnableVal ifFetch) { - if ((name == null) || (name.length() == 0)) { + if ((name == null) || (name.isEmpty())) { return null; } // check online diff --git a/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java b/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java index 100eaee86..c2e5e634a 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java +++ b/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java @@ -1,27 +1,22 @@ package com.intellectualcrafters.plot.util.area; +import com.intellectualcrafters.plot.object.RegionWrapper; + import java.util.HashSet; import java.util.Set; -import com.intellectualcrafters.plot.object.RegionWrapper; - public class QuadMap { public final int size; public final int x; public final int z; - + private final int newsize; + private final int min; public HashSet objects; - public QuadMap one; public QuadMap two; public QuadMap three; public QuadMap four; - public QuadMap skip; - - private final int newsize; - - private final int min; public QuadMap(int size, int x, int z) { this.size = size; @@ -161,7 +156,7 @@ public class QuadMap { public boolean remove(T area) { if (objects != null) { if (objects.remove(area)) { - return objects.size() == 0; + return objects.isEmpty(); } } if (skip != null) { diff --git a/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java b/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java index 0447ed375..438a42929 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java +++ b/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java @@ -13,7 +13,8 @@ public class HelpObject { public HelpObject(final Command command, final String label) { _command = command; _rendered = StringMan.replaceAll(C.HELP_ITEM.s(), "%usage%", _command.getUsage().replaceAll("\\{label\\}", label), "[%alias%]", - _command.getAliases().size() > 0 ? "(" + StringMan.join(_command.getAliases(), "|") + ")" : "", "%desc%", _command.getDescription(), "%arguments%", + !_command.getAliases().isEmpty() ? "(" + StringMan.join(_command.getAliases(), "|") + ")" : "", "%desc%", _command.getDescription(), + "%arguments%", buildArgumentList(_command.getRequiredArguments()), "{label}", label); } diff --git a/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/src/main/java/com/plotsquared/bukkit/BukkitMain.java index c918b184a..bfb6e5eba 100644 --- a/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -1,28 +1,5 @@ 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.plot.IPlotMain; 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.SQLUUIDHandler; 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 { @@ -115,11 +116,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (split.length == 3) { version[2] = Integer.parseInt(split[2]); } - } catch (final Exception e) { + } catch (NumberFormatException e) { e.printStackTrace(); PS.debug(StringMan.getString(Bukkit.getBukkitVersion())); 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; @@ -261,7 +262,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { continue; } List meta = entity.getMetadata("plot"); - if (meta.size() == 0) { + if (meta.isEmpty()) { continue; } Plot origin = (Plot) meta.get(0).value(); @@ -322,13 +323,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (BukkitUtil.getLocation(loc).isPlotRoad()) { final Entity passenger = entity.getPassenger(); if (!(passenger instanceof Player)) { - if (entity.getMetadata("keep").size() == 0) { + if (entity.getMetadata("keep").isEmpty()) { iter.remove(); entity.remove(); } } } - continue; } } } @@ -412,7 +412,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (econ.init()) { return econ; } - } catch (final Throwable e) {} + } catch (final Throwable ignored) { + } return null; } @@ -428,11 +429,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) { try { return new FastQueue_1_8_3(); - } catch (final Throwable e) { + } catch (NoSuchMethodException e) { e.printStackTrace(); try { return new FastQueue_1_8(); - } catch (Throwable e2) { + } catch (NoSuchMethodException e2) { e2.printStackTrace(); return new SlowQueue(); } @@ -440,7 +441,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { } try { return new FastQueue_1_7(); - } catch (final Throwable e) { + } catch (NoSuchMethodException e) { return new SlowQueue(); } } @@ -524,9 +525,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { FlagManager.removeFlag(FlagManager.getFlag("titles")); } else { AbstractTitle.TITLE_CLASS = new DefaultTitle(); - if (wrapper instanceof DefaultUUIDWrapper) { - Settings.TWIN_MODE_UUID = true; - } else if ((wrapper.getClass() == OfflineUUIDWrapper.class) && !Bukkit.getOnlineMode()) { + if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { Settings.TWIN_MODE_UUID = true; } } @@ -579,7 +578,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { final Metrics metrics = new Metrics(this); metrics.start(); log(C.PREFIX.s() + "&6Metrics enabled."); - } catch (final Exception e) { + } catch (IOException e) { 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(); String[] pas = bukkitServerClass.getName().split("\\."); if (pas.length == 5) { - final String verB = pas[3]; - return verB; + return pas[3]; } try { final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); @@ -676,10 +674,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { final Class handleServerClass = handle.getClass(); pas = handleServerClass.getName().split("\\."); if (pas.length == 5) { - final String verM = pas[3]; - return verM; + return pas[3]; } - } catch (final Exception e) { + } catch (IllegalAccessException | InvocationTargetException | SecurityException | NoSuchMethodException | IllegalArgumentException e) { e.printStackTrace(); } PS.debug("Unknown NMS package: " + StringMan.getString(pas)); diff --git a/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java b/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java index 3b7dbe19a..3e1ba2006 100644 --- a/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java +++ b/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java @@ -1,25 +1,55 @@ 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.util.ArrayList; import java.util.HashMap; import java.util.Map; 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}. */ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable { - + + static final BiMap stylesToNames; + + static { + final ImmutableBiMap.Builder 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; ArrayList styles = new ArrayList(); String clickActionName = null, clickActionData = null, hoverActionName = null; @@ -35,7 +65,21 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa MessagePart() { text = null; } - + + @SuppressWarnings("unchecked") + public static MessagePart deserialize(final Map serialized) { + final MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); + part.styles = (ArrayList) 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) serialized.get("translationReplacements"); + return part; + } + boolean hasText() { return text != null; } @@ -52,34 +96,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa } obj.translationReplacements = (ArrayList) translationReplacements.clone(); return obj; - - } - - static final BiMap stylesToNames; - - static { - final ImmutableBiMap.Builder 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 @@ -102,7 +119,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa if (insertionData != null) { 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(); for (final JsonRepresentedObject obj : translationReplacements) { obj.writeJson(json); @@ -130,22 +147,4 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa return map; } - @SuppressWarnings("unchecked") - public static MessagePart deserialize(final Map serialized) { - final MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); - part.styles = (ArrayList) 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) serialized.get("translationReplacements"); - return part; - } - - static { - ConfigurationSerialization.registerClass(MessagePart.class); - } - } diff --git a/src/main/java/com/plotsquared/bukkit/chat/Reflection.java b/src/main/java/com/plotsquared/bukkit/chat/Reflection.java index 61fc79722..309f79e0c 100644 --- a/src/main/java/com/plotsquared/bukkit/chat/Reflection.java +++ b/src/main/java/com/plotsquared/bukkit/chat/Reflection.java @@ -1,23 +1,38 @@ package com.plotsquared.bukkit.chat; +import org.bukkit.Bukkit; + import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import org.bukkit.Bukkit; - /** * A class containing static utility methods and caches which are intended as reflective conveniences. * Unless otherwise noted, upon failure methods will return {@code null}. */ public final class Reflection { - + + /** + * Stores loaded classes from the {@code net.minecraft.server} package. + */ + private static final Map> _loadedNMSClasses = new HashMap<>(); + /** + * Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages). + */ + private static final Map> _loadedOBCClasses = new HashMap<>(); + private static final Map, Map> _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, Map>, Method>>> _loadedMethods = new HashMap<>(); private static String _versionString; - + private Reflection() { - + } /** @@ -34,19 +49,10 @@ public final class Reflection { final String name = Bukkit.getServer().getClass().getPackage().getName(); _versionString = name.substring(name.lastIndexOf('.') + 1) + "."; } - + return _versionString; } - /** - * Stores loaded classes from the {@code net.minecraft.server} package. - */ - private static final Map> _loadedNMSClasses = new HashMap>(); - /** - * Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages). - */ - private static final Map> _loadedOBCClasses = new HashMap>(); - /** * 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). @@ -57,12 +63,12 @@ public final class Reflection { if (_loadedNMSClasses.containsKey(className)) { return _loadedNMSClasses.get(className); } - + final String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; + Class clazz; try { clazz = Class.forName(fullName); - } catch (final Exception e) { + } catch (ClassNotFoundException e) { e.printStackTrace(); _loadedNMSClasses.put(className, 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. - * 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). - * @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}. + * 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). + * @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. */ public synchronized static Class getOBCClass(final String className) { if (_loadedOBCClasses.containsKey(className)) { return _loadedOBCClasses.get(className); } - + final String fullName = "org.bukkit.craftbukkit." + getVersion() + className; - Class clazz = null; + Class clazz; try { clazz = Class.forName(fullName); - } catch (final Exception e) { + } catch (ClassNotFoundException e) { e.printStackTrace(); _loadedOBCClasses.put(className, null); return null; @@ -98,7 +106,8 @@ public final class Reflection { /** * Attempts to get the NMS handle of a CraftBukkit 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. + * 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. *

* @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()}. @@ -106,14 +115,18 @@ public final class Reflection { public synchronized static Object getHandle(final Object obj) { try { 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(); return null; } } - private static final Map, Map> _loadedFields = new HashMap, Map>(); - /** * 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 @@ -123,7 +136,8 @@ public final class Reflection { * no field will be reflectively looked up twice. *

*

- * 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. *

* @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) { Map loaded; if (!_loadedFields.containsKey(clazz)) { - loaded = new HashMap(); + loaded = new HashMap<>(); _loadedFields.put(clazz, loaded); } else { loaded = _loadedFields.get(clazz); @@ -148,7 +162,13 @@ public final class Reflection { field.setAccessible(true); loaded.put(name, 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 e.printStackTrace(); // 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, Map>, Method>>> _loadedMethods = new HashMap, Map>, Method>>>(); - /** * 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 @@ -194,7 +208,7 @@ public final class Reflection { } final Map>, Method> loadedSignatures = loadedMethodNames.get(name); - final ArrayWrapper> wrappedArg = new ArrayWrapper>(args); + final ArrayWrapper> wrappedArg = new ArrayWrapper<>(args); if (loadedSignatures.containsKey(wrappedArg)) { return loadedSignatures.get(wrappedArg); } diff --git a/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java b/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java index d091cb6ca..3c0e0d9e9 100644 --- a/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java +++ b/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java @@ -1,15 +1,15 @@ 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.collect.ImmutableMap; import com.google.gson.stream.JsonWriter; import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; 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. * 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); } - @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 map) { - if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) { + if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) { // Arbitrary text component 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 return ComplexTextTypeComponent.deserialize(map); } @@ -66,161 +46,27 @@ public abstract class TextualComponent implements Cloneable { } 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) { - 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 ArbitraryTextTypeComponent(final String key, final String value) { - setKey(key); - setValue(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 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 serialize() { - return new HashMap() { - { - put("key", getKey()); - put("value", getValue()); - } - }; - } - - public static ArbitraryTextTypeComponent deserialize(final Map 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 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 getValue() { - return _value; - } - - public void setValue(final Map value) { - Preconditions.checkArgument(value != null, "The value must be specified."); - _value = value; - } - - private String _key; - private Map _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 jsonPair : _value.entrySet()) { - writer.name(jsonPair.getKey()).value(jsonPair.getValue()); - } - writer.endObject(); - } - - @Override - @SuppressWarnings("serial") - public Map serialize() { - return new java.util.HashMap() { - { - put("key", getKey()); - for (final Map.Entry valEntry : getValue().entrySet()) { - put("value." + valEntry.getKey(), valEntry.getValue()); - } - } - }; - } - - public static ComplexTextTypeComponent deserialize(final Map map) { - String key = null; - final Map value = new HashMap(); - for (final Map.Entry 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. + public abstract String getKey(); + + extual component + representing a + string literal + . * 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. * @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 key, which can be overridden by a resource pack. *

* 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) { 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."); } /** - * 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. *

* This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. @@ -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 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 serialize() { + return new HashMap() { + { + 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. *

* This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. @@ -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. */ 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 - - return new ComplexTextTypeComponent("score", ImmutableMap. builder().put("name", playerName).put("objective", scoreboardObjective).build()); + 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.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 _value; + + public ComplexTextTypeComponent(final String key, final Map values) { + setKey(key); + setValue(values); + } + + public static ComplexTextTypeComponent deserialize(final Map map) { + String key = null; + final Map value = new HashMap(); + for (final Map.Entry 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 getValue() { + return _value; + } + + public void setValue(final Map 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 jsonPair : _value.entrySet()) { + writer.name(jsonPair.getKey()).value(jsonPair.getValue()); + } + writer.endObject(); + } + + @Override + @SuppressWarnings("serial") + public Map serialize() { + return new java.util.HashMap() { + { + put("key", getKey()); + for (final Map.Entry 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. *

* This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. diff --git a/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java b/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java index 68943c4bb..dd3fa9e38 100644 --- a/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java +++ b/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java @@ -74,30 +74,26 @@ public class DebugUUID extends SubCommand { final UUIDWrapper newWrapper; switch (args[0].toLowerCase()) { - case "lower": { + case "lower": newWrapper = new LowerOfflineUUIDWrapper(); break; - } - case "offline": { + case "offline": newWrapper = new OfflineUUIDWrapper(); break; - } - case "online": { + case "online": newWrapper = new DefaultUUIDWrapper(); break; - } - default: { + default: try { final Class clazz = Class.forName(args[0]); newWrapper = (UUIDWrapper) clazz.newInstance(); - } catch (final Exception e) { + } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert "); 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, "&cBe aware of the following!"); 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"); - - final HashMap uCMap = new HashMap(); - final HashMap uCReverse = new HashMap(); + + final HashMap uCMap = new HashMap<>(); + final HashMap uCReverse = new HashMap<>(); MainUtil.sendMessage(player, "&7 - Collecting playerdata"); @@ -187,7 +183,7 @@ public class DebugUUID extends SubCommand { uCReverse.put(uuid2, uuid); } } - if (uCMap.size() == 0) { + if (uCMap.isEmpty()) { MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate"); for (final OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) { 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!"); return false; } else { @@ -229,13 +225,13 @@ public class DebugUUID extends SubCommand { for (String line : lines) { try { line = line.trim(); - if (line.length() == 0) { + if (line.isEmpty()) { continue; } line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); final String[] split = line.split("\\|"); 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; } final UUID old = currentUUIDWrapper.getUUID(name); @@ -302,16 +298,13 @@ public class DebugUUID extends SubCommand { if (newWrapper instanceof OfflineUUIDWrapper) { PS.get().config.set("UUID.force-lowercase", false); 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) { PS.get().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.offline", false); } try { 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!"); } diff --git a/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java b/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java index b57892d49..2a88003d8 100644 --- a/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java +++ b/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java @@ -1,16 +1,5 @@ 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.intellectualcrafters.configuration.file.FileConfiguration; 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.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 { private String plugin; @@ -46,20 +46,19 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } else { return new SQLite(dataFolder + File.separator + "plots.db").openConnection(); } - } catch (SQLException | ClassNotFoundException e) {} + } catch (SQLException | ClassNotFoundException ignored) { + } return null; } @Override public HashMap> getPlotMePlots(final Connection connection) throws SQLException { - ResultSet r; - PreparedStatement stmt; final HashMap plotWidth = new HashMap<>(); final HashMap roadWidth = new HashMap<>(); final HashMap> plots = new HashMap<>(); final HashMap> merges = new HashMap<>(); - stmt = connection.prepareStatement("SELECT * FROM `" + prefix + "Plots`"); - r = stmt.executeQuery(); + PreparedStatement stmt = connection.prepareStatement("SELECT * FROM `" + prefix + "Plots`"); + ResultSet r = stmt.executeQuery(); String column = null; final boolean checkUUID = DBFunc.hasColumn(r, "ownerid"); final boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId"); @@ -68,7 +67,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } else if (checkUUID2) { column = "ownerId"; } - final boolean merge = !plugin.equalsIgnoreCase("plotme") && Settings.CONVERT_PLOTME; + final boolean merge = !"plotme".equalsIgnoreCase(plugin) && Settings.CONVERT_PLOTME; int missing = 0; while (r.next()) { 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); if (owner == null) { - if (name.equals("*")) { + if ("*".equals(name)) { owner = DBFunc.everyone; } else { if (checkUUID || checkUUID2) { @@ -126,12 +125,12 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } UUIDHandler.add(new StringWrapper(name), owner); } - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } } if (owner == null) { - if (name.length() > 0) { + if (!name.isEmpty()) { owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); } 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")); UUID denied = UUIDHandler.getUUID(name, null); if (denied == null) { - if (name.equals("*")) { + if ("*".equals(name)) { denied = DBFunc.everyone; } else { if (DBFunc.hasColumn(r, "playerid")) { @@ -196,7 +195,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } UUIDHandler.add(new StringWrapper(name), denied); } - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -220,7 +219,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { final String world = LikePlotMeConverter.getWorld(r.getString("world")); UUID helper = UUIDHandler.getUUID(name, null); if (helper == null) { - if (name.equals("*")) { + if ("*".equals(name)) { helper = DBFunc.everyone; } else { if (DBFunc.hasColumn(r, "playerid")) { @@ -238,7 +237,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } UUIDHandler.add(new StringWrapper(name), helper); } - } catch (final Exception e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -263,9 +262,6 @@ public class ClassicPlotMeConnector extends APlotMeConnector { @Override public boolean accepts(final String version) { - if (version == null) { - return true; - } - return PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version); + return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version); } } diff --git a/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index b58f5829f..ba29c4393 100644 --- a/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -20,17 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// 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.generator.GeneratorWrapper; 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.util.BukkitUtil; 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 { - private boolean loaded = false; private final PlotChunk chunkSetter; private final PseudoRandom random = new PseudoRandom(); - private PlotManager manager; private final IndependentPlotGenerator plotGenerator; + private final List populators = new ArrayList<>(); + private boolean loaded = false; + private PlotManager manager; private ChunkGenerator platformGenerator; private boolean full; - - private final List populators = new ArrayList<>(); public BukkitPlotGenerator(final String world, IndependentPlotGenerator generator) { WorldEvents.lastWorld = world; @@ -211,7 +209,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap final String name = WorldEvents.getName(world); PS.get().loadWorld(name, this); Set areas = PS.get().getPlotAreas(name); - if (areas.size() != 0) { + if (!areas.isEmpty()) { PlotArea area = areas.iterator().next(); if (!area.MOB_SPAWNING) { if (!area.SPAWN_EGGS) { diff --git a/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java b/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java index 2288f2dbf..5cfda088c 100644 --- a/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java +++ b/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java @@ -2,10 +2,17 @@ package com.plotsquared.bukkit.listeners; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; -import java.util.ArrayDeque; -import java.util.HashMap; -import java.util.Map.Entry; - +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.Settings; +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.Chunk; 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.ChunkUnloadEvent; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -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 java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map.Entry; public class ChunkListener implements Listener { - private Chunk lastChunk = null; - private final RefClass classChunk = getRefClass("{nms}.Chunk"); private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - private RefMethod methodGetHandleChunk; private final RefField mustSave = classChunk.getField("mustSave"); + private Chunk lastChunk = null; + private RefMethod methodGetHandleChunk; public ChunkListener() { @@ -62,7 +60,6 @@ public class ChunkListener implements Listener { TaskManager.runTask(new Runnable() { @Override public void run() { - int time = 300; final int distance = Bukkit.getViewDistance() + 2; final HashMap> players = new HashMap<>(); for (final Entry entry : UUIDHandler.getPlayers().entrySet()) { @@ -90,23 +87,24 @@ public class ChunkListener implements Listener { map.put(origin, distance); } for (int x = -distance; x <= distance; x++) { - if ((x >= check) || (-x >= check)) { + if (x >= check || -x >= check) { continue; } for (int z = -distance; z <= distance; z++) { - if ((z >= check) || (-z >= check)) { + if (z >= check || -z >= check) { continue; } final int weight = distance - Math.max(Math.abs(x), Math.abs(z)); final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z); val = map.get(chunk); - if ((val == null) || (val < weight)) { + if (val == null || val < weight) { map.put(chunk, weight); } } } } + int time = 300; for (final World world : Bukkit.getWorlds()) { final String name = world.getName(); if (!PS.get().hasPlotArea(name)) { @@ -117,11 +115,11 @@ public class ChunkListener implements Listener { world.setAutoSave(false); } final HashMap map = players.get(name); - if ((map == null) || (map.size() == 0)) { + if (map == null || map.isEmpty()) { continue; } Chunk[] chunks = world.getLoadedChunks(); - ArrayDeque toUnload = new ArrayDeque(); + ArrayDeque toUnload = new ArrayDeque<>(); for (final Chunk chunk : chunks) { final int x = chunk.getX(); final int z = chunk.getZ(); @@ -129,17 +127,17 @@ public class ChunkListener implements Listener { toUnload.add(chunk); } } - if (toUnload.size() > 0) { + if (!toUnload.isEmpty()) { long start = System.currentTimeMillis(); 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 (chunk.isLoaded()) { chunk.unload(true, false); } } } - if (toUnload.size() > 0) { + if (!toUnload.isEmpty()) { time = 1; } } @@ -159,26 +157,25 @@ public class ChunkListener implements Listener { final int z = Z << 4; final int x2 = x + 15; final int z2 = z + 15; - Plot plot; Thread thread = new Thread(); - plot = new Location(world, x, 1, z).getOwnedPlotAbs(); - if ((plot != null) && (plot.owner != null)) { + Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs(); + if (plot != null && plot.hasOwner()) { return false; } plot = new Location(world, x2, 1, z2).getOwnedPlotAbs(); - if ((plot != null) && (plot.owner != null)) { + if (plot != null && plot.hasOwner()) { return false; } plot = new Location(world, x2, 1, z).getOwnedPlotAbs(); - if ((plot != null) && (plot.owner != null)) { + if (plot != null && plot.hasOwner()) { return false; } plot = new Location(world, x, 1, z2).getOwnedPlotAbs(); - if ((plot != null) && (plot.owner != null)) { + if (plot != null && plot.hasOwner()) { return false; } plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs(); - if ((plot != null) && (plot.owner != null)) { + if (plot != null && plot.hasOwner()) { return false; } final Object c = methodGetHandleChunk.of(chunk).call(); @@ -284,7 +281,7 @@ public class ChunkListener implements Listener { } final long start = System.currentTimeMillis(); int i = 0; - while ((System.currentTimeMillis() - start) < 250) { + while (System.currentTimeMillis() - start < 250) { if (i >= tiles.length) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); diff --git a/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java b/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java index 8d6fcdffa..74dec3012 100644 --- a/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java @@ -1,16 +1,33 @@ package com.plotsquared.bukkit.listeners; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; - +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotBlock; +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.ChatColor; import org.bukkit.Material; @@ -89,34 +106,16 @@ import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.Vector; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -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 java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; /** * Player Events involving plots @@ -126,6 +125,9 @@ import com.plotsquared.listener.PlayerBlockEventType; public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener { 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) { TaskManager.runTaskLater(new Runnable() { @@ -139,10 +141,10 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen PlotPlayer player = entry.getValue(); final Location loc = player.getLocation(); if (loc.getWorld().equals(world)) { - if ((16 * (Math.abs(loc.getX() - x) / 16)) > distance) { + if (16 * Math.abs(loc.getX() - x) / 16 > distance) { continue; } - if ((16 * (Math.abs(loc.getZ() - z) / 16)) > distance) { + if (16 * Math.abs(loc.getZ() - z) / 16 > distance) { continue; } ((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 ACACIA_FENCE_GATE: case DARK_OAK_FENCE_GATE: - case POWERED_RAIL: { + case POWERED_RAIL: return; - } - default: { + default: final Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { @@ -227,7 +228,6 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } event.setNewCurrent(0); } - } } } @@ -254,7 +254,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case 122: case 145: case 12: - case 13: { + case 13: final Block block = event.getBlock(); final Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); @@ -262,15 +262,13 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } 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); return; } return; - } - default: { + default: break; - } } } @@ -286,9 +284,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } Plot plot = area.getPlotAbs(loc); - // + // final ProjectileSource shooter = entity.getShooter(); - if ((shooter instanceof Player)) { + if (shooter instanceof Player) { final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { @@ -314,7 +312,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } final Plot sPlot = area.getOwnedPlotAbs(sLoc); - if ((sPlot == null) || !PlotHandler.sameOwners(plot, sPlot)) { + if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) { entity.remove(); } } @@ -323,7 +321,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void PlayerCommand(final PlayerCommandPreprocessEvent event) { String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); - if (msg.length() == 0) { + if (msg.isEmpty()) { return; } final String[] split = msg.split(" "); @@ -388,7 +386,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen for (final String s : v) { Pattern pattern; if (!RegExUtil.compiledPatterns.containsKey(s)) { - RegExUtil.compiledPatterns.put(s, ((pattern = Pattern.compile(s)))); + RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); } else { pattern = RegExUtil.compiledPatterns.get(s); } @@ -418,7 +416,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen StringWrapper sw = new StringWrapper(name); final UUID uuid = pp.getUUID(); UUIDHandler.add(sw, uuid); - + Location loc = pp.getLocation(); PlotArea area = loc.getPlotArea(); final Plot plot; @@ -431,9 +429,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen plot = null; } // Delayed - { - - } + // Async TaskManager.runTaskLaterAsync(new Runnable() { @Override @@ -447,7 +443,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen 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"); } 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()))) { final Player player = event.getPlayer(); final PlotPlayer pp = BukkitUtil.getPlayer(player); - + // Cancel teleport TaskManager.TELEPORT_QUEUE.remove(pp.getName()); @@ -486,9 +482,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen Plot now = area.getPlotAbs(loc); final Plot lastPlot = pp.getMeta("lastplot"); 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); - if (lastPlot.equals((BukkitUtil.getLocation(from).getPlot()))) { + if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { player.teleport(from); } else { player.teleport(player.getWorld().getSpawnLocation()); @@ -496,7 +492,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } - } else if ((lastPlot != null) && now.equals(lastPlot)) { + } else if (lastPlot != null && now.equals(lastPlot)) { return; } else { 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()))) { final Player player = event.getPlayer(); final PlotPlayer pp = BukkitUtil.getPlayer(player); - + // Cancel teleport TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location Location loc = BukkitUtil.getLocation(to); pp.setMeta("location", loc); - + PlotArea area = loc.getPlotArea(); if (area == null) { pp.deleteMeta("lastplot"); @@ -544,9 +540,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen Plot now = area.getPlotAbs(loc); final Plot lastPlot = pp.getMeta("lastplot"); 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); - if (lastPlot.equals((BukkitUtil.getLocation(from).getPlot()))) { + if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { player.teleport(from); } else { player.teleport(player.getWorld().getSpawnLocation()); @@ -554,7 +550,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } - } else if ((lastPlot != null) && now.equals(lastPlot)) { + } else if (lastPlot != null && now.equals(lastPlot)) { return; } else { if (!plotEntry(pp, now)) { @@ -587,7 +583,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen final PlotPlayer plr = BukkitUtil.getPlayer(player); Location loc = plr.getLocation(); PlotArea area = loc.getPlotArea(); - if (area == null || (!area.PLOT_CHAT && !plr.getAttribute("chat"))) { + if (area == null || !area.PLOT_CHAT && !plr.getAttribute("chat")) { return; } 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())) { final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); final Block block = event.getBlock(); - if ((destroy != null) && ((HashSet) destroy.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + if (destroy != null && ((HashSet) destroy.getValue()) + .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { return; } 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")) { List meta = event.getEntity().getMetadata("plot"); Plot origin; - if (meta.size() == 0) { + if (meta.isEmpty()) { origin = plot; } else { origin = (Plot) meta.get(0).value(); @@ -694,7 +691,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (lastRadius != 0) { final List nearby = event.getEntity().getNearbyEntities(lastRadius, lastRadius, lastRadius); 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")) { 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) { final Player player = event.getPlayer(); final PlotPlayer pp = BukkitUtil.getPlayer(player); - + // Delete last location pp.deleteMeta("location"); @@ -729,7 +726,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (plot != null) { plotExit(pp, plot); } - + if (BukkitMain.worldEdit != null) { if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { if (pp.getAttribute("worldedit")) { @@ -815,7 +812,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (!plot.isAdded(pp.getUUID())) { final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); final Block block = event.getBlock(); - if ((destroy != null) && ((HashSet) destroy.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + if (destroy != null && ((HashSet) destroy.getValue()) + .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { return; } if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { @@ -928,7 +926,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen pistonBlocks = false; } } - if (!pistonBlocks && (block.getType() != Material.PISTON_BASE)) { + if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { final BlockFace dir = event.getDirection(); loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (loc.getPlotArea() != null) { @@ -957,7 +955,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen pistonBlocks = false; } } - if (!pistonBlocks && (block.getType() != Material.PISTON_BASE)) { + if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { final BlockFace dir = event.getDirection(); loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (!area.contains(loc)) { @@ -989,7 +987,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return; } final List blocks = e.getBlocks(); - if (blocks.size() == 0) { + if (blocks.isEmpty()) { return; } Location loc = BukkitUtil.getLocation(blocks.get(0).getLocation()); @@ -1106,24 +1104,21 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case HOPPER: case NOTE_BLOCK: case JUKEBOX: - case WORKBENCH: { + case WORKBENCH: eventType = PlayerBlockEventType.INTERACT_BLOCK; break; - } - case DRAGON_EGG: { + case DRAGON_EGG: eventType = PlayerBlockEventType.TELEPORT_OBJECT; break; - } - default: { + default: if (blockId > 197) { eventType = PlayerBlockEventType.INTERACT_BLOCK; } break; - } } lb = new BukkitLazyBlock(blockId, block); final ItemStack hand = player.getItemInHand(); - if ((eventType != null) && !player.isSneaking()) { + if (eventType != null && !player.isSneaking()) { break; } 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)); switch (handType) { case MONSTER_EGG: - case MONSTER_EGGS: { + case MONSTER_EGGS: eventType = PlayerBlockEventType.SPAWN_MOB; break; - } - - case ARMOR_STAND: { + + case ARMOR_STAND: eventType = PlayerBlockEventType.PLACE_MISC; break; - } - + case WRITTEN_BOOK: case BOOK_AND_QUILL: - case BOOK: { + case BOOK: eventType = PlayerBlockEventType.READ; break; - } - + case APPLE: case BAKED_POTATO: case MUSHROOM_SOUP: @@ -1178,42 +1170,36 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case RABBIT_STEW: case RAW_BEEF: case RAW_FISH: - case RAW_CHICKEN: { + case RAW_CHICKEN: eventType = PlayerBlockEventType.EAT; break; - } case MINECART: case STORAGE_MINECART: case POWERED_MINECART: case HOPPER_MINECART: case EXPLOSIVE_MINECART: case COMMAND_MINECART: - case BOAT: { + case BOAT: eventType = PlayerBlockEventType.PLACE_VEHICLE; break; - } case PAINTING: - case ITEM_FRAME: { + case ITEM_FRAME: eventType = PlayerBlockEventType.PLACE_HANGING; break; - } - default: { + default: eventType = PlayerBlockEventType.INTERACT_BLOCK; break; - } } break; } - case LEFT_CLICK_BLOCK: { + case LEFT_CLICK_BLOCK: Block block = event.getClickedBlock(); loc = BukkitUtil.getLocation(block.getLocation()); eventType = PlayerBlockEventType.BREAK_BLOCK; lb = new BukkitLazyBlock(block); break; - } - default: { + default: return; - } } if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, loc, lb, true)) { event.setCancelled(true); @@ -1293,7 +1279,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (event.getTo().hasGravity()) { Entity entity = event.getEntity(); List meta = entity.getMetadata("plot"); - if (meta.size() == 0) { + if (meta.isEmpty()) { return; } Plot origin = (Plot) meta.get(0).value(); @@ -1307,13 +1293,11 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } } - private float lastRadius; - @EventHandler public void onPrime(final ExplosionPrimeEvent event) { lastRadius = event.getRadius() + 1; } - + public boolean checkEntity(Plot plot, String... flags) { int[] mobs = null; for (String flag : flags) { @@ -1337,9 +1321,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case "misc-cap": i = 5; break; - default: { + default: i = 0; - } } final Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag); if (plotFlag == null) { @@ -1348,7 +1331,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (mobs == null) { mobs = plot.countEntities(); } - if (mobs[i] >= ((Integer) plotFlag.getValue())) { + if (mobs[i] >= (Integer) plotFlag.getValue()) { return true; } } @@ -1356,13 +1339,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } 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; } switch (entity.getType()) { - case PLAYER: { + case PLAYER: return false; - } case SMALL_FIREBALL: case FIREBALL: case DROPPED_ITEM: @@ -1371,13 +1355,11 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case SPLASH_POTION: case SNOWBALL: case ENDER_PEARL: - case ARROW: { + case ARROW: // projectile - } case PRIMED_TNT: - case FALLING_BLOCK: { - // Block entities - } + case FALLING_BLOCK: + // Block entities case ENDER_CRYSTAL: case COMPLEX_PART: case FISHING_HOOK: @@ -1388,16 +1370,14 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case WEATHER: case LIGHTNING: case WITHER_SKULL: - case UNKNOWN: { + case UNKNOWN: // non moving / unremovable return checkEntity(plot, "entity-cap"); - } case ITEM_FRAME: case PAINTING: - case ARMOR_STAND: { + case ARMOR_STAND: return checkEntity(plot, "entity-cap", "misc-cap"); - // misc - } + // misc case MINECART: case MINECART_CHEST: case MINECART_COMMAND: @@ -1405,9 +1385,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case MINECART_HOPPER: case MINECART_MOB_SPAWNER: case MINECART_TNT: - case BOAT: { + case BOAT: return checkEntity(plot, "entity-cap", "vehicle-cap"); - } case RABBIT: case SHEEP: case MUSHROOM_COW: @@ -1421,10 +1400,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case CHICKEN: case COW: case SNOWMAN: - case BAT: { + case BAT: // animal return checkEntity(plot, "entity-cap", "mob-cap", "animal-cap"); - } case BLAZE: case CAVE_SPIDER: case CREEPER: @@ -1442,11 +1420,10 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen case SPIDER: case WITCH: case WITHER: - case ZOMBIE: { + case ZOMBIE: // monster return checkEntity(plot, "entity-cap", "mob-cap", "hostile-cap"); - } - default: { + default: String[] types; if (entity instanceof LivingEntity) { if (entity instanceof Animals) { @@ -1464,7 +1441,6 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen types = new String[] { "entity-cap" }; } 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) 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("lastplot"); return; @@ -1551,7 +1524,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen Plot now = area.getPlotAbs(loc); final Plot lastPlot = pp.getMeta("lastplot"); 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); if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { tmp_teleport = false; @@ -1568,7 +1541,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } - } else if ((lastPlot != null) && now.equals(lastPlot)) { + } else if (lastPlot != null && now.equals(lastPlot)) { return; } else { if (!plotEntry(pp, now) && tmp_teleport) { @@ -1623,7 +1596,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen Plot now = area.getPlotAbs(loc); final Plot lastPlot = pp.getMeta("lastplot"); 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); if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { tmp_teleport = false; @@ -1640,7 +1613,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen event.setCancelled(true); return; } - } else if ((lastPlot != null) && now.equals(lastPlot)) { + } else if (lastPlot != null && now.equals(lastPlot)) { return; } else { if (!plotEntry(pp, now) && tmp_teleport) { @@ -1706,7 +1679,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen e.setCancelled(true); } else if (!plot.isAdded(pp.getUUID())) { final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); - if ((use != null) && ((HashSet) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) { + if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) { return; } 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 PlotPlayer pp = BukkitUtil.getPlayer(player); 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())) { event.setCancelled(true); inv.close(); @@ -1778,7 +1751,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen } else if (!plot.isAdded(pp.getUUID())) { final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); final Block block = e.getBlockClicked(); - if ((use != null) && ((HashSet) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { return; } 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())) { 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; } - 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; } - 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; } - 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; } - 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; } 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 vloc = BukkitUtil.getLocation(victim); 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) { return true; } @@ -2042,7 +2015,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen Plot plot; String stub; - if ((dplot == null) && (vplot == null)) { + if (dplot == null && vplot == null) { if (dArea == null) { return true; } @@ -2050,7 +2023,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen stub = "road"; } else { // 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"; } @@ -2071,7 +2045,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen if (player != null) { final PlotPlayer pp = BukkitUtil.getPlayer(player); 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; } if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { @@ -2079,15 +2053,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return false; } } 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; } if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); return false; } - } 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())))) { + } 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()))) { return true; } if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { @@ -2095,7 +2070,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return false; } } 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; } if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { @@ -2121,7 +2097,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return false; } } 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; } 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 return true; } 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; } if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { @@ -2142,7 +2119,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen return true; } // player is null - return !((damager instanceof Arrow) && (!(victim instanceof Creature))); + return !(damager instanceof Arrow && !(victim instanceof Creature)); } @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())) { final Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s()); final Block block = event.getBlock(); - if (((place == null) || !((HashSet) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) + if ((place == null || !((HashSet) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); @@ -2214,7 +2191,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen 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); MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", "" + area.MAX_BUILD_HEIGHT)); } diff --git a/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java b/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java index 1d262f193..f1f1309ec 100644 --- a/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -20,13 +20,14 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.listeners; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.UUID; - +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; +import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.listener.PlotListener; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; @@ -42,18 +43,17 @@ import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; -import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.listener.PlotListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.UUID; /** * Created 2014-10-30 for PlotSquared - * + * + */ @SuppressWarnings({ "deprecation" }) 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() { @Override public void run() { - if (healRunnable.size() > 0) { + if (!healRunnable.isEmpty()) { for (final Iterator> iter = healRunnable.entrySet().iterator(); iter.hasNext();) { final Entry entry = iter.next(); 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> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) { final Entry entry = iter.next(); final Interval value = entry.getValue(); @@ -216,7 +216,8 @@ public class PlotPlusListener extends PlotListener implements Listener { /** * Record Meta Class - * + * + */ public static class RecordMeta { public final static List metaList = new ArrayList<>(); diff --git a/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java b/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java index 5f2cbcb59..3cda97f6c 100644 --- a/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java +++ b/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java @@ -3,7 +3,11 @@ package com.plotsquared.bukkit.object; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.object.Location; 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 org.bukkit.Bukkit; import org.bukkit.Effect; @@ -12,7 +16,6 @@ import org.bukkit.WeatherType; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.PluginManager; import java.util.UUID; @@ -20,10 +23,10 @@ import java.util.UUID; public class BukkitPlayer extends PlotPlayer { public final Player player; + public boolean offline; private UUID uuid; private String name; private long last = 0; - public boolean offline; /** * 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 public boolean hasPermission(final String node) { - if (offline && (EconHandler.manager != null)) { + if (offline && EconHandler.manager != null) { return EconHandler.manager.hasPermission(getName(), node); } return player.hasPermission(node); @@ -77,8 +80,8 @@ public class BukkitPlayer extends PlotPlayer { final String[] nodes = node.split("\\."); perm = new Permission(node); final StringBuilder n = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - n.append(nodes[i] + (".")); + for (int i = 0; i < nodes.length - 1; i++) { + n.append(nodes[i]).append("."); if (!node.equals(n + C.PERMISSION_STAR.s())) { final Permission parent = getPermission(n + C.PERMISSION_STAR.s()); if (parent != null) { @@ -105,7 +108,7 @@ public class BukkitPlayer extends PlotPlayer { @Override 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; } 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 public boolean getAttribute(String key) { + if (!hasPersistentMeta(key)) { return false; } @@ -171,10 +175,9 @@ public class BukkitPlayer extends PlotPlayer { case CLEAR: player.setPlayerWeather(WeatherType.CLEAR); return; - case RAIN: { + case RAIN: player.setPlayerWeather(WeatherType.DOWNFALL); return; - } case RESET: player.resetPlayerWeather(); return; diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java b/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java index 4ee0c1c9f..921f97d5e 100644 --- a/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java +++ b/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java @@ -33,7 +33,8 @@ import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; public class EntityWrapper { - public short id; + + public EntityType type; public float yaw; public float pitch; public double x; @@ -55,110 +56,6 @@ public class EntityWrapper { 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") public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) { hash = entity.getEntityId(); @@ -169,7 +66,7 @@ public class EntityWrapper { x = loc.getX(); y = loc.getY(); z = loc.getZ(); - id = entity.getType().getTypeId(); + type = entity.getType(); if (depth == 0) { 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() }; storeLiving((LivingEntity) entity); this.stand = new ArmorStandStats(); - + final EulerAngle head = stand.getHeadPose(); this.stand.head[0] = (float) head.getX(); this.stand.head[1] = (float) head.getY(); this.stand.head[2] = (float) head.getZ(); - + final EulerAngle body = stand.getBodyPose(); this.stand.body[0] = (float) body.getX(); this.stand.body[1] = (float) body.getY(); this.stand.body[2] = (float) body.getZ(); - + final EulerAngle leftLeg = stand.getLeftLegPose(); this.stand.leftLeg[0] = (float) leftLeg.getX(); this.stand.leftLeg[1] = (float) leftLeg.getY(); this.stand.leftLeg[2] = (float) leftLeg.getZ(); - + final EulerAngle rightLeg = stand.getRightLegPose(); this.stand.rightLeg[0] = (float) rightLeg.getX(); this.stand.rightLeg[1] = (float) rightLeg.getY(); this.stand.rightLeg[2] = (float) rightLeg.getZ(); - + final EulerAngle leftArm = stand.getLeftArmPose(); this.stand.leftArm[0] = (float) leftArm.getX(); this.stand.leftArm[1] = (float) leftArm.getY(); this.stand.leftArm[2] = (float) leftArm.getZ(); - + final EulerAngle rightArm = stand.getRightArmPose(); this.stand.rightArm[0] = (float) rightArm.getX(); this.stand.rightArm[1] = (float) rightArm.getY(); this.stand.rightArm[2] = (float) rightArm.getZ(); - + if (stand.hasArms()) { this.stand.arms = true; } @@ -403,16 +300,120 @@ public class EntityWrapper { // 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") 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); loc.setYaw(yaw); loc.setPitch(pitch); - if (id == -1) { + if (type.isSpawnable()) { return null; } - final EntityType type = EntityType.fromId(id); Entity entity; switch (type) { case DROPPED_ITEM: { diff --git a/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java b/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java index d3a1c7cf8..504e3ebf1 100644 --- a/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -1,16 +1,5 @@ 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.CompoundTag; 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.util.MathMan; 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 { @@ -46,9 +45,9 @@ public class StateWrapper { for (int i = 0; i < length; i++) { final Tag itemTag = itemsTag.get(i); final CompoundTag itemComp = (CompoundTag) itemTag; - short id = itemComp.getShort("id"); - String idStr = itemComp.getString("id"); - if ((idStr != null) && !MathMan.isInteger(idStr)) { + short id = itemComp.getShort("type"); + String idStr = itemComp.getString("type"); + if (idStr != null && !MathMan.isInteger(idStr)) { idStr = idStr.split(":")[0].toLowerCase(); id = (short) ItemType.getId(idStr); } @@ -69,7 +68,7 @@ public class StateWrapper { if (state instanceof InventoryHolder) { final InventoryHolder inv = (InventoryHolder) state; final ItemStack[] contents = inv.getInventory().getContents(); - final Map values = new HashMap(); + final Map values = new HashMap<>(); values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents))); return new CompoundTag(values); } @@ -81,7 +80,7 @@ public class StateWrapper { } public List serializeInventory(final ItemStack[] items) { - final List tags = new ArrayList(); + final List tags = new ArrayList<>(); for (int i = 0; i < items.length; ++i) { if (items[i] != null) { final Map tagData = serializeItem(items[i]); @@ -105,19 +104,19 @@ public class StateWrapper { */ public Map serializeItem(final ItemStack item) { - final Map data = new HashMap(); - data.put("id", new ShortTag("id", (short) item.getTypeId())); + final Map data = new HashMap<>(); + data.put("type", new ShortTag("type", (short) item.getTypeId())); data.put("Damage", new ShortTag("Damage", item.getDurability())); data.put("Count", new ByteTag("Count", (byte) item.getAmount())); if (!item.getEnchantments().isEmpty()) { - final List enchantmentList = new ArrayList(); + final List enchantmentList = new ArrayList<>(); for (final Entry entry : item.getEnchantments().entrySet()) { - final Map enchantment = new HashMap(); - enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId())); + final Map enchantment = new HashMap<>(); + enchantment.put("type", new ShortTag("type", (short) entry.getKey().getId())); enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue())); enchantmentList.add(new CompoundTag(enchantment)); } - final Map auxData = new HashMap(); + final Map auxData = new HashMap<>(); auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList)); data.put("tag", new CompoundTag("tag", auxData)); } diff --git a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java b/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java index abc63ce90..4de7d0281 100644 --- a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java +++ b/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java @@ -10,7 +10,7 @@ public class DefaultTitle extends AbstractTitle { try { final DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out); title.send(((BukkitPlayer) player).player); - } catch (final Throwable e) { + } catch (Exception e) { AbstractTitle.TITLE_CLASS = new DefaultTitle_183(); AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); } diff --git a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java b/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java index 9a9def85a..3398e3589 100644 --- a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java +++ b/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java @@ -1,15 +1,15 @@ 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.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - /** * [ PlotSquared DefaultTitleManager by Maxim Van de Wynckel ] * @@ -18,6 +18,8 @@ import org.bukkit.entity.Player; * */ public class DefaultTitleManager { + + private static final Map, Class> CORRESPONDING_TYPES = new HashMap<>(); /* Title packet */ private Class packetTitle; /* Title packet actions ENUM */ @@ -36,8 +38,7 @@ public class DefaultTitleManager { private int stayTime = -1; private int fadeOutTime = -1; private boolean ticks = false; - private static final Map, Class> CORRESPONDING_TYPES = new HashMap, Class>(); - + /** * Create a new 1.8 title * @@ -49,7 +50,7 @@ public class DefaultTitleManager { this.title = title; loadClasses(); } - + /** * Create a new 1.8 title * @@ -64,7 +65,7 @@ public class DefaultTitleManager { this.subtitle = subtitle; loadClasses(); } - + /** * Copy 1.8 title * @@ -84,7 +85,7 @@ public class DefaultTitleManager { ticks = title.ticks; loadClasses(); } - + /** * Create a new 1.8 title * @@ -108,216 +109,7 @@ public class DefaultTitleManager { this.fadeOutTime = fadeOutTime; 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) { if (a.length != o.length) { return false; @@ -329,16 +121,239 @@ public class DefaultTitleManager { } 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) { try { 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(); return null; } } - + private Method getMethod(final String name, final Class clazz, final Class... paramTypes) { final Class[] t = toPrimitiveTypeArray(paramTypes); for (final Method m : clazz.getMethods()) { @@ -349,46 +364,46 @@ public class DefaultTitleManager { } return null; } - + private String getVersion() { final String name = Bukkit.getServer().getClass().getPackage().getName(); - final String version = name.substring(name.lastIndexOf('.') + 1) + "."; - return version; + return name.substring(name.lastIndexOf('.') + 1) + "."; } - + private Class getNMSClass(final String className) throws ClassNotFoundException { final String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; - clazz = Class.forName(fullName); - return clazz; + return Class.forName(fullName); } - + private Field getField(final Class clazz, final String name) { try { final Field field = clazz.getDeclaredField(name); field.setAccessible(true); return field; - } catch (final Exception e) { + } catch (NoSuchFieldException e) { + e.printStackTrace(); + return null; + } catch (SecurityException e) { e.printStackTrace(); return null; } } - + private Method getMethod(final Class clazz, final String name, final Class... args) { 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); return m; } } return null; } - + private boolean ClassListEqual(final Class[] l1, final Class[] l2) { - boolean equal = true; if (l1.length != l2.length) { return false; } + boolean equal = true; for (int i = 0; i < l1.length; i++) { if (l1[i] != l2[i]) { equal = false; diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java b/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java index 1d84d4bf3..1c1bd2dee 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java @@ -1,10 +1,5 @@ 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.object.ConsolePlayer; import com.intellectualcrafters.plot.object.PlotMessage; @@ -12,19 +7,23 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.ChatManager; import com.plotsquared.bukkit.chat.FancyMessage; import com.plotsquared.bukkit.object.BukkitPlayer; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; public class BukkitChatManager extends ChatManager { - + @Override public FancyMessage builder() { return new FancyMessage(""); } - + @Override public void color(final PlotMessage m, final String color) { m.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); } - + @Override public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { final List lines = new ArrayList<>(); @@ -33,17 +32,17 @@ public class BukkitChatManager extends ChatManager { } m.$(this).formattedTooltip(lines); } - + @Override public void command(final PlotMessage m, final String command) { m.$(this).command(command); } - + @Override public void text(final PlotMessage m, final String text) { m.$(this).then(ChatColor.stripColor(text)); } - + @Override public void send(final PlotMessage m, final PlotPlayer player) { if (ConsolePlayer.isConsole(player)) { @@ -52,10 +51,10 @@ public class BukkitChatManager extends ChatManager { m.$(this).send(((BukkitPlayer) player).player); } } - + @Override public void suggest(final PlotMessage m, final String command) { m.$(this).suggest(command); } - + } diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index ef4c12afd..010ccbbbe 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -44,7 +44,6 @@ import org.bukkit.block.NoteBlock; import org.bukkit.block.Sign; import org.bukkit.block.Skull; import org.bukkit.block.banner.Pattern; -import org.bukkit.block.banner.PatternType; import org.bukkit.entity.Animals; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; @@ -62,6 +61,590 @@ import java.util.Map.Entry; import java.util.Set; public class BukkitChunkManager extends ChunkManager { + + private static HashMap chestContents; + private static HashMap furnaceContents; + private static HashMap dispenserContents; + private static HashMap dropperContents; + private static HashMap brewingStandContents; + private static HashMap beaconContents; + private static HashMap hopperContents; + private static HashMap furnaceTime; + private static HashMap skullData; + private static HashMap jukeDisc; + private static HashMap brewTime; + private static HashMap spawnerData; + private static HashMap cmdData; + private static HashMap signContents; + private static HashMap noteBlockContents; + private static HashMap> bannerPatterns; + private static HashMap bannerBase; + private static HashSet entities; + private static HashMap allblocks; + + public static void initMaps() { + chestContents = new HashMap<>(); + furnaceContents = new HashMap<>(); + dispenserContents = new HashMap<>(); + dropperContents = new HashMap<>(); + brewingStandContents = new HashMap<>(); + beaconContents = new HashMap<>(); + hopperContents = new HashMap<>(); + furnaceTime = new HashMap<>(); + skullData = new HashMap<>(); + brewTime = new HashMap<>(); + jukeDisc = new HashMap<>(); + spawnerData = new HashMap<>(); + noteBlockContents = new HashMap<>(); + signContents = new HashMap<>(); + cmdData = new HashMap<>(); + bannerBase = new HashMap<>(); + bannerPatterns = new HashMap<>(); + entities = new HashSet<>(); + allblocks = new HashMap<>(); + } + + public static boolean isIn(final RegionWrapper region, final int x, final int z) { + return x >= region.minX && x <= region.maxX && z >= region.minZ && z <= region.maxZ; + } + + public static void saveEntitiesOut(final Chunk chunk, final RegionWrapper region) { + for (final Entity entity : chunk.getEntities()) { + final Location loc = BukkitUtil.getLocation(entity); + final int x = loc.getX(); + final int z = loc.getZ(); + if (isIn(region, x, z)) { + continue; + } + if (entity.getVehicle() != null) { + continue; + } + final EntityWrapper wrap = new EntityWrapper(entity, (short) 2); + entities.add(wrap); + } + } + + public static void saveEntitiesIn(final Chunk chunk, final RegionWrapper region) { + saveEntitiesIn(chunk, region, 0, 0, false); + } + + public static void saveEntitiesIn(final Chunk chunk, final RegionWrapper region, final int offset_x, final int offset_z, final boolean delete) { + for (final Entity entity : chunk.getEntities()) { + final Location loc = BukkitUtil.getLocation(entity); + final int x = loc.getX(); + final int z = loc.getZ(); + if (!isIn(region, x, z)) { + continue; + } + if (entity.getVehicle() != null) { + continue; + } + final EntityWrapper wrap = new EntityWrapper(entity, (short) 2); + wrap.x += offset_x; + wrap.z += offset_z; + entities.add(wrap); + if (delete) { + if (!(entity instanceof Player)) { + entity.remove(); + } + } + } + } + + public static void restoreEntities(final World world, final int x_offset, final int z_offset) { + for (final EntityWrapper entity : entities) { + try { + entity.spawn(world, x_offset, z_offset); + } catch (final Exception e) { + PS.debug("Failed to restore entity (e): " + entity.x + "," + entity.y + "," + entity.z + " : " + entity.type); + e.printStackTrace(); + } + } + entities.clear(); + } + + public static void restoreBlocks(final World world, final int x_offset, final int z_offset) { + for (final Entry blockLocEntry : chestContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Chest) { + final InventoryHolder chest = (InventoryHolder) state; + chest.getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : signContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Sign) { + final Sign sign = (Sign) state; + int i = 0; + for (final String line : blockLocEntry.getValue()) { + sign.setLine(i, line); + i++; + } + state.update(true); + } else { + PS.debug( + "&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry.getKey().y + + "," + ( + blockLocEntry.getKey().z + z_offset)); + } + } catch (IndexOutOfBoundsException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry.getKey().y + + "," + ( + blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : dispenserContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Dispenser) { + ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : dropperContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Dropper) { + ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : beaconContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Beacon) { + ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocMaterialEntry : jukeDisc.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocMaterialEntry.getKey().x + x_offset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry + .getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Jukebox) { + ((Jukebox) state).setPlaying(blockLocMaterialEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + x_offset) + "," + + blockLocMaterialEntry + .getKey().y + "," + ( + blockLocMaterialEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + x_offset) + "," + + blockLocMaterialEntry + .getKey().y + "," + ( + blockLocMaterialEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : skullData.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Skull) { + final Object[] data = blockLocEntry.getValue(); + if (data[0] != null) { + ((Skull) state).setOwner((String) data[0]); + } + if ((Integer) data[1] != 0) { + ((Skull) state).setRotation(BlockFace.values()[(int) data[1]]); + } + if ((Integer) data[2] != 0) { + ((Skull) state).setSkullType(SkullType.values()[(int) data[2]]); + } + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry.getKey().y + + "," + ( + blockLocEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : hopperContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Hopper) { + ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocNoteEntry : noteBlockContents.entrySet()) { + try { + final Block block = world.getBlockAt( + blockLocNoteEntry.getKey().x + x_offset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof NoteBlock) { + ((NoteBlock) state).setNote(blockLocNoteEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + x_offset) + "," + + blockLocNoteEntry + .getKey().y + "," + ( + blockLocNoteEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + x_offset) + "," + + blockLocNoteEntry + .getKey().y + "," + ( + blockLocNoteEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocShortEntry : brewTime.entrySet()) { + try { + final Block block = world.getBlockAt( + blockLocShortEntry.getKey().x + x_offset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof BrewingStand) { + ((BrewingStand) state).setBrewingTime(blockLocShortEntry.getValue()); + } else { + PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + x_offset) + "," + + blockLocShortEntry + .getKey().y + "," + ( + blockLocShortEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + x_offset) + "," + + blockLocShortEntry + .getKey().y + "," + ( + blockLocShortEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntityTypeEntry : spawnerData.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntityTypeEntry.getKey().x + x_offset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry + .getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof CreatureSpawner) { + ((CreatureSpawner) state).setSpawnedType(blockLocEntityTypeEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + x_offset) + "," + + blockLocEntityTypeEntry + .getKey().y + "," + ( + blockLocEntityTypeEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + x_offset) + "," + + blockLocEntityTypeEntry + .getKey().y + "," + ( + blockLocEntityTypeEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocStringEntry : cmdData.entrySet()) { + try { + final Block block = world.getBlockAt( + blockLocStringEntry.getKey().x + x_offset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof CommandBlock) { + ((CommandBlock) state).setCommand(blockLocStringEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + x_offset) + "," + + blockLocStringEntry + .getKey().y + "," + ( + blockLocStringEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + x_offset) + "," + + blockLocStringEntry + .getKey().y + "," + ( + blockLocStringEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : brewingStandContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof BrewingStand) { + ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + ( + blockLocEntry.getKey().z + + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + ( + blockLocEntry.getKey().z + + z_offset)); + } + } + for (final Entry blockLocEntry : furnaceTime.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Furnace) { + final Short[] time = blockLocEntry.getValue(); + ((Furnace) state).setBurnTime(time[0]); + ((Furnace) state).setCookTime(time[1]); + } else { + PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + ( + blockLocEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + ( + blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocEntry : furnaceContents.entrySet()) { + try { + final Block block = + world.getBlockAt(blockLocEntry.getKey().x + x_offset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Furnace) { + ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } catch (IllegalArgumentException e) { + PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + x_offset) + "," + blockLocEntry + .getKey().y + "," + (blockLocEntry.getKey().z + z_offset)); + } + } + for (final Entry blockLocByteEntry : bannerBase.entrySet()) { + try { + final Block block = world.getBlockAt( + blockLocByteEntry.getKey().x + x_offset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + z_offset); + final BlockState state = block.getState(); + if (state instanceof Banner) { + final Banner banner = (Banner) state; + final DyeColor base = blockLocByteEntry.getValue(); + final List patterns = bannerPatterns.get(blockLocByteEntry.getKey()); + banner.setBaseColor(base); + banner.setPatterns(patterns); + state.update(true); + } else { + PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + x_offset) + "," + blockLocByteEntry + .getKey().y + "," + ( + blockLocByteEntry.getKey().z + z_offset)); + } + } catch (final Exception e) { + PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + x_offset) + "," + blockLocByteEntry + .getKey().y + "," + ( + blockLocByteEntry.getKey().z + z_offset)); + } + } + } + + public static void saveBlocks(final World world, int maxY, final int x, final int z, final int offset_x, final int offset_z, + boolean storeNormal) { + maxY = Math.min(255, maxY); + PlotBlock[] ids = storeNormal ? new PlotBlock[maxY + 1] : null; + for (short y = 0; y <= maxY; y++) { + final Block block = world.getBlockAt(x, y, z); + final Material id = block.getType(); + if (!id.equals(Material.AIR)) { + if (storeNormal) { + ids[y] = new PlotBlock((short) id.getId(), block.getData()); + } + try { + BlockLoc bl = new BlockLoc(x + offset_x, y, z + offset_z); + if (block.getState() instanceof InventoryHolder) { + final InventoryHolder inventoryHolder = (InventoryHolder) block.getState(); + final ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone(); + if (id == Material.CHEST) { + chestContents.put(bl, inventory); + } else if (id == Material.DISPENSER) { + dispenserContents.put(bl, inventory); + } else if (id == Material.BEACON) { + beaconContents.put(bl, inventory); + } else if (id == Material.DROPPER) { + dropperContents.put(bl, inventory); + } else if (id == Material.HOPPER) { + hopperContents.put(bl, inventory); + } else if (id == Material.BREWING_STAND) { + final BrewingStand brewingStand = (BrewingStand) inventoryHolder; + final short time = (short) brewingStand.getBrewingTime(); + if (time > 0) { + brewTime.put(bl, time); + } + final ItemStack[] invBre = brewingStand.getInventory().getContents().clone(); + brewingStandContents.put(bl, invBre); + } else if (id == Material.FURNACE || id == Material.BURNING_FURNACE) { + final Furnace furnace = (Furnace) inventoryHolder; + final short burn = furnace.getBurnTime(); + final short cook = furnace.getCookTime(); + final ItemStack[] invFur = furnace.getInventory().getContents().clone(); + furnaceContents.put(bl, invFur); + if (cook != 0) { + furnaceTime.put(bl, new Short[]{burn, cook}); + } + } + } else if (block.getState() instanceof CreatureSpawner) { + final CreatureSpawner spawner = (CreatureSpawner) block.getState(); + final EntityType type = spawner.getSpawnedType(); + if (type != null) { + spawnerData.put(bl, type); + } + } else if (block.getState() instanceof CommandBlock) { + final CommandBlock cmd = (CommandBlock) block.getState(); + final String string = cmd.getCommand(); + if (string != null && !string.isEmpty()) { + cmdData.put(bl, string); + } + } else if (block.getState() instanceof NoteBlock) { + final NoteBlock noteBlock = (NoteBlock) block.getState(); + final Note note = noteBlock.getNote(); + noteBlockContents.put(bl, note); + } else if (block.getState() instanceof Jukebox) { + final Jukebox jukebox = (Jukebox) block.getState(); + final Material playing = jukebox.getPlaying(); + if (playing != null) { + jukeDisc.put(bl, playing); + } + } else if (block.getState() instanceof Skull) { + final Skull skull = (Skull) block.getState(); + final String o = skull.getOwner(); + final byte skulltype = getOrdinal(SkullType.values(), skull.getSkullType()); + skull.getRotation(); + final short rot = getOrdinal(BlockFace.values(), skull.getRotation()); + skullData.put(bl, new Object[]{o, rot, skulltype}); + } else if (block.getState() instanceof Banner) { + final Banner banner = (Banner) block.getState(); + final DyeColor base = banner.getBaseColor(); + bannerBase.put(bl, base); + bannerPatterns.put(bl, banner.getPatterns()); + + } + } catch (final Exception e) { + PS.debug("------------ FAILED TO DO SOMETHING --------"); + e.printStackTrace(); + PS.debug("------------ but we caught it ^ --------"); + } + } + } + final PlotLoc loc = new PlotLoc(x, z); + allblocks.put(loc, ids); + } + + private static byte getOrdinal(final Object[] list, final Object value) { + for (byte i = 0; i < list.length; i++) { + if (list[i].equals(value)) { + return i; + } + } + return 0; + } + + public static void swapChunk(final World world1, final World world2, final Chunk pos1, final Chunk pos2, final RegionWrapper r1, + final RegionWrapper r2) { + initMaps(); + final int relX = r2.minX - r1.minX; + final int relZ = r2.minZ - r1.minZ; + + saveEntitiesIn(pos1, r1, relX, relZ, true); + saveEntitiesIn(pos2, r2, -relX, -relZ, true); + + final int sx = pos1.getX() << 4; + final int sz = pos1.getZ() << 4; + + String worldname1 = world1.getName(); + String worldname2 = world2.getName(); + + for (int x = Math.max(r1.minX, sx); x <= Math.min(r1.maxX, sx + 15); x++) { + for (int z = Math.max(r1.minZ, sz); z <= Math.min(r1.maxZ, sz + 15); z++) { + saveBlocks(world1, 256, sx, sz, relX, relZ, false); + for (int y = 0; y < 256; y++) { + final Block block1 = world1.getBlockAt(x, y, z); + final int id1 = block1.getTypeId(); + final byte data1 = block1.getData(); + final int xx = x + relX; + final int zz = z + relZ; + final Block block2 = world2.getBlockAt(xx, y, zz); + final int id2 = block2.getTypeId(); + final byte data2 = block2.getData(); + if (id1 == 0) { + if (id2 != 0) { + SetQueue.IMP.setBlock(worldname1, x, y, z, (short) id2, data2); + SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) 0, (byte) 0); + } + } else if (id2 == 0) { + SetQueue.IMP.setBlock(worldname1, x, y, z, (short) 0, (byte) 0); + SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) id1, data1); + } else if (id1 == id2) { + if (data1 != data2) { + block1.setData(data2); + block2.setData(data1); + } + } else { + SetQueue.IMP.setBlock(worldname1, x, y, z, (short) id2, data2); + SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) id1, data1); + } + } + } + } + while (SetQueue.IMP.forceChunkSet()) { + ; + } + restoreBlocks(world1, 0, 0); + restoreEntities(world1, 0, 0); + } + @Override public Set getChunkChunks(final String world) { Set chunks = super.getChunkChunks(world); @@ -73,7 +656,7 @@ public class BukkitChunkManager extends ChunkManager { } return chunks; } - + @Override public void regenerateChunk(final String world, final ChunkLoc loc) { final World worldObj = Bukkit.getWorld(world); @@ -92,41 +675,21 @@ public class BukkitChunkManager extends ChunkManager { } } } - - private static HashMap chestContents; - private static HashMap furnaceContents; - private static HashMap dispenserContents; - private static HashMap dropperContents; - private static HashMap brewingStandContents; - private static HashMap beaconContents; - private static HashMap hopperContents; - private static HashMap furnaceTime; - private static HashMap skullData; - private static HashMap jukeDisc; - private static HashMap brewTime; - private static HashMap spawnerData; - private static HashMap cmdData; - private static HashMap signContents; - private static HashMap noteBlockContents; - private static HashMap> bannerColors; - private static HashMap bannerBase; - private static HashSet entities; - private static HashMap allblocks; - + @Override public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - + final int relCX = relX >> 4; final int relCZ = relZ >> 4; - + final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); final World oldWorld = Bukkit.getWorld(pos1.getWorld()); final World newWorld = Bukkit.getWorld(newPos.getWorld()); final String newWorldname = newWorld.getName(); - final ArrayList chunks = new ArrayList<>(); - + final List chunks = new ArrayList<>(); + ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { @@ -134,7 +697,7 @@ public class BukkitChunkManager extends ChunkManager { final int bx = value[2]; final int bz = value[3]; - + final int tx = value[4]; final int tz = value[5]; @@ -152,86 +715,84 @@ public class BukkitChunkManager extends ChunkManager { setChunkInPlotArea(null, new RunnableVal>() { @Override public void run(PlotChunk value) { - for (int x = (bx & 15); x <= (tx & 15); x++) { - for (int z = (bz & 15); z <= (tz & 15); z++) { + for (int x = bx & 15; x <= (tx & 15); x++) { + for (int z = bz & 15; z <= (tz & 15); z++) { for (int y = 1; y < 256; y++) { Block block = c1.getBlock(x, y, z); - int id = block.getTypeId(); + Material id = block.getType(); switch (id) { - case 0: - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 30: - case 32: - case 37: - case 39: - case 40: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 51: - case 55: - case 56: - case 57: - case 58: - case 60: - case 7: - case 8: - case 9: - case 10: - case 11: - case 73: - case 74: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 121: - case 122: - case 129: - case 133: - case 165: - case 166: - case 169: - case 170: - case 172: - case 173: - case 174: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: { - value.setBlock(x, y, z, id, (byte) 0); + case AIR: + case GRASS: + case COBBLESTONE: + case GRAVEL: + case GOLD_ORE: + case IRON_ORE: + case GLASS: + case LAPIS_ORE: + case LAPIS_BLOCK: + case WEB: + case DEAD_BUSH: + case YELLOW_FLOWER: + case BROWN_MUSHROOM: + case RED_MUSHROOM: + case GOLD_BLOCK: + case IRON_BLOCK: + case BRICK: + case TNT: + case BOOKSHELF: + case MOSSY_COBBLESTONE: + case OBSIDIAN: + case FIRE: + case REDSTONE_WIRE: + case DIAMOND_ORE: + case DIAMOND_BLOCK: + case WORKBENCH: + case SOIL: + case BEDROCK: + case WATER: + case STATIONARY_WATER: + case LAVA: + case STATIONARY_LAVA: + case REDSTONE_ORE: + case GLOWING_REDSTONE_ORE: + case SNOW: + case ICE: + case SNOW_BLOCK: + case CACTUS: + case CLAY: + case SUGAR_CANE_BLOCK: + case FENCE: + case NETHERRACK: + case SOUL_SAND: + case IRON_FENCE: + case THIN_GLASS: + case MELON_BLOCK: + case MYCEL: + case NETHER_BRICK: + case NETHER_FENCE: + case ENDER_STONE: + case DRAGON_EGG: + case EMERALD_ORE: + case EMERALD_BLOCK: + case SLIME_BLOCK: + case BARRIER: + case SEA_LANTERN: + case HAY_BLOCK: + case HARD_CLAY: + case COAL_BLOCK: + case PACKED_ICE: + case DOUBLE_STONE_SLAB2: + case STONE_SLAB2: + case SPRUCE_FENCE: + case BIRCH_FENCE: + case JUNGLE_FENCE: + case DARK_OAK_FENCE: + case ACACIA_FENCE: + value.setBlock(x, y, z, id.getId(), (byte) 0); break; - } - default: { - value.setBlock(x, y, z, id, block.getData()); + default: + value.setBlock(x, y, z, id.getId(), block.getData()); break; - } } } } @@ -251,7 +812,7 @@ public class BukkitChunkManager extends ChunkManager { }, 5); return true; } - + public void saveRegion(final World world, int x1, int x2, int z1, int z2) { if (z1 > z2) { final int tmp = z1; @@ -269,11 +830,11 @@ public class BukkitChunkManager extends ChunkManager { } } } - + @Override public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { final String world = pos1.getWorld(); - + final int p1x = pos1.getX(); final int p1z = pos1.getZ(); final int p2x = pos2.getX(); @@ -282,9 +843,9 @@ public class BukkitChunkManager extends ChunkManager { final int bcz = p1z >> 4; final int tcx = p2x >> 4; final int tcz = p2z >> 4; - - final ArrayList chunks = new ArrayList(); - + + final List chunks = new ArrayList<>(); + for (int x = bcx; x <= tcx; x++) { for (int z = bcz; z <= tcz; z++) { chunks.add(new ChunkLoc(x, z)); @@ -295,7 +856,7 @@ public class BukkitChunkManager extends ChunkManager { @Override public void run() { final long start = System.currentTimeMillis(); - while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < 5)) { + while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { final ChunkLoc chunk = chunks.remove(0); final int x = chunk.x; final int z = chunk.z; @@ -308,7 +869,7 @@ public class BukkitChunkManager extends ChunkManager { continue; } RegionWrapper currentPlotClear = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - if ((xxb >= p1x) && (xxt <= p2x) && (zzb >= p1z) && (zzt <= p2z)) { + if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { AugmentedUtils.bypass(ignoreAugment, new Runnable() { @Override public void run() { @@ -318,33 +879,33 @@ public class BukkitChunkManager extends ChunkManager { continue; } boolean checkX1 = false; - boolean checkX2 = false; - boolean checkZ1 = false; - boolean checkZ2 = false; - + int xxb2; - int zzb2; - int xxt2; - int zzt2; - + if (x == bcx) { xxb2 = p1x - 1; checkX1 = true; } else { xxb2 = xxb; } + boolean checkX2 = false; + int xxt2; if (x == tcx) { xxt2 = p2x + 1; checkX2 = true; } else { xxt2 = xxt; } + boolean checkZ1 = false; + int zzb2; if (z == bcz) { zzb2 = p1z - 1; checkZ1 = true; } else { zzb2 = zzb; } + boolean checkZ2 = false; + int zzt2; if (z == tcz) { zzt2 = p2z + 1; checkZ2 = true; @@ -416,7 +977,7 @@ public class BukkitChunkManager extends ChunkManager { restoreBlocks(worldObj, 0, 0); restoreEntities(worldObj, 0, 0); } - if (chunks.size() != 0) { + if (!chunks.isEmpty()) { TaskManager.runTaskLater(this, 1); } else { TaskManager.runTaskLater(whenDone, 1); @@ -425,481 +986,7 @@ public class BukkitChunkManager extends ChunkManager { }); return true; } - - public static void initMaps() { - chestContents = new HashMap<>(); - furnaceContents = new HashMap<>(); - dispenserContents = new HashMap<>(); - dropperContents = new HashMap<>(); - brewingStandContents = new HashMap<>(); - beaconContents = new HashMap<>(); - hopperContents = new HashMap<>(); - furnaceTime = new HashMap<>(); - skullData = new HashMap<>(); - brewTime = new HashMap<>(); - jukeDisc = new HashMap<>(); - spawnerData = new HashMap<>(); - noteBlockContents = new HashMap<>(); - signContents = new HashMap<>(); - cmdData = new HashMap<>(); - bannerBase = new HashMap<>(); - bannerColors = new HashMap<>(); - entities = new HashSet<>(); - allblocks = new HashMap<>(); - } - - public static boolean isIn(final RegionWrapper region, final int x, final int z) { - return ((x >= region.minX) && (x <= region.maxX) && (z >= region.minZ) && (z <= region.maxZ)); - } - - public static void saveEntitiesOut(final Chunk chunk, final RegionWrapper region) { - for (final Entity entity : chunk.getEntities()) { - final Location loc = BukkitUtil.getLocation(entity); - final int x = loc.getX(); - final int z = loc.getZ(); - if (isIn(region, x, z)) { - continue; - } - if (entity.getVehicle() != null) { - continue; - } - final EntityWrapper wrap = new EntityWrapper(entity, (short) 2); - entities.add(wrap); - } - } - - public static void saveEntitiesIn(final Chunk chunk, final RegionWrapper region) { - saveEntitiesIn(chunk, region, 0, 0, false); - } - - public static void saveEntitiesIn(final Chunk chunk, final RegionWrapper region, final int offset_x, final int offset_z, final boolean delete) { - for (final Entity entity : chunk.getEntities()) { - final Location loc = BukkitUtil.getLocation(entity); - final int x = loc.getX(); - final int z = loc.getZ(); - if (!isIn(region, x, z)) { - continue; - } - if (entity.getVehicle() != null) { - continue; - } - final EntityWrapper wrap = new EntityWrapper(entity, (short) 2); - wrap.x += offset_x; - wrap.z += offset_z; - entities.add(wrap); - if (delete) { - if (!(entity instanceof Player)) { - entity.remove(); - } - } - } - } - - public static void restoreEntities(final World world, final int x_offset, final int z_offset) { - for (final EntityWrapper entity : entities) { - try { - entity.spawn(world, x_offset, z_offset); - } catch (final Exception e) { - PS.debug("Failed to restore entity (e): " + entity.x + "," + entity.y + "," + entity.z + " : " + entity.id + " : " + EntityType.fromId(entity.id)); - e.printStackTrace(); - } - } - entities.clear(); - } - - public static void restoreBlocks(final World world, final int x_offset, final int z_offset) { - for (final BlockLoc loc : chestContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Chest) { - final Chest chest = (Chest) state; - chest.getInventory().setContents(chestContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : signContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Sign) { - final Sign sign = (Sign) state; - int i = 0; - for (final String line : signContents.get(loc)) { - sign.setLine(i, line); - i++; - } - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : dispenserContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Dispenser) { - ((Dispenser) (state)).getInventory().setContents(dispenserContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : dropperContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Dropper) { - ((Dropper) (state)).getInventory().setContents(dropperContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : beaconContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Beacon) { - ((Beacon) (state)).getInventory().setContents(beaconContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : jukeDisc.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Jukebox) { - ((Jukebox) (state)).setPlaying(Material.getMaterial(jukeDisc.get(loc))); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : skullData.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Skull) { - final Object[] data = skullData.get(loc); - if (data[0] != null) { - ((Skull) (state)).setOwner((String) data[0]); - } - if (((Integer) data[1]) != 0) { - ((Skull) (state)).setRotation(BlockFace.values()[(int) data[1]]); - } - if (((Integer) data[2]) != 0) { - ((Skull) (state)).setSkullType(SkullType.values()[(int) data[2]]); - } - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to restore skull: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : hopperContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Hopper) { - ((Hopper) (state)).getInventory().setContents(hopperContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : noteBlockContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof NoteBlock) { - ((NoteBlock) (state)).setNote(noteBlockContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : brewTime.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof BrewingStand) { - ((BrewingStand) (state)).setBrewingTime(brewTime.get(loc)); - } else { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : spawnerData.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof CreatureSpawner) { - ((CreatureSpawner) (state)).setCreatureTypeId(spawnerData.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : cmdData.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof CommandBlock) { - ((CommandBlock) (state)).setCommand(cmdData.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to restore command block: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : brewingStandContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof BrewingStand) { - ((BrewingStand) (state)).getInventory().setContents(brewingStandContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : furnaceTime.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Furnace) { - final Short[] time = furnaceTime.get(loc); - ((Furnace) (state)).setBurnTime(time[0]); - ((Furnace) (state)).setCookTime(time[1]); - } else { - PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : furnaceContents.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Furnace) { - ((Furnace) (state)).getInventory().setContents(furnaceContents.get(loc)); - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - for (final BlockLoc loc : bannerBase.keySet()) { - try { - final Block block = world.getBlockAt(loc.x + x_offset, loc.y, loc.z + z_offset); - final BlockState state = block.getState(); - if (state instanceof Banner) { - final Banner banner = (Banner) state; - final byte base = bannerBase.get(loc); - final ArrayList colors = bannerColors.get(loc); - banner.setBaseColor(DyeColor.values()[base]); - for (final Byte[] color : colors) { - banner.addPattern(new Pattern(DyeColor.getByDyeData(color[1]), PatternType.values()[color[0]])); - } - state.update(true); - } else { - PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } catch (final Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (loc.x + x_offset) + "," + (loc.y) + "," + (loc.z + z_offset)); - } - } - } - - public static void saveBlocks(final World world, int maxY, final int x, final int z, final int offset_x, final int offset_z, boolean storeNormal) { - maxY = Math.min(255, maxY); - PlotBlock[] ids = storeNormal ? new PlotBlock[maxY + 1] : null; - for (short y = 0; y <= maxY; y++) { - final Block block = world.getBlockAt(x, y, z); - final short id = (short) block.getTypeId(); - if (id != 0) { - if (storeNormal) { - ids[y] = new PlotBlock(id, block.getData()); - } - BlockLoc bl; - try { - switch (id) { - case 54: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final InventoryHolder chest = (InventoryHolder) block.getState(); - final ItemStack[] inventory = chest.getInventory().getContents().clone(); - chestContents.put(bl, inventory); - break; - case 52: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final CreatureSpawner spawner = (CreatureSpawner) block.getState(); - final String type = spawner.getCreatureTypeId(); - if ((type != null) && (type.length() != 0)) { - spawnerData.put(bl, type); - } - break; - case 137: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final CommandBlock cmd = (CommandBlock) block.getState(); - final String string = cmd.getCommand(); - if ((string != null) && (string.length() > 0)) { - cmdData.put(bl, string); - } - break; - case 63: - case 68: - case 323: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Sign sign = (Sign) block.getState(); - sign.getLines(); - signContents.put(bl, sign.getLines().clone()); - break; - case 61: - case 62: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Furnace furnace = (Furnace) block.getState(); - final short burn = furnace.getBurnTime(); - final short cook = furnace.getCookTime(); - final ItemStack[] invFur = furnace.getInventory().getContents().clone(); - furnaceContents.put(bl, invFur); - if (cook != 0) { - furnaceTime.put(bl, new Short[] { burn, cook }); - } - break; - case 23: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Dispenser dispenser = (Dispenser) block.getState(); - final ItemStack[] invDis = dispenser.getInventory().getContents().clone(); - dispenserContents.put(bl, invDis); - break; - case 158: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Dropper dropper = (Dropper) block.getState(); - final ItemStack[] invDro = dropper.getInventory().getContents().clone(); - dropperContents.put(bl, invDro); - break; - case 117: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final BrewingStand brewingStand = (BrewingStand) block.getState(); - final short time = (short) brewingStand.getBrewingTime(); - if (time > 0) { - brewTime.put(bl, time); - } - final ItemStack[] invBre = brewingStand.getInventory().getContents().clone(); - brewingStandContents.put(bl, invBre); - break; - case 25: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final NoteBlock noteBlock = (NoteBlock) block.getState(); - final Note note = noteBlock.getNote(); - noteBlockContents.put(bl, note); - break; - case 138: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Beacon beacon = (Beacon) block.getState(); - final ItemStack[] invBea = beacon.getInventory().getContents().clone(); - beaconContents.put(bl, invBea); - break; - case 84: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Jukebox jukebox = (Jukebox) block.getState(); - final Material playing = jukebox.getPlaying(); - if (playing != null) { - jukeDisc.put(bl, (short) playing.getId()); - } - break; - case 154: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Hopper hopper = (Hopper) block.getState(); - final ItemStack[] invHop = hopper.getInventory().getContents().clone(); - hopperContents.put(bl, invHop); - break; - case 397: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Skull skull = (Skull) block.getState(); - final String o = skull.getOwner(); - final byte skulltype = getOrdinal(SkullType.values(), skull.getSkullType()); - skull.getRotation(); - final short rot = getOrdinal(BlockFace.values(), skull.getRotation()); - skullData.put(bl, new Object[] { o, rot, skulltype }); - break; - case 176: - case 177: - bl = new BlockLoc(x + offset_x, y, z + offset_z); - final Banner banner = (Banner) block.getState(); - final byte base = getOrdinal(DyeColor.values(), banner.getBaseColor()); - final ArrayList types = new ArrayList<>(); - for (final Pattern pattern : banner.getPatterns()) { - types.add(new Byte[] { getOrdinal(PatternType.values(), pattern.getPattern()), pattern.getColor().getDyeData() }); - } - bannerBase.put(bl, base); - bannerColors.put(bl, types); - break; - } - } catch (final Exception e) { - PS.debug("------------ FAILED TO DO SOMETHING --------"); - e.printStackTrace(); - PS.debug("------------ but we caught it ^ --------"); - } - } - } - final PlotLoc loc = new PlotLoc(x, z); - allblocks.put(loc, ids); - } - - private static byte getOrdinal(final Object[] list, final Object value) { - for (byte i = 0; i < list.length; i++) { - if (list[i].equals(value)) { - return i; - } - } - return 0; - } - + @Override public void clearAllEntities(final Location pos1, final Location pos2) { final String world = pos1.getWorld(); @@ -911,7 +998,7 @@ public class BukkitChunkManager extends ChunkManager { for (final Entity entity : entities) { if (entity instanceof Player) { final org.bukkit.Location loc = entity.getLocation(); - if ((loc.getX() >= bx) && (loc.getX() <= tx) && (loc.getZ() >= bz) && (loc.getZ() <= tz)) { + if (loc.getX() >= bx && loc.getX() <= tx && loc.getZ() >= bz && loc.getZ() <= tz) { final Player player = (Player) entity; final PlotPlayer pp = BukkitUtil.getPlayer(player); final Plot plot = pp.getCurrentPlot(); @@ -924,18 +1011,18 @@ public class BukkitChunkManager extends ChunkManager { } } else { final org.bukkit.Location loc = entity.getLocation(); - if ((loc.getX() >= bx) && (loc.getX() <= tx) && (loc.getZ() >= bz) && (loc.getZ() <= tz)) { + if (loc.getX() >= bx && loc.getX() <= tx && loc.getZ() >= bz && loc.getZ() <= tz) { entity.remove(); } } } } - + @Override public boolean loadChunk(final String world, final ChunkLoc loc, final boolean force) { return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force); } - + @Override public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe) { if (!PS.get().isMainThread(Thread.currentThread())) { @@ -945,75 +1032,23 @@ public class BukkitChunkManager extends ChunkManager { BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe); } }); - } - else { + } else { BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe); } } - - public static void swapChunk(final World world1, final World world2, final Chunk pos1, final Chunk pos2, final RegionWrapper r1, final RegionWrapper r2) { - initMaps(); - final int relX = (r2.minX - r1.minX); - final int relZ = (r2.minZ - r1.minZ); - - saveEntitiesIn(pos1, r1, relX, relZ, true); - saveEntitiesIn(pos2, r2, -relX, -relZ, true); - - final int sx = pos1.getX() << 4; - final int sz = pos1.getZ() << 4; - - String worldname1 = world1.getName(); - String worldname2 = world2.getName(); - for (int x = Math.max(r1.minX, sx); x <= Math.min(r1.maxX, sx + 15); x++) { - for (int z = Math.max(r1.minZ, sz); z <= Math.min(r1.maxZ, sz + 15); z++) { - saveBlocks(world1, 256, sx, sz, relX, relZ, false); - for (int y = 0; y < 256; y++) { - final Block block1 = world1.getBlockAt(x, y, z); - final int id1 = block1.getTypeId(); - final byte data1 = block1.getData(); - final int xx = x + relX; - final int zz = z + relZ; - final Block block2 = world2.getBlockAt(xx, y, zz); - final int id2 = block2.getTypeId(); - final byte data2 = block2.getData(); - if (id1 == 0) { - if (id2 != 0) { - SetQueue.IMP.setBlock(worldname1, x, y, z, (short) id2, data2); - SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) 0, (byte) 0); - } - } else if (id2 == 0) { - SetQueue.IMP.setBlock(worldname1, x, y, z, (short) 0, (byte) 0); - SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) id1, data1); - } else if (id1 == id2) { - if (data1 != data2) { - block1.setData(data2); - block2.setData(data1); - } - } else { - SetQueue.IMP.setBlock(worldname1, x, y, z, (short) id2, data2); - SetQueue.IMP.setBlock(worldname2, xx, y, zz, (short) id1, data1); - } - } - } - } - while (SetQueue.IMP.forceChunkSet()); - restoreBlocks(world1, 0, 0); - restoreEntities(world1, 0, 0); - } - @Override public void swap(final Location bot1, final Location top1, final Location bot2, final Location top2, final Runnable whenDone) { final RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); final RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); final World world1 = Bukkit.getWorld(bot1.getWorld()); final World world2 = Bukkit.getWorld(bot2.getWorld()); - + final int relX = bot2.getX() - bot1.getX(); final int relZ = bot2.getZ() - bot1.getZ(); - - for (int x = bot1.getX() >> 4; x <= (top1.getX() >> 4); x++) { - for (int z = bot1.getZ() >> 4; z <= (top1.getZ() >> 4); z++) { + + for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) { + for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) { final Chunk chunk1 = world1.getChunkAt(x, z); final Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4)); swapChunk(world1, world2, chunk1, chunk2, region1, region2); @@ -1021,39 +1056,39 @@ public class BukkitChunkManager extends ChunkManager { } TaskManager.runTaskLater(whenDone, 1); } - + @Override public int[] countEntities(final Plot plot) { - final int[] count = new int[6]; PlotArea area = plot.getArea(); final World world = BukkitUtil.getWorld(area.worldname); - + final Location bot = plot.getBottomAbs(); final Location top = plot.getTopAbs(); final int bx = bot.getX() >> 4; final int bz = bot.getZ() >> 4; - + final int tx = top.getX() >> 4; final int tz = top.getZ() >> 4; - - final int size = (tx - bx) << 4; - - final HashSet chunks = new HashSet<>(); + + final int size = tx - bx << 4; + + final Set chunks = new HashSet<>(); for (int X = bx; X <= tx; X++) { for (int Z = bz; Z <= tz; Z++) { chunks.add(world.getChunkAt(X, Z)); } } - + boolean doWhole = false; List entities = null; if (size > 200) { entities = world.getEntities(); - if (entities.size() < (16 + ((size * size) / 64))) { + if (entities.size() < 16 + size * size / 64) { doWhole = true; } } - + + final int[] count = new int[6]; if (doWhole) { for (final Entity entity : entities) { final org.bukkit.Location loc = entity.getLocation(); @@ -1061,7 +1096,7 @@ public class BukkitChunkManager extends ChunkManager { if (chunks.contains(chunk)) { final int X = chunk.getX(); final int Z = chunk.getX(); - if ((X > bx) && (X < tx) && (Z > bz) && (Z < tz)) { + if (X > bx && X < tx && Z > bz && Z < tz) { count(count, entity); } else { Plot other = area.getPlot(BukkitUtil.getLocation(loc)); @@ -1077,7 +1112,7 @@ public class BukkitChunkManager extends ChunkManager { final int Z = chunk.getX(); final Entity[] ents = chunk.getEntities(); for (final Entity entity : ents) { - if ((X == bx) || (X == tx) || (Z == bz) || (Z == tz)) { + if (X == bx || X == tx || Z == bz || Z == tz) { Plot other = area.getPlot(BukkitUtil.getLocation(entity)); if (plot.equals(other)) { count(count, entity); @@ -1090,13 +1125,12 @@ public class BukkitChunkManager extends ChunkManager { } return count; } - + private void count(final int[] count, final Entity entity) { switch (entity.getType()) { - case PLAYER: { + case PLAYER: // not valid return; - } case SMALL_FIREBALL: case FIREBALL: case DROPPED_ITEM: @@ -1105,13 +1139,11 @@ public class BukkitChunkManager extends ChunkManager { case SPLASH_POTION: case SNOWBALL: case ENDER_PEARL: - case ARROW: { + case ARROW: // projectile - } case PRIMED_TNT: - case FALLING_BLOCK: { - // Block entities - } + case FALLING_BLOCK: + // Block entities case ENDER_CRYSTAL: case COMPLEX_PART: case FISHING_HOOK: @@ -1122,16 +1154,14 @@ public class BukkitChunkManager extends ChunkManager { case WEATHER: case LIGHTNING: case WITHER_SKULL: - case UNKNOWN: { + case UNKNOWN: // non moving / unremovable break; - } case ITEM_FRAME: case PAINTING: - case ARMOR_STAND: { + case ARMOR_STAND: count[5]++; // misc - } case MINECART: case MINECART_CHEST: case MINECART_COMMAND: @@ -1139,10 +1169,9 @@ public class BukkitChunkManager extends ChunkManager { case MINECART_HOPPER: case MINECART_MOB_SPAWNER: case MINECART_TNT: - case BOAT: { + case BOAT: count[4]++; break; - } case RABBIT: case SHEEP: case MUSHROOM_COW: @@ -1156,12 +1185,11 @@ public class BukkitChunkManager extends ChunkManager { case CHICKEN: case COW: case SNOWMAN: - case BAT: { + case BAT: // animal count[3]++; count[1]++; break; - } case BLAZE: case CAVE_SPIDER: case CREEPER: @@ -1179,13 +1207,12 @@ public class BukkitChunkManager extends ChunkManager { case SPIDER: case WITCH: case WITHER: - case ZOMBIE: { + case ZOMBIE: // monster count[3]++; count[2]++; break; - } - default: { + default: if (entity instanceof Creature) { count[3]++; if (entity instanceof Animals) { @@ -1196,7 +1223,6 @@ public class BukkitChunkManager extends ChunkManager { } else { count[4]++; } - } } count[0]++; } diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java b/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java index 98a4037d3..d056ca211 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java @@ -1,17 +1,5 @@ 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.object.ConsolePlayer; import com.intellectualcrafters.plot.object.PlotPlayer; @@ -19,19 +7,32 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.StringComparison; import com.plotsquared.bukkit.commands.DebugUUID; 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 - * + * + */ public class BukkitCommand implements CommandExecutor, TabCompleter { - + public BukkitCommand() { MainCommand.getInstance().addCommand(new DebugUUID()); } - + @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) { return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args); } @@ -44,12 +45,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { public void sendMessage(String message) { commandSender.sendMessage(commandLabel); } - + @Override public boolean hasPermission(String perm) { return commandSender.hasPermission(commandLabel); } - + @Override public String getName() { if (commandSender.getName().equals("CONSOLE")) { @@ -63,9 +64,10 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { ConsolePlayer.getConsole().teleport(sender.getLocationFull()); return result; } - + @Override - public List onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, final String[] strings) { + public List onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, + final String[] strings) { if (!(commandSender instanceof Player)) { return null; } @@ -98,7 +100,7 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } String best = new StringComparison<>(arg, labels).getBestMatch(); tabOptions.add(best); - if (tabOptions.size() > 0) { + if (!tabOptions.isEmpty()) { return new ArrayList<>(tabOptions); } return null; diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java index 5057edb6a..2094d3448 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -1,80 +1,80 @@ 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.PlotPlayer; import com.intellectualcrafters.plot.util.EconHandler; import com.plotsquared.bukkit.object.BukkitOfflinePlayer; 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 { - + private Economy econ; private Permission perms; - + public Economy getEconomy() { init(); return econ; } - + public Permission getPermissions() { init(); return perms; } - + public boolean init() { - if ((econ == null) || (perms == null)) { + if (econ == null || perms == null) { setupPermissions(); setupEconomy(); } - return (econ != null) && (perms != null); + return econ != null && perms != null; } - + private boolean setupPermissions() { - final RegisteredServiceProvider permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); + final RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { perms = permissionProvider.getProvider(); } - return (perms != null); + return perms != null; } - + private boolean setupEconomy() { - final RegisteredServiceProvider economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + final RegisteredServiceProvider economyProvider = + Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { econ = economyProvider.getProvider(); } - return (econ != null); + return econ != null; } - + @Override public double getMoney(final PlotPlayer player) { final double bal = super.getMoney(player); if (Double.isNaN(bal)) { - return econ.getBalance(((BukkitPlayer)player).player); + return econ.getBalance(((BukkitPlayer) player).player); } return bal; } - + @Override public void withdrawMoney(final PlotPlayer player, final double amount) { - econ.withdrawPlayer(((BukkitPlayer)player).player, amount); + econ.withdrawPlayer(((BukkitPlayer) player).player, amount); } - + @Override public void depositMoney(final PlotPlayer player, final double amount) { - econ.depositPlayer(((BukkitPlayer)player).player, amount); + econ.depositPlayer(((BukkitPlayer) player).player, amount); } - + @Override public void depositMoney(final OfflinePlotPlayer player, final double amount) { econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); } - + @Override public void setPermission(final String world, final String player, final String perm, final boolean value) { if (value) { @@ -83,7 +83,7 @@ public class BukkitEconHandler extends EconHandler { perms.playerRemove(world, player, perm); } } - + @Override public boolean hasPermission(final String world, final String player, final String perm) { return perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java b/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java index d8f7f42f6..5ba42b7b9 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java @@ -34,97 +34,94 @@ import java.util.ArrayList; import java.util.UUID; public class BukkitEventUtil extends EventUtil { - + public Player getPlayer(final PlotPlayer player) { if (player instanceof BukkitPlayer) { return ((BukkitPlayer) player).player; } return null; } - + public boolean callEvent(final Event event) { Bukkit.getServer().getPluginManager().callEvent(event); - if (event instanceof Cancellable) { - return !((Cancellable) event).isCancelled(); - } - return true; + return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); } - + @Override public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto) { return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); } - + @Override public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot) { return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); } - + @Override public boolean callClear(final Plot plot) { return callEvent(new PlotClearEvent(plot)); } - + @Override public void callDelete(final Plot plot) { callEvent(new PlotDeleteEvent(plot)); } - + @Override public boolean callFlagAdd(final Flag flag, final Plot plot) { return callEvent(new PlotFlagAddEvent(flag, plot)); } - + @Override public boolean callFlagRemove(final Flag flag, final Plot plot) { return callEvent(new PlotFlagRemoveEvent(flag, plot)); } - + @Override public boolean callMerge(final Plot plot, final ArrayList plots) { return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getArea().worldname), plot, plots)); } - + @Override public boolean callUnlink(final PlotArea area, final ArrayList plots) { return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); } - + @Override public void callEntry(final PlotPlayer player, final Plot plot) { callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); } - + @Override public void callLeave(final PlotPlayer player, final Plot plot) { callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); } - + @Override public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); } - + @Override public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); } - + @Override public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); } - + @Override public boolean callFlagRemove(final Flag flag, final PlotCluster cluster) { return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); } - + @Override public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating) { final PlotRateEvent event = new PlotRateEvent(player, rating, plot); Bukkit.getServer().getPluginManager().callEvent(event); return event.getRating(); } - + } diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java b/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java index 84c324dbf..9fb483a4d 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -1,18 +1,5 @@ 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.object.Location; 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.MathMan; 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 { - + @Override public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal whenDone) { // 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() { @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 public Biome getBiome(final int a, final int b) { return null; } }; - + 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 bot = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1); -// final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id); - + + // final Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.type).add(1, 0, 1); + // final Location top = MainUtil.getPlotTopLoc(plot.world, plot.type); + final int bx = bot.getX(); final int bz = bot.getZ(); final int tx = top.getX(); @@ -76,12 +76,12 @@ public class BukkitHybridUtils extends HybridUtils { MainUtil.initCache(); final int width = (tx - bx) + 1; final int length = (tz - bz) + 1; - + System.gc(); System.gc(); final short[][][] oldblocks = new short[256][width][length]; final short[][][] newblocks = new short[256][width][length]; - + final Runnable run = new Runnable() { @Override public void run() { @@ -123,7 +123,7 @@ public class BukkitHybridUtils extends HybridUtils { oldblocks[y][x][z] = result[i][j]; } } - + } }, new Runnable() { @Override @@ -172,7 +172,7 @@ public class BukkitHybridUtils extends HybridUtils { faces[i]++; } } - + final Material material = Material.getMaterial(now); final Class md = material.getData(); if (md.equals(Directional.class)) { @@ -189,7 +189,7 @@ public class BukkitHybridUtils extends HybridUtils { } // analyze plot // put in analysis obj - + // run whenDone final PlotAnalysis analysis = new PlotAnalysis(); analysis.changes = (int) (MathMan.getMean(changes) * 100); @@ -197,7 +197,7 @@ public class BukkitHybridUtils extends HybridUtils { analysis.data = (int) (MathMan.getMean(data) * 100); analysis.air = (int) (MathMan.getMean(air) * 100); analysis.variety = (int) (MathMan.getMean(variety) * 100); - + analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes)); analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces)); analysis.data_sd = (int) (MathMan.getSD(data, analysis.data)); @@ -211,13 +211,13 @@ public class BukkitHybridUtils extends HybridUtils { }); } }, 5); - + } }; System.gc(); MainUtil.initCache(); ChunkManager.chunkTask(bot, top, new RunnableVal() { - + @Override public void run(int[] value) { final int X = value[0]; @@ -247,10 +247,10 @@ public class BukkitHybridUtils extends HybridUtils { } else { maxZ = 16; } - + final int cbx = X << 4; final int cbz = Z << 4; - + final int xb = (cbx) - bx; final int zb = (cbz) - bz; for (int x = minX; x <= maxX; x++) { @@ -276,9 +276,10 @@ public class BukkitHybridUtils extends HybridUtils { } }); } - + @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); int count = 0; for (int y = y1; y <= y2; y++) { @@ -301,7 +302,7 @@ public class BukkitHybridUtils extends HybridUtils { } return count; } - + @Override 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); diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java b/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java index cfc15b5a5..7f5a4e9b6 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -1,8 +1,10 @@ package com.plotsquared.bukkit.util; -import java.util.ArrayList; -import java.util.List; - +import com.intellectualcrafters.plot.object.PlotInventory; +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.ChatColor; import org.bukkit.event.inventory.InventoryType; @@ -12,72 +14,11 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; -import com.intellectualcrafters.plot.object.PlotInventory; -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 java.util.ArrayList; +import java.util.List; 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 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) { if (item == null) { return null; @@ -103,10 +44,68 @@ public class BukkitInventoryUtil extends InventoryUtil { } 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 itemLore = meta.getLore(); + lore = itemLore.toArray(new String[itemLore.size()]); + } + } + return new PlotItemStack(id, data, amount, name, lore); + } + @Override public PlotItemStack[] getItems(final PlotPlayer player) { - final BukkitPlayer bp = ((BukkitPlayer) player); + final BukkitPlayer bp = (BukkitPlayer) player; final PlayerInventory inv = bp.player.getInventory(); final PlotItemStack[] items = new PlotItemStack[36]; for (int i = 0; i < 36; i++) { @@ -114,14 +113,14 @@ public class BukkitInventoryUtil extends InventoryUtil { } return items; } - + @Override public boolean isOpen(final PlotInventory inv) { if (!inv.isOpen()) { return false; } - final BukkitPlayer bp = ((BukkitPlayer) inv.player); + final BukkitPlayer bp = (BukkitPlayer) inv.player; 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; } } diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java b/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java index 20ac1cc98..92a192052 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java @@ -1,38 +1,39 @@ 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.PlotPlayer; import com.intellectualcrafters.plot.util.ChatManager; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; public class BukkitPlainChatManager extends ChatManager> { - + @Override public List builder() { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public void color(final PlotMessage m, final String color) { final List parts = m.$(this); parts.get(parts.size() - 1).insert(0, color); } - + @Override - public void tooltip(final PlotMessage m, final PlotMessage... tooltips) {} - + public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { + } + @Override - public void command(final PlotMessage m, final String command) {} - + public void command(final PlotMessage m, final String command) { + } + @Override public void text(final PlotMessage m, final String text) { m.$(this).add(new StringBuilder(ChatColor.stripColor(text))); } - + @Override public void send(final PlotMessage m, final PlotPlayer player) { final StringBuilder built = new StringBuilder(); @@ -41,8 +42,9 @@ public class BukkitPlainChatManager extends ChatManager> { } player.sendMessage(built.toString()); } - + @Override - public void suggest(final PlotMessage m, final String command) {} - + public void suggest(final PlotMessage m, final String command) { + } + } diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java b/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java index 8bfa607e8..f697dacc6 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java @@ -20,20 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// 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.CompoundTag; 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.TaskManager; 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 - * + * + + */ public class BukkitSchematicHandler extends SchematicHandler { - + @Override public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { // async @@ -66,7 +67,7 @@ public class BukkitSchematicHandler extends SchematicHandler { Location[] corners = MainUtil.getCorners(world, regions); final Location bot = corners[0]; final Location top = corners[1]; - + final int width = (top.getX() - bot.getX()) + 1; final int height = (top.getY() - bot.getY()) + 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("WEOffsetZ", new IntTag("WEOffsetZ", 0)); // Arrays of data types - final List tileEntities = new ArrayList(); + final List tileEntities = new ArrayList<>(); final byte[] blocks = new byte[width * height * length]; final byte[] blockData = new byte[width * height * length]; // Queue @@ -91,7 +92,7 @@ public class BukkitSchematicHandler extends SchematicHandler { TaskManager.runTask(new Runnable() { @Override public void run() { - if (queue.size() == 0) { + if (queue.isEmpty()) { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { @@ -124,7 +125,7 @@ public class BukkitSchematicHandler extends SchematicHandler { final int sy = pos1.getY(); final int ey = pos2.getY(); // Generate list of chunks - final ArrayList chunks = new ArrayList(); + final ArrayList chunks = new ArrayList<>(); for (int x = bcx; x <= tcx; x++) { for (int z = bcz; z <= tcz; z++) { chunks.add(new ChunkLoc(x, z)); @@ -136,7 +137,7 @@ public class BukkitSchematicHandler extends SchematicHandler { @Override public void run() { final long start = System.currentTimeMillis(); - while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < 20)) { + while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < 20)) { // save schematics final ChunkLoc chunk = chunks.remove(0); final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); @@ -149,7 +150,7 @@ public class BukkitSchematicHandler extends SchematicHandler { int zzb = Z << 4; int xxt = xxb + 15; int zzt = zzb + 15; - + if (X == bcx) { xxb = p1x; } @@ -289,7 +290,7 @@ public class BukkitSchematicHandler extends SchematicHandler { for (final Entry entry : rawTag.getValue().entrySet()) { 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("y", new IntTag("y", y)); 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 - // Especially since the most likely reason beyond this range is modded servers in which the blocks have NBT - // if (id > 255) { + // Especially since the most likely reason beyond this range is modded servers in which the blocks + // have NBT + // if (type > 255) { // if (addBlocks == null) { // 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; } } } } - if (chunks.size() != 0) { + if (!chunks.isEmpty()) { TaskManager.runTaskLater(this, 1); } else { regionTask.run(); @@ -327,7 +331,7 @@ public class BukkitSchematicHandler extends SchematicHandler { } }); } - + @Override public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) { new StateWrapper(ct).restoreTag(x, y, z, schem); diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java index 8df61640e..03a29b9d4 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -1,18 +1,5 @@ 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.file.YamlConfiguration; 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.util.SetupUtils; 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 { - + @Override public void updateGenerators() { - if (SetupUtils.generators.size() > 0) { + if (!SetupUtils.generators.isEmpty()) { return; } final String testWorld = "CheckingPlotSquaredGenerator"; @@ -48,7 +47,7 @@ public class BukkitSetupUtils extends SetupUtils { } } } - + @Override public String setupWorld(final SetupObject object) { SetupUtils.manager.updateGenerators(); @@ -127,8 +126,10 @@ public class BukkitSetupUtils extends SetupUtils { e.printStackTrace(); } if (object.setupGenerator != null) { - if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); + if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core") + .isEnabled()) { + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); setGenerator(world, object.setupGenerator); if (Bukkit.getWorld(world) != null) { return world; @@ -147,7 +148,8 @@ public class BukkitSetupUtils extends SetupUtils { Bukkit.createWorld(wc); setGenerator(world, object.setupGenerator); } 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"); if (Bukkit.getWorld(world) != null) { return world; @@ -163,9 +165,9 @@ public class BukkitSetupUtils extends SetupUtils { } return object.world; } - + 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; } final File file = new File("bukkit.yml").getAbsoluteFile(); @@ -177,10 +179,10 @@ public class BukkitSetupUtils extends SetupUtils { e.printStackTrace(); } } - + @Override public String getGenerator(final PlotArea plotworld) { - if (SetupUtils.generators.size() == 0) { + if (SetupUtils.generators.isEmpty()) { updateGenerators(); } final World world = Bukkit.getWorld(plotworld.worldname); diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java b/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java index 252ae7e72..e3b2dfb91 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java @@ -1,41 +1,41 @@ package com.plotsquared.bukkit.util; -import org.bukkit.Bukkit; - import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.BukkitMain; +import org.bukkit.Bukkit; public class BukkitTaskManager extends TaskManager { + @Override public int taskRepeat(final Runnable r, final int interval) { return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval); } - + @SuppressWarnings("deprecation") @Override public int taskRepeatAsync(final Runnable r, final int interval) { return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval); } - + @Override public void taskAsync(final Runnable r) { BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId(); } - + @Override public void task(final Runnable r) { BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId(); } - + @Override public void taskLater(final Runnable r, final int delay) { BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId(); } - + @Override public void taskLaterAsync(final Runnable r, final int delay) { BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay); } - + @Override public void cancelTask(final int task) { if (task != -1) { diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 87d805a4a..a83e963af 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -1,8 +1,17 @@ package com.plotsquared.bukkit.util; -import java.util.Arrays; -import java.util.List; - +import com.intellectualcrafters.plot.object.Location; +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.Material; import org.bukkit.OfflinePlayer; @@ -23,26 +32,17 @@ import org.bukkit.material.Tree; import org.bukkit.material.WoodenStep; import org.bukkit.material.Wool; -import com.intellectualcrafters.plot.object.Location; -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 java.util.Arrays; +import java.util.List; public class BukkitUtil extends WorldUtil { + private static String lastString = null; private static World lastWorld = null; - + private static Player lastPlayer = null; private static PlotPlayer lastPlotPlayer = null; - + public static void removePlayer(final String plr) { lastPlayer = null; lastPlotPlayer = null; @@ -56,7 +56,7 @@ public class BukkitUtil extends WorldUtil { player.loadData(); return new BukkitPlayer(player, true); } - + public static PlotPlayer getPlayer(final Player player) { if (player == lastPlayer) { return lastPlotPlayer; @@ -71,15 +71,15 @@ public class BukkitUtil extends WorldUtil { lastPlayer = player; return lastPlotPlayer; } - + 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())); } - + public static org.bukkit.Location getLocation(final Location loc) { return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()); } - + public static World getWorld(final String string) { if (StringMan.isEqual(string, lastString)) { if (lastWorld != null) { @@ -91,36 +91,37 @@ public class BukkitUtil extends WorldUtil { lastWorld = world; return world; } - + public static String getWorld(final Entity entity) { return entity.getWorld().getName(); } - + public static List getEntities(final String worldname) { return getWorld(worldname).getEntities(); } - + public static Location getLocation(final Entity entity) { final org.bukkit.Location loc = entity.getLocation(); final String world = loc.getWorld().getName(); return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } - + public static Location getLocationFull(final Entity entity) { 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 public boolean isWorld(final String world) { return getWorld(world) != null; } - + @Override public String getBiome(final String world, final int x, final int z) { return getWorld(world).getBiome(x, z).name(); } - + @Override public void setSign(final String worldname, final int x, final int y, final int z, final String[] lines) { final World world = getWorld(worldname); @@ -128,7 +129,7 @@ public class BukkitUtil extends WorldUtil { // block.setType(Material.AIR); block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); final BlockState blockstate = block.getState(); - if ((blockstate instanceof Sign)) { + if (blockstate instanceof Sign) { final Sign sign = (Sign) blockstate; for (int i = 0; i < lines.length; i++) { sign.setLine(i, lines[i]); @@ -142,7 +143,7 @@ public class BukkitUtil extends WorldUtil { }, 20); } } - + @Override public String[] getSign(final Location loc) { final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ()); @@ -154,18 +155,18 @@ public class BukkitUtil extends WorldUtil { } return null; } - + @Override public Location getSpawn(final String world) { final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); } - + @Override public int getHeighestBlock(final String world, final int x, final int z) { return getWorld(world).getHighestBlockAt(x, z).getY(); } - + @Override public int getBiomeFromString(final String biomeStr) { try { @@ -178,7 +179,7 @@ public class BukkitUtil extends WorldUtil { return -1; } } - + @Override public String[] getBiomeList() { final Biome[] biomes = Biome.values(); @@ -188,7 +189,7 @@ public class BukkitUtil extends WorldUtil { } return list; } - + @Override public boolean addItems(final String worldname, final PlotItem items) { final World world = getWorld(worldname); @@ -197,8 +198,8 @@ public class BukkitUtil extends WorldUtil { return false; } final BlockState state = block.getState(); - if ((state != null) && (state instanceof InventoryHolder)) { - final InventoryHolder holder = ((InventoryHolder) state); + if (state instanceof InventoryHolder) { + final InventoryHolder holder = (InventoryHolder) state; final Inventory inv = holder.getInventory(); for (int i = 0; i < items.id.length; 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; } - + @Override public boolean isBlockSolid(final PlotBlock block) { try { final Material material = Material.getMaterial(block.id); if (material.isBlock() && material.isSolid() && !material.hasGravity()) { final Class data = material.getData(); - if ((data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()) - || data.equals(Tree.class) - || data.equals(Sandstone.class) - || data.equals(Wool.class) - || data.equals(Step.class) - || data.equals(WoodenStep.class)) { + if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding() + || data.equals(Tree.class) + || data.equals(Sandstone.class) + || data.equals(Wool.class) + || data.equals(Step.class) + || data.equals(WoodenStep.class)) { switch (material) { case NOTE_BLOCK: - case MOB_SPAWNER: { + case MOB_SPAWNER: return false; - } default: return true; } @@ -237,7 +237,7 @@ public class BukkitUtil extends WorldUtil { return false; } } - + @Override public String getClosestMatchingName(final PlotBlock block) { try { @@ -246,16 +246,15 @@ public class BukkitUtil extends WorldUtil { return null; } } - + @Override public StringComparison.ComparisonResult getClosestBlock(String name) { try { final Material material = Material.valueOf(name.toUpperCase()); return new StringComparison().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0)); - } catch (Exception e) {} + } catch (IllegalArgumentException e) { + } try { - double match; - short id; byte data; final String[] split = name.split(":"); if (split.length == 2) { @@ -264,22 +263,25 @@ public class BukkitUtil extends WorldUtil { } else { data = 0; } + double match; + short id; if (MathMan.isInteger(split[0])) { id = Short.parseShort(split[0]); match = 0; } else { - final StringComparison.ComparisonResult comparison = new StringComparison(name, Material.values()).getBestMatchAdvanced(); + final StringComparison.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); match = comparison.match; id = (short) comparison.best.getId(); } final PlotBlock block = new PlotBlock(id, data); - final StringComparison outer = new StringComparison(); + final StringComparison outer = new StringComparison<>(); return outer.new ComparisonResult(match, block); - - } catch (final Exception e) {} + + } catch (NumberFormatException e) { + } return null; } - + @Override public void setBiomes(final String worldname, RegionWrapper region, final String biomeStr) { final World world = getWorld(worldname); @@ -290,7 +292,7 @@ public class BukkitUtil extends WorldUtil { } } } - + @Override public PlotBlock getBlock(final Location loc) { final World world = getWorld(loc.getWorld()); @@ -300,7 +302,7 @@ public class BukkitUtil extends WorldUtil { } return new PlotBlock((short) block.getTypeId(), block.getData()); } - + @Override public String getMainWorld() { return Bukkit.getWorlds().get(0).getName(); diff --git a/src/main/java/com/plotsquared/bukkit/util/Metrics.java b/src/main/java/com/plotsquared/bukkit/util/Metrics.java index ce26cb0c4..6cc3d2fae 100644 --- a/src/main/java/com/plotsquared/bukkit/util/Metrics.java +++ b/src/main/java/com/plotsquared/bukkit/util/Metrics.java @@ -20,6 +20,15 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// 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.ByteArrayOutputStream; import java.io.File; @@ -41,17 +50,8 @@ import java.util.UUID; import java.util.logging.Level; 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 { + /** * The current revision number */ @@ -85,7 +85,7 @@ public class Metrics { */ private final File configurationFile; /** - * Unique server id + * Unique server type */ private final String guid; /** @@ -100,7 +100,7 @@ public class Metrics { * The scheduled task */ private volatile BukkitTask task = null; - + public Metrics(final Plugin plugin) throws IOException { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); @@ -122,7 +122,7 @@ public class Metrics { guid = configuration.getString("guid"); debug = configuration.getBoolean("debug", false); } - + /** * GZip compress a string of bytes * @@ -142,12 +142,13 @@ public class Metrics { if (gzos != null) { try { gzos.close(); - } catch (final IOException ignore) {} + } catch (final IOException ignore) { + } } } return baos.toByteArray(); } - + /** * Appends a json encoded key/value pair to the given string builder. * @@ -157,7 +158,7 @@ public class Metrics { * * @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; try { if (value.equals("0") || !value.endsWith("0")) { @@ -178,7 +179,7 @@ public class Metrics { json.append(escapeJSON(value)); } } - + /** * Escape a string to create a valid JSON string * @@ -222,7 +223,7 @@ public class Metrics { builder.append('"'); return builder.toString(); } - + /** * Encode text as UTF-8 * @@ -233,7 +234,7 @@ public class Metrics { private static String urlEncode(final String text) throws UnsupportedEncodingException { 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 * website. Plotters can be added to the graph object returned. @@ -253,7 +254,7 @@ public class Metrics { // and return back return graph; } - + /** * 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); } - + /** * 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 @@ -286,7 +287,7 @@ public class Metrics { // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; - + @Override public void run() { try { @@ -297,7 +298,7 @@ public class Metrics { // Disable Task, if it is running and the // server // owner decided to opt-out - if (isOptOut() && (task != null)) { + if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering @@ -330,7 +331,7 @@ public class Metrics { return true; } } - + /** * Has the server owner denied plugin metrics? * @@ -355,7 +356,7 @@ public class Metrics { 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. * @@ -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. * @@ -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 * @@ -417,7 +418,7 @@ public class Metrics { // return => base/plugins/PluginMetrics/config.yml return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); } - + /** * Generic method that posts a plugin to the metrics website */ @@ -436,11 +437,12 @@ public class Metrics { int playersOnline = 0; try { 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 { - 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 // any code outside of this class / Java // Construct the post data @@ -472,7 +474,7 @@ public class Metrics { if (isPing) { appendJSONPair(json, "ping", "1"); } - if (graphs.size() > 0) { + if (!graphs.isEmpty()) { synchronized (graphs) { json.append(','); json.append('"'); @@ -526,16 +528,15 @@ public class Metrics { PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); } // Write the data - final OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - // close resources - os.close(); - reader.close(); - if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) { + String response; + try (OutputStream os = connection.getOutputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + os.write(compressed); + os.flush(); + // Now read the response + response = reader.readLine(); + } + if (response == null || response.startsWith("ERR") || response.startsWith("7")) { if (response == null) { response = "null"; } else if (response.startsWith("7")) { @@ -544,7 +545,7 @@ public class Metrics { throw new IOException(response); } else { // 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) { for (final Graph graph : graphs) { 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 * @@ -565,15 +566,16 @@ public class Metrics { try { Class.forName("mineshafter.MineServer"); return true; - } catch (final Exception e) { + } catch (ClassNotFoundException e) { return false; } } - + /** * Represents a custom graph on the website */ public static class Graph { + /** * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is * rejected @@ -582,12 +584,12 @@ public class Metrics { /** * The set of plotters that are contained within this graph */ - private final Set plotters = new LinkedHashSet(); - + private final Set plotters = new LinkedHashSet<>(); + private Graph(final String name) { this.name = name; } - + /** * Gets the graph's name * @@ -596,7 +598,7 @@ public class Metrics { public String getName() { return name; } - + /** * 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) { plotters.add(plotter); } - + /** * Remove a plotter from the graph * @@ -614,7 +616,7 @@ public class Metrics { public void removePlotter(final Plotter plotter) { plotters.remove(plotter); } - + /** * Gets an unmodifiable set of the plotter objects in the graph * @@ -623,12 +625,12 @@ public class Metrics { public Set getPlotters() { return Collections.unmodifiableSet(plotters); } - + @Override public int hashCode() { return name.hashCode(); } - + @Override public boolean equals(final Object object) { if (!(object instanceof Graph)) { @@ -637,29 +639,31 @@ public class Metrics { final Graph graph = (Graph) object; return graph.name.equals(name); } - + /** * 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 */ public static abstract class Plotter { + /** * The plot's name */ private final String name; - + /** * Construct a plotter with the default plot name */ public Plotter() { this("Default"); } - + /** * Construct a plotter with a specific plot name * @@ -668,7 +672,7 @@ public class Metrics { public Plotter(final String name) { this.name = name; } - + /** * 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 @@ -677,7 +681,7 @@ public class Metrics { * @return the current value for the point to be plotted. */ public abstract int getValue(); - + /** * Get the column name for the plotted point * @@ -686,24 +690,25 @@ public class Metrics { public String getColumnName() { return name; } - + /** * Called after the website graphs have been updated */ - public void reset() {} - + public void reset() { + } + @Override public int hashCode() { return getColumnName().hashCode(); } - + @Override public boolean equals(final Object object) { if (!(object instanceof Plotter)) { return false; } final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && (plotter.getValue() == getValue()); + return plotter.name.equals(name) && plotter.getValue() == getValue(); } } } diff --git a/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java b/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java index a0f5eb211..98b830dfb 100644 --- a/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java +++ b/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java @@ -1,5 +1,20 @@ package com.plotsquared.bukkit.util; +import com.google.common.base.Splitter; +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.Lists; +import com.google.common.collect.MapMaker; +import com.google.common.io.ByteSink; +import com.google.common.io.ByteSource; +import com.google.common.io.Closeables; +import com.google.common.io.Files; +import com.google.common.primitives.Primitives; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.inventory.ItemStack; + import java.io.BufferedInputStream; import java.io.DataInput; import java.io.DataInputStream; @@ -25,69 +40,14 @@ import java.util.concurrent.ConcurrentMap; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.inventory.ItemStack; - -import com.google.common.base.Splitter; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Lists; -import com.google.common.collect.MapMaker; -import com.google.common.io.Closeables; -import com.google.common.io.Files; -import com.google.common.io.InputSupplier; -import com.google.common.io.OutputSupplier; -import com.google.common.primitives.Primitives; - public class NbtFactory { - // Convert between NBT id and the equivalent class in java + + // Convert between NBT type and the equivalent class in java private static final BiMap> NBT_CLASS = HashBiMap.create(); private static final BiMap NBT_ENUM = HashBiMap.create(); - - /** - * Whether or not to enable stream compression. - * @author Kristian - */ - public enum StreamOptions { - NO_COMPRESSION, GZIP_COMPRESSION, - } - - private enum NbtType { - TAG_END(0, Void.class), - TAG_BYTE(1, byte.class), - TAG_SHORT(2, short.class), - TAG_INT(3, int.class), - TAG_LONG(4, long.class), - TAG_FLOAT(5, float.class), - TAG_DOUBLE(6, double.class), - TAG_BYTE_ARRAY(7, byte[].class), - TAG_INT_ARRAY(11, int[].class), - TAG_STRING(8, String.class), - TAG_LIST(9, List.class), - TAG_COMPOUND(10, Map.class); - - // Unique NBT id - public final int id; - - NbtType(final int id, final Class type) { - this.id = id; - NBT_CLASS.put(id, type); - NBT_ENUM.put(id, this); - } - - private String getFieldName() { - if (this == TAG_COMPOUND) { - return "map"; - } else if (this == TAG_LIST) { - return "list"; - } else { - return "data"; - } - } - } - + // Shared instance + private static NbtFactory INSTANCE; + private final Field[] DATA_FIELD = new Field[12]; // The NBT base class private Class BASE_CLASS; private Class COMPOUND_CLASS; @@ -96,215 +56,51 @@ public class NbtFactory { private Method NBT_CREATE_TAG; private Method NBT_GET_TYPE; private Field NBT_LIST_TYPE; - private final Field[] DATA_FIELD = new Field[12]; - // CraftItemStack private Class CRAFT_STACK; private Field CRAFT_HANDLE; private Field STACK_TAG; - // Loading/saving compounds private LoadCompoundMethod LOAD_COMPOUND; private Method SAVE_COMPOUND; - - // Shared instance - private static NbtFactory INSTANCE; - /** - * Represents a root NBT compound. - *

- * All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: - *

    - *
  • Primitive types
  • - *
  • {@link java.lang.String String}
  • - *
  • {@link NbtList}
  • - *
  • {@link NbtCompound}
  • - *
- *

- * See also: - *

    - *
  • {@link NbtFactory#createCompound()}
  • - *
  • {@link NbtFactory#fromCompound(Object)}
  • - *
- * @author Kristian + * Construct an instance of the NBT factory by deducing the class of NBTBase. */ - public final class NbtCompound extends ConvertedMap { - private NbtCompound(final Object handle) { - super(handle, getDataMap(handle)); - } - - // Simplifiying access to each value - public Byte getByte(final String key, final Byte defaultValue) { - return containsKey(key) ? (Byte) get(key) : defaultValue; - } - - public Short getShort(final String key, final Short defaultValue) { - return containsKey(key) ? (Short) get(key) : defaultValue; - } - - public Integer getInteger(final String key, final Integer defaultValue) { - return containsKey(key) ? (Integer) get(key) : defaultValue; - } - - public Long getLong(final String key, final Long defaultValue) { - return containsKey(key) ? (Long) get(key) : defaultValue; - } - - public Float getFloat(final String key, final Float defaultValue) { - return containsKey(key) ? (Float) get(key) : defaultValue; - } - - public Double getDouble(final String key, final Double defaultValue) { - return containsKey(key) ? (Double) get(key) : defaultValue; - } - - public String getString(final String key, final String defaultValue) { - return containsKey(key) ? (String) get(key) : defaultValue; - } - - public byte[] getByteArray(final String key, final byte[] defaultValue) { - return containsKey(key) ? (byte[]) get(key) : defaultValue; - } - - public int[] getIntegerArray(final String key, final int[] defaultValue) { - return containsKey(key) ? (int[]) get(key) : defaultValue; - } - - /** - * Retrieve the list by the given name. - * @param key - the name of the list. - * @param createNew - whether or not to create a new list if its missing. - * @return An existing list, a new list or NULL. - */ - public NbtList getList(final String key, final boolean createNew) { - NbtList list = (NbtList) get(key); - - if ((list == null) && createNew) { - put(key, list = createList()); + private NbtFactory() { + if (BASE_CLASS == null) { + try { + // Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing + // with CraftBukkit or its derivatives. This does not work in MCPC+ however. + final ClassLoader loader = NbtFactory.class.getClassLoader(); + + final String packageName = getPackageName(); + final Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); + + // Prepare NBT + COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); + BASE_CLASS = COMPOUND_CLASS.getSuperclass(); + NBT_GET_TYPE = getMethod(0, Modifier.STATIC, BASE_CLASS, "getTypeId"); + NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, BASE_CLASS, "createTag", byte.class); + + // Prepare CraftItemStack + CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); + CRAFT_HANDLE = getField(null, CRAFT_STACK, "handle"); + STACK_TAG = getField(null, CRAFT_HANDLE.getType(), "tag"); + + // Loading/saving + final String nmsPackage = BASE_CLASS.getPackage().getName(); + initializeNMS(loader, nmsPackage); + + LOAD_COMPOUND = READ_LIMITER_CLASS != null ? new LoadMethodSkinUpdate(STREAM_TOOLS, READ_LIMITER_CLASS) : + new LoadMethodWorldUpdate(STREAM_TOOLS); + SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, STREAM_TOOLS, null, BASE_CLASS, DataOutput.class); + + } catch (final ClassNotFoundException e) { + throw new IllegalStateException("Unable to find offline player.", e); } - return list; - } - - /** - * Retrieve the map by the given name. - * @param key - the name of the map. - * @param createNew - whether or not to create a new map if its missing. - * @return An existing map, a new map or NULL. - */ - public NbtCompound getMap(final String key, final boolean createNew) { - return getMap(Collections.singletonList(key), createNew); - } - - // Done - - /** - * Set the value of an entry at a given location. - *

- * Every element of the path (except the end) are assumed to be compounds, and will - * be created if they are missing. - * @param path - the path to the entry. - * @param value - the new value of this entry. - * @return This compound, for chaining. - */ - public NbtCompound putPath(final String path, final Object value) { - final List entries = getPathElements(path); - final Map map = getMap(entries.subList(0, entries.size() - 1), true); - - map.put(entries.get(entries.size() - 1), value); - return this; - } - - /** - * Retrieve the value of a given entry in the tree. - *

- * Every element of the path (except the end) are assumed to be compounds. The - * retrieval operation will be cancelled if any of them are missing. - * @param path - path to the entry. - * @return The value, or NULL if not found. - */ - @SuppressWarnings("unchecked") - public T getPath(final String path) { - final List entries = getPathElements(path); - final NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); - - if (map != null) { - return (T) map.get(entries.get(entries.size() - 1)); - } - return null; - } - - /** - * Save the content of a NBT compound to a stream. - *

- * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. - * @param stream - the output stream. - * @param option - whether or not to compress the output. - * @throws IOException If anything went wrong. - */ - public void saveTo(final OutputSupplier stream, final StreamOptions option) throws IOException { - saveStream(this, stream, option); - } - - /** - * Retrieve a map from a given path. - * @param path - path of compounds to look up. - * @param createNew - whether or not to create new compounds on the way. - * @return The map at this location. - */ - private NbtCompound getMap(final Iterable path, final boolean createNew) { - NbtCompound current = this; - - for (final String entry : path) { - NbtCompound child = (NbtCompound) current.get(entry); - - if (child == null) { - if (!createNew) { - return null; - } - current.put(entry, child = createCompound()); - } - current = child; - } - return current; - } - - /** - * Split the path into separate elements. - * @param path - the path to split. - * @return The elements. - */ - private List getPathElements(final String path) { - return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path)); } } - - /** - * Represents a root NBT list. - * See also: - *

    - *
  • {@link NbtFactory#createList(Iterable)}}
  • - *
  • {@link NbtFactory#fromList(Object)}
  • - *
- * @author Kristian - */ - public final class NbtList extends ConvertedList { - private NbtList(final Object handle) { - super(handle, getDataList(handle)); - } - } - - /** - * Represents an object that provides a view of a native NMS class. - * @author Kristian - */ - public interface Wrapper { - /** - * Retrieve the underlying native NBT tag. - * @return The underlying NBT. - */ - Object getHandle(); - } - + /** * Retrieve or construct a shared NBT factory. * @return The factory. @@ -315,75 +111,7 @@ public class NbtFactory { } return INSTANCE; } - - /** - * Construct an instance of the NBT factory by deducing the class of NBTBase. - */ - private NbtFactory() { - if (BASE_CLASS == null) { - try { - // Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing - // with CraftBukkit or its derivatives. This does not work in MCPC+ however. - final ClassLoader loader = NbtFactory.class.getClassLoader(); - - final String packageName = getPackageName(); - final Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); - - // Prepare NBT - COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); - BASE_CLASS = COMPOUND_CLASS.getSuperclass(); - NBT_GET_TYPE = getMethod(0, Modifier.STATIC, BASE_CLASS, "getTypeId"); - NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, BASE_CLASS, "createTag", byte.class); - - // Prepare CraftItemStack - CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); - CRAFT_HANDLE = getField(null, CRAFT_STACK, "handle"); - STACK_TAG = getField(null, CRAFT_HANDLE.getType(), "tag"); - - // Loading/saving - final String nmsPackage = BASE_CLASS.getPackage().getName(); - initializeNMS(loader, nmsPackage); - - LOAD_COMPOUND = READ_LIMITER_CLASS != null ? new LoadMethodSkinUpdate(STREAM_TOOLS, READ_LIMITER_CLASS) : new LoadMethodWorldUpdate(STREAM_TOOLS); - SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, STREAM_TOOLS, null, BASE_CLASS, DataOutput.class); - - } catch (final ClassNotFoundException e) { - throw new IllegalStateException("Unable to find offline player.", e); - } - } - } - - private void initializeNMS(final ClassLoader loader, final String nmsPackage) { - try { - STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); - READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); - } catch (final ClassNotFoundException e) { - // Ignore - we will detect this later - } - } - - private String getPackageName() { - final Server server = Bukkit.getServer(); - final String name = server != null ? server.getClass().getPackage().getName() : null; - - if ((name != null) && name.contains("craftbukkit")) { - return name; - } else { - // Fallback - return "org.bukkit.craftbukkit.v1_7_R3"; - } - } - - @SuppressWarnings("unchecked") - private Map getDataMap(final Object handle) { - return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle); - } - - @SuppressWarnings("unchecked") - private List getDataList(final Object handle) { - return (List) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); - } - + /** * Construct a new NBT list of an unspecified type. * @return The NBT list. @@ -391,21 +119,21 @@ public class NbtFactory { public static NbtList createList(final Object... content) { return createList(Arrays.asList(content)); } - + /** * Construct a new NBT list of an unspecified type. * @return The NBT list. */ public static NbtList createList(final Iterable iterable) { final NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); - + // Add the content as well for (final Object obj : iterable) { list.add(obj); } return list; } - + /** * Construct a new NBT compound. *

@@ -415,7 +143,7 @@ public class NbtFactory { public static NbtCompound createCompound() { return get().new NbtCompound(INSTANCE.createNbtTag(NbtType.TAG_COMPOUND, null)); } - + /** * Construct a new NBT wrapper from a list. * @param nmsList - the NBT list. @@ -424,7 +152,7 @@ public class NbtFactory { public static NbtList fromList(final Object nmsList) { return get().new NbtList(nmsList); } - + /** * Load the content of a file from a stream. *

@@ -434,19 +162,19 @@ public class NbtFactory { * @return The decoded NBT compound. * @throws IOException If anything went wrong. */ - public static NbtCompound fromStream(final InputSupplier stream, final StreamOptions option) throws IOException { + public static NbtCompound fromStream(final ByteSource stream, final StreamOptions option) throws IOException { InputStream input = null; DataInputStream data = null; boolean suppress = true; - + try { - input = stream.getInput(); + input = stream.openStream(); data = new DataInputStream(new BufferedInputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input)); - + final NbtCompound result = fromCompound(get().LOAD_COMPOUND.loadNbt(data)); suppress = false; return result; - + } finally { if (data != null) { Closeables.close(data, suppress); @@ -455,7 +183,7 @@ public class NbtFactory { } } } - + /** * Save the content of a NBT compound to a stream. *

@@ -465,18 +193,18 @@ public class NbtFactory { * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public static void saveStream(final NbtCompound source, final OutputSupplier stream, final StreamOptions option) throws IOException { + public static void saveStream(final NbtCompound source, final ByteSink stream, final StreamOptions option) throws IOException { OutputStream output = null; DataOutputStream data = null; boolean suppress = true; - + try { - output = stream.getOutput(); + output = stream.openStream(); data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); - + invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); suppress = false; - + } finally { if (data != null) { Closeables.close(data, suppress); @@ -485,7 +213,7 @@ public class NbtFactory { } } } - + /** * Construct a new NBT wrapper from a compound. * @param nmsCompound - the NBT compund. @@ -494,7 +222,7 @@ public class NbtFactory { public static NbtCompound fromCompound(final Object nmsCompound) { return get().new NbtCompound(nmsCompound); } - + /** * Set the NBT compound tag of a given item stack. *

@@ -505,11 +233,11 @@ public class NbtFactory { public static void setItemTag(final ItemStack stack, final NbtCompound compound) { checkItemStack(stack); final Object nms = getFieldValue(get().CRAFT_HANDLE, stack); - + // Now update the tag compound setFieldValue(get().STACK_TAG, nms, compound.getHandle()); } - + /** * Construct a wrapper for an NBT tag stored (in memory) in an item stack. This is where * auxillary data such as enchanting, name and lore is stored. It does not include items @@ -523,7 +251,7 @@ public class NbtFactory { checkItemStack(stack); final Object nms = getFieldValue(get().CRAFT_HANDLE, stack); final Object tag = getFieldValue(get().STACK_TAG, nms); - + // Create the tag if it doesn't exist if (tag == null) { final NbtCompound compound = createCompound(); @@ -532,7 +260,7 @@ public class NbtFactory { } return fromCompound(tag); } - + /** * Retrieve a CraftItemStack version of the stack. * @param stack - the stack to convert. @@ -552,7 +280,7 @@ public class NbtFactory { throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); } } - + /** * Ensure that the given stack can store arbitrary NBT information. * @param stack - the stack to check. @@ -568,111 +296,7 @@ public class NbtFactory { throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information."); } } - - /** - * Convert wrapped List and Map objects into their respective NBT counterparts. - * @param value - the value of the element to create. Can be a List or a Map. - * @return The NBT element. - */ - private Object unwrapValue(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof Wrapper) { - return ((Wrapper) value).getHandle(); - - } else if (value instanceof List) { - throw new IllegalArgumentException("Can only insert a WrappedList."); - } else if (value instanceof Map) { - throw new IllegalArgumentException("Can only insert a WrappedCompound."); - - } else { - return createNbtTag(getPrimitiveType(value), value); - } - } - - /** - * Convert a given NBT element to a primitive wrapper or List/Map equivalent. - *

- * All changes to any mutable objects will be reflected in the underlying NBT element(s). - * @param nms - the NBT element. - * @return The wrapper equivalent. - */ - private Object wrapNative(final Object nms) { - if (nms == null) { - return null; - } - - if (BASE_CLASS.isAssignableFrom(nms.getClass())) { - final NbtType type = getNbtType(nms); - - // Handle the different types - switch (type) { - case TAG_COMPOUND: - return new NbtCompound(nms); - case TAG_LIST: - return new NbtList(nms); - default: - return getFieldValue(getDataField(type, nms), nms); - } - } - throw new IllegalArgumentException("Unexpected type: " + nms); - } - - /** - * Construct a new NMS NBT tag initialized with the given value. - * @param type - the NBT type. - * @param value - the value, or NULL to keep the original value. - * @return The created tag. - */ - private Object createNbtTag(final NbtType type, final Object value) { - final Object tag = invokeMethod(NBT_CREATE_TAG, null, (byte) type.id); - - if (value != null) { - setFieldValue(getDataField(type, tag), tag, value); - } - return tag; - } - - /** - * Retrieve the field where the NBT class stores its value. - * @param type - the NBT type. - * @param nms - the NBT class instance. - * @return The corresponding field. - */ - private Field getDataField(final NbtType type, final Object nms) { - if (DATA_FIELD[type.id] == null) { - DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); - } - return DATA_FIELD[type.id]; - } - - /** - * Retrieve the NBT type from a given NMS NBT tag. - * @param nms - the native NBT tag. - * @return The corresponding type. - */ - private NbtType getNbtType(final Object nms) { - final int type = (Byte) invokeMethod(NBT_GET_TYPE, nms); - return NBT_ENUM.get(type); - } - - /** - * Retrieve the nearest NBT type for a given primitive type. - * @param primitive - the primitive type. - * @return The corresponding type. - */ - private NbtType getPrimitiveType(final Object primitive) { - final NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); - - // Display the illegal value at least - if (type == null) { - throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); - } - return type; - } - + /** * Invoke a method on the given target instance using the provided parameters. * @param method - the method to invoke. @@ -687,7 +311,7 @@ public class NbtFactory { throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); } } - + private static void setFieldValue(final Field field, final Object target, final Object value) { try { field.set(target, value); @@ -695,7 +319,7 @@ public class NbtFactory { throw new RuntimeException("Unable to set " + field + " for " + target, e); } } - + private static Object getFieldValue(final Field field, final Object target) { try { return field.get(target); @@ -703,7 +327,7 @@ public class NbtFactory { throw new RuntimeException("Unable to retrieve " + field + " for " + target, e); } } - + /** * Search for the first publically and privately defined method of the given name and parameter count. * @param requireMod - modifiers that are required. @@ -714,14 +338,15 @@ public class NbtFactory { * @return The first method by this name. * @throws IllegalStateException If we cannot find this method. */ - private static Method getMethod(final int requireMod, final int bannedMod, final Class clazz, final String methodName, final Class... params) { + private static Method getMethod(final int requireMod, final int bannedMod, final Class clazz, final String methodName, + final Class... params) { for (final Method method : clazz.getDeclaredMethods()) { // Limitation: Doesn't handle overloads if (((method.getModifiers() & requireMod) == requireMod) - && ((method.getModifiers() & bannedMod) == 0) - && ((methodName == null) || method.getName().equals(methodName)) - && Arrays.equals(method.getParameterTypes(), params)) { - + && ((method.getModifiers() & bannedMod) == 0) + && ((methodName == null) || method.getName().equals(methodName)) + && Arrays.equals(method.getParameterTypes(), params)) { + method.setAccessible(true); return method; } @@ -732,7 +357,7 @@ public class NbtFactory { } throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); } - + /** * Search for the first publically and privately defined field of the given name. * @param instance - an instance of the class with the field. @@ -758,211 +383,210 @@ public class NbtFactory { } throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); } - - /** - * Represents a class for caching wrappers. - * @author Kristian - */ - private final class CachedNativeWrapper { - // Don't recreate wrapper objects - private final ConcurrentMap cache = new MapMaker().weakKeys().makeMap(); - - public Object wrap(final Object value) { - Object current = cache.get(value); - - if (current == null) { - current = wrapNative(value); - - // Only cache composite objects - if ((current instanceof ConvertedMap) || (current instanceof ConvertedList)) { - cache.put(value, current); - } - } - return current; + + private void initializeNMS(final ClassLoader loader, final String nmsPackage) { + try { + STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); + READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); + } catch (final ClassNotFoundException e) { + // Ignore - we will detect this later } } - - /** - * Represents a map that wraps another map and automatically - * converts entries of its type and another exposed type. - * @author Kristian - */ - private class ConvertedMap extends AbstractMap implements Wrapper { - private final Object handle; - private final Map original; - - private final CachedNativeWrapper cache = new CachedNativeWrapper(); - - public ConvertedMap(final Object handle, final Map original) { - this.handle = handle; - this.original = original; - } - - // For converting back and forth - protected Object wrapOutgoing(final Object value) { - return cache.wrap(value); - } - - protected Object unwrapIncoming(final Object wrapped) { - return unwrapValue(wrapped); - } - - // Modification - @Override - public Object put(final String key, final Object value) { - return wrapOutgoing(original.put(key, unwrapIncoming(value))); - } - - // Performance - @Override - public Object get(final Object key) { - return wrapOutgoing(original.get(key)); - } - - @Override - public Object remove(final Object key) { - return wrapOutgoing(original.remove(key)); - } - - @Override - public boolean containsKey(final Object key) { - return original.containsKey(key); - } - - @Override - public Set> entrySet() { - return new AbstractSet>() { - @Override - public boolean add(final Entry e) { - final String key = e.getKey(); - final Object value = e.getValue(); - - original.put(key, unwrapIncoming(value)); - return true; - } - - @Override - public int size() { - return original.size(); - } - - @Override - public Iterator> iterator() { - return ConvertedMap.this.iterator(); - } - }; - } - - private Iterator> iterator() { - final Iterator> proxy = original.entrySet().iterator(); - - return new Iterator>() { - @Override - public boolean hasNext() { - return proxy.hasNext(); - } - - @Override - public Entry next() { - final Entry entry = proxy.next(); - - return new SimpleEntry(entry.getKey(), wrapOutgoing(entry.getValue())); - } - - @Override - public void remove() { - proxy.remove(); - } - }; - } - - @Override - public Object getHandle() { - return handle; + + private String getPackageName() { + final Server server = Bukkit.getServer(); + final String name = server != null ? server.getClass().getPackage().getName() : null; + + if ((name != null) && name.contains("craftbukkit")) { + return name; + } else { + // Fallback + return "org.bukkit.craftbukkit.v1_7_R3"; } } - + + @SuppressWarnings("unchecked") + private Map getDataMap(final Object handle) { + return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle); + } + + @SuppressWarnings("unchecked") + private List getDataList(final Object handle) { + return (List) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); + } + /** - * Represents a list that wraps another list and converts elements - * of its type and another exposed type. - * @author Kristian + * Convert wrapped List and Map objects into their respective NBT counterparts. + * @param value - the value of the element to create. Can be a List or a Map. + * @return The NBT element. */ - private class ConvertedList extends AbstractList implements Wrapper { - private final Object handle; - - private final List original; - private final CachedNativeWrapper cache = new CachedNativeWrapper(); - - public ConvertedList(final Object handle, final List original) { - if (NBT_LIST_TYPE == null) { - NBT_LIST_TYPE = getField(handle, null, "type"); - } - this.handle = handle; - this.original = original; + private Object unwrapValue(final Object value) { + if (value == null) { + return null; } - - protected Object wrapOutgoing(final Object value) { - return cache.wrap(value); - } - - protected Object unwrapIncoming(final Object wrapped) { - return unwrapValue(wrapped); - } - - @Override - public Object get(final int index) { - return wrapOutgoing(original.get(index)); - } - - @Override - public int size() { - return original.size(); - } - - @Override - public Object set(final int index, final Object element) { - return wrapOutgoing(original.set(index, unwrapIncoming(element))); - } - - @Override - public void add(final int index, final Object element) { - final Object nbt = unwrapIncoming(element); - - // Set the list type if its the first element - if (size() == 0) { - setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id); - } - original.add(index, nbt); - } - - @Override - public Object remove(final int index) { - return wrapOutgoing(original.remove(index)); - } - - @Override - public boolean remove(final Object o) { - return original.remove(unwrapIncoming(o)); - } - - @Override - public Object getHandle() { - return handle; + + if (value instanceof Wrapper) { + return ((Wrapper) value).getHandle(); + + } else if (value instanceof List) { + throw new IllegalArgumentException("Can only insert a WrappedList."); + } else if (value instanceof Map) { + throw new IllegalArgumentException("Can only insert a WrappedCompound."); + + } else { + return createNbtTag(getPrimitiveType(value), value); } } - + + /** + * Convert a given NBT element to a primitive wrapper or List/Map equivalent. + *

+ * All changes to any mutable objects will be reflected in the underlying NBT element(s). + * @param nms - the NBT element. + * @return The wrapper equivalent. + */ + private Object wrapNative(final Object nms) { + if (nms == null) { + return null; + } + + if (BASE_CLASS.isAssignableFrom(nms.getClass())) { + final NbtType type = getNbtType(nms); + + // Handle the different types + switch (type) { + case TAG_COMPOUND: + return new NbtCompound(nms); + case TAG_LIST: + return new NbtList(nms); + default: + return getFieldValue(getDataField(type, nms), nms); + } + } + throw new IllegalArgumentException("Unexpected type: " + nms); + } + + /** + * Construct a new NMS NBT tag initialized with the given value. + * @param type - the NBT type. + * @param value - the value, or NULL to keep the original value. + * @return The created tag. + */ + private Object createNbtTag(final NbtType type, final Object value) { + final Object tag = invokeMethod(NBT_CREATE_TAG, null, (byte) type.id); + + if (value != null) { + setFieldValue(getDataField(type, tag), tag, value); + } + return tag; + } + + /** + * Retrieve the field where the NBT class stores its value. + * @param type - the NBT type. + * @param nms - the NBT class instance. + * @return The corresponding field. + */ + private Field getDataField(final NbtType type, final Object nms) { + if (DATA_FIELD[type.id] == null) { + DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); + } + return DATA_FIELD[type.id]; + } + + /** + * Retrieve the NBT type from a given NMS NBT tag. + * @param nms - the native NBT tag. + * @return The corresponding type. + */ + private NbtType getNbtType(final Object nms) { + final int type = (Byte) invokeMethod(NBT_GET_TYPE, nms); + return NBT_ENUM.get(type); + } + + /** + * Retrieve the nearest NBT type for a given primitive type. + * @param primitive - the primitive type. + * @return The corresponding type. + */ + private NbtType getPrimitiveType(final Object primitive) { + final NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); + + // Display the illegal value at least + if (type == null) { + throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); + } + return type; + } + + /** + * Whether or not to enable stream compression. + * @author Kristian + */ + public enum StreamOptions { + NO_COMPRESSION, GZIP_COMPRESSION, + } + + private enum NbtType { + TAG_END(0, Void.class), + TAG_BYTE(1, byte.class), + TAG_SHORT(2, short.class), + TAG_INT(3, int.class), + TAG_LONG(4, long.class), + TAG_FLOAT(5, float.class), + TAG_DOUBLE(6, double.class), + TAG_BYTE_ARRAY(7, byte[].class), + TAG_INT_ARRAY(11, int[].class), + TAG_STRING(8, String.class), + TAG_LIST(9, List.class), + TAG_COMPOUND(10, Map.class); + + // Unique NBT type + public final int id; + + NbtType(final int id, final Class type) { + this.id = id; + NBT_CLASS.put(id, type); + NBT_ENUM.put(id, this); + } + + private String getFieldName() { + if (this == TAG_COMPOUND) { + return "map"; + } else if (this == TAG_LIST) { + return "list"; + } else { + return "data"; + } + } + } + + /** + * Represents an object that provides a view of a native NMS class. + * @author Kristian + */ + public interface Wrapper { + + /** + * Retrieve the underlying native NBT tag. + * @return The underlying NBT. + */ + Object getHandle(); + } + /** * Represents a method for loading an NBT compound. * @author Kristian */ private static abstract class LoadCompoundMethod { + protected Method staticMethod; - + protected void setMethod(final Method method) { staticMethod = method; staticMethod.setAccessible(true); } - + /** * Load an NBT compound from a given stream. * @param input - the input stream. @@ -970,30 +594,32 @@ public class NbtFactory { */ public abstract Object loadNbt(final DataInput input); } - + /** * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.2 - 1.7.5 */ private static class LoadMethodWorldUpdate extends LoadCompoundMethod { + public LoadMethodWorldUpdate(final Class streamClass) { setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class)); } - + @Override public Object loadNbt(final DataInput input) { return invokeMethod(staticMethod, null, input); } } - + /** * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.8 */ private static class LoadMethodSkinUpdate extends LoadCompoundMethod { + private Object readLimiter; - + public LoadMethodSkinUpdate(final Class streamClass, final Class readLimiterClass) { setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass)); - + // Find the unlimited read limiter for (final Field field : readLimiterClass.getDeclaredFields()) { if (readLimiterClass.isAssignableFrom(field.getType())) { @@ -1005,10 +631,390 @@ public class NbtFactory { } } } - + @Override public Object loadNbt(final DataInput input) { return invokeMethod(staticMethod, null, input, readLimiter); } } + + /** + * Represents a root NBT compound. + *

+ * All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: + *

    + *
  • Primitive types
  • + *
  • {@link java.lang.String String}
  • + *
  • {@link NbtList}
  • + *
  • {@link NbtCompound}
  • + *
+ *

+ * See also: + *

    + *
  • {@link NbtFactory#createCompound()}
  • + *
  • {@link NbtFactory#fromCompound(Object)}
  • + *
+ * @author Kristian + */ + public final class NbtCompound extends ConvertedMap { + + private NbtCompound(final Object handle) { + super(handle, getDataMap(handle)); + } + + // Simplifiying access to each value + public Byte getByte(final String key, final Byte defaultValue) { + return containsKey(key) ? (Byte) get(key) : defaultValue; + } + + public Short getShort(final String key, final Short defaultValue) { + return containsKey(key) ? (Short) get(key) : defaultValue; + } + + public Integer getInteger(final String key, final Integer defaultValue) { + return containsKey(key) ? (Integer) get(key) : defaultValue; + } + + public Long getLong(final String key, final Long defaultValue) { + return containsKey(key) ? (Long) get(key) : defaultValue; + } + + public Float getFloat(final String key, final Float defaultValue) { + return containsKey(key) ? (Float) get(key) : defaultValue; + } + + public Double getDouble(final String key, final Double defaultValue) { + return containsKey(key) ? (Double) get(key) : defaultValue; + } + + public String getString(final String key, final String defaultValue) { + return containsKey(key) ? (String) get(key) : defaultValue; + } + + public byte[] getByteArray(final String key, final byte[] defaultValue) { + return containsKey(key) ? (byte[]) get(key) : defaultValue; + } + + public int[] getIntegerArray(final String key, final int[] defaultValue) { + return containsKey(key) ? (int[]) get(key) : defaultValue; + } + + /** + * Retrieve the list by the given name. + * @param key - the name of the list. + * @param createNew - whether or not to create a new list if its missing. + * @return An existing list, a new list or NULL. + */ + public NbtList getList(final String key, final boolean createNew) { + NbtList list = (NbtList) get(key); + + if ((list == null) && createNew) { + put(key, list = createList()); + } + return list; + } + + /** + * Retrieve the map by the given name. + * @param key - the name of the map. + * @param createNew - whether or not to create a new map if its missing. + * @return An existing map, a new map or NULL. + */ + public NbtCompound getMap(final String key, final boolean createNew) { + return getMap(Collections.singletonList(key), createNew); + } + + // Done + + /** + * Set the value of an entry at a given location. + *

+ * Every element of the path (except the end) are assumed to be compounds, and will + * be created if they are missing. + * @param path - the path to the entry. + * @param value - the new value of this entry. + * @return This compound, for chaining. + */ + public NbtCompound putPath(final String path, final Object value) { + final List entries = getPathElements(path); + final Map map = getMap(entries.subList(0, entries.size() - 1), true); + + map.put(entries.get(entries.size() - 1), value); + return this; + } + + /** + * Retrieve the value of a given entry in the tree. + *

+ * Every element of the path (except the end) are assumed to be compounds. The + * retrieval operation will be cancelled if any of them are missing. + * @param path - path to the entry. + * @return The value, or NULL if not found. + */ + @SuppressWarnings("unchecked") + public T getPath(final String path) { + final List entries = getPathElements(path); + final NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); + + if (map != null) { + return (T) map.get(entries.get(entries.size() - 1)); + } + return null; + } + + /** + * Save the content of a NBT compound to a stream. + *

+ * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. + * @param stream - the output stream. + * @param option - whether or not to compress the output. + * @throws IOException If anything went wrong. + */ + public void saveTo(final ByteSink stream, final StreamOptions option) throws IOException { + saveStream(this, stream, option); + } + + /** + * Retrieve a map from a given path. + * @param path - path of compounds to look up. + * @param createNew - whether or not to create new compounds on the way. + * @return The map at this location. + */ + private NbtCompound getMap(final Iterable path, final boolean createNew) { + NbtCompound current = this; + + for (final String entry : path) { + NbtCompound child = (NbtCompound) current.get(entry); + + if (child == null) { + if (!createNew) { + return null; + } + current.put(entry, child = createCompound()); + } + current = child; + } + return current; + } + + /** + * Split the path into separate elements. + * @param path - the path to split. + * @return The elements. + */ + private List getPathElements(final String path) { + return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path)); + } + } + + /** + * Represents a root NBT list. + * See also: + *

    + *
  • {@link NbtFactory#createList(Iterable)}}
  • + *
  • {@link NbtFactory#fromList(Object)}
  • + *
+ * @author Kristian + */ + public final class NbtList extends ConvertedList { + + private NbtList(final Object handle) { + super(handle, getDataList(handle)); + } + } + + /** + * Represents a class for caching wrappers. + * @author Kristian + */ + private final class CachedNativeWrapper { + + // Don't recreate wrapper objects + private final ConcurrentMap cache = new MapMaker().weakKeys().makeMap(); + + public Object wrap(final Object value) { + Object current = cache.get(value); + + if (current == null) { + current = wrapNative(value); + + // Only cache composite objects + if ((current instanceof ConvertedMap) || (current instanceof ConvertedList)) { + cache.put(value, current); + } + } + return current; + } + } + + /** + * Represents a map that wraps another map and automatically + * converts entries of its type and another exposed type. + * @author Kristian + */ + private class ConvertedMap extends AbstractMap implements Wrapper { + + private final Object handle; + private final Map original; + + private final CachedNativeWrapper cache = new CachedNativeWrapper(); + + public ConvertedMap(final Object handle, final Map original) { + this.handle = handle; + this.original = original; + } + + // For converting back and forth + protected Object wrapOutgoing(final Object value) { + return cache.wrap(value); + } + + protected Object unwrapIncoming(final Object wrapped) { + return unwrapValue(wrapped); + } + + // Modification + @Override + public Object put(final String key, final Object value) { + return wrapOutgoing(original.put(key, unwrapIncoming(value))); + } + + // Performance + @Override + public Object get(final Object key) { + return wrapOutgoing(original.get(key)); + } + + @Override + public Object remove(final Object key) { + return wrapOutgoing(original.remove(key)); + } + + @Override + public boolean containsKey(final Object key) { + return original.containsKey(key); + } + + @Override + public Set> entrySet() { + return new AbstractSet>() { + @Override + public boolean add(final Entry e) { + final String key = e.getKey(); + final Object value = e.getValue(); + + original.put(key, unwrapIncoming(value)); + return true; + } + + @Override + public int size() { + return original.size(); + } + + @Override + public Iterator> iterator() { + return ConvertedMap.this.iterator(); + } + }; + } + + private Iterator> iterator() { + final Iterator> proxy = original.entrySet().iterator(); + + return new Iterator>() { + @Override + public boolean hasNext() { + return proxy.hasNext(); + } + + @Override + public Entry next() { + final Entry entry = proxy.next(); + + return new SimpleEntry(entry.getKey(), wrapOutgoing(entry.getValue())); + } + + @Override + public void remove() { + proxy.remove(); + } + }; + } + + @Override + public Object getHandle() { + return handle; + } + } + + /** + * Represents a list that wraps another list and converts elements + * of its type and another exposed type. + * @author Kristian + */ + private class ConvertedList extends AbstractList implements Wrapper { + + private final Object handle; + + private final List original; + private final CachedNativeWrapper cache = new CachedNativeWrapper(); + + public ConvertedList(final Object handle, final List original) { + if (NBT_LIST_TYPE == null) { + NBT_LIST_TYPE = getField(handle, null, "type"); + } + this.handle = handle; + this.original = original; + } + + protected Object wrapOutgoing(final Object value) { + return cache.wrap(value); + } + + protected Object unwrapIncoming(final Object wrapped) { + return unwrapValue(wrapped); + } + + @Override + public Object get(final int index) { + return wrapOutgoing(original.get(index)); + } + + @Override + public int size() { + return original.size(); + } + + @Override + public Object set(final int index, final Object element) { + return wrapOutgoing(original.set(index, unwrapIncoming(element))); + } + + @Override + public void add(final int index, final Object element) { + final Object nbt = unwrapIncoming(element); + + // Set the list type if its the first element + if (size() == 0) { + setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id); + } + original.add(index, nbt); + } + + @Override + public Object remove(final int index) { + return wrapOutgoing(original.remove(index)); + } + + @Override + public boolean remove(final Object o) { + return original.remove(unwrapIncoming(o)); + } + + @Override + public Object getHandle() { + return handle; + } + } } diff --git a/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java index d32ab5ffc..61144ddf4 100644 --- a/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ b/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java @@ -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.makeMethod; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.UUID; - import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.UUID; + public class OfflinePlayerUtil { - + public static Player loadPlayer(final String name) { return loadPlayer(Bukkit.getOfflinePlayer(name)); } - + public static Player loadPlayer(final UUID id) { return loadPlayer(Bukkit.getOfflinePlayer(id)); } - + public static Player loadPlayer(final OfflinePlayer player) { if (player == null) { return null; @@ -36,27 +36,26 @@ public class OfflinePlayerUtil { } return loadPlayer(player.getUniqueId(), player.getName()); } - + private static Player loadPlayer(final UUID id, final String name) { final Object server = getMinecraftServer(); final Object interactManager = newPlayerInteractManager(); final Object worldServer = getWorldServer(); final Object profile = newGameProfile(id, name); final Class entityPlayerClass = getNmsClass("EntityPlayer"); - final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), - getNmsClass("PlayerInteractManager")); + final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), + getUtilClass("com.mojang.authlib.GameProfile"), + getNmsClass("PlayerInteractManager")); final Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); - final Player player = (Player) getBukkitEntity(entityPlayer); - return player; + return (Player) getBukkitEntity(entityPlayer); } - + private static Object newGameProfile(final UUID id, final String name) { final Class gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); if (gameProfileClass == null) { //Before uuids return name; } - Constructor gameProfileConstructor = null; - gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class); + Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class); if (gameProfileConstructor == null) { //Verson has string constructor gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class); return callConstructor(gameProfileConstructor, id.toString(), name); @@ -64,7 +63,7 @@ public class OfflinePlayerUtil { return callConstructor(gameProfileConstructor, id, name); } } - + private static Object newPlayerInteractManager() { final Object worldServer = getWorldServer(); final Class playerInteractClass = getNmsClass("PlayerInteractManager"); @@ -72,20 +71,20 @@ public class OfflinePlayerUtil { final Constructor c = makeConstructor(playerInteractClass, worldClass); return callConstructor(c, worldServer); } - + private static Object getWorldServer() { final Object server = getMinecraftServer(); final Class minecraftServerClass = getNmsClass("MinecraftServer"); final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); return callMethod(getWorldServer, server, 0); } - + //NMS Utils - + private static Object getMinecraftServer() { return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer()); } - + private static Entity getBukkitEntity(final Object o) { final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); return callMethod(getBukkitEntity, o); diff --git a/src/main/java/com/plotsquared/bukkit/util/ReflectionUtil.java b/src/main/java/com/plotsquared/bukkit/util/ReflectionUtil.java deleted file mode 100644 index eb5f421b4..000000000 --- a/src/main/java/com/plotsquared/bukkit/util/ReflectionUtil.java +++ /dev/null @@ -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 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 Constructor makeConstructor(final Class clazz, final Class... paramaterTypes) { - try { - return (Constructor) clazz.getConstructor(paramaterTypes); - } catch (final NoSuchMethodException ex) { - return null; - } catch (final Exception ex) { - throw new RuntimeException(ex); - } - } - - public static T callConstructor(final Constructor 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 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 Class getClass(final String name, final Class superClass) { - try { - return Class.forName(name).asSubclass(superClass); - } catch (ClassCastException | ClassNotFoundException ex) { - return null; - } - } -} diff --git a/src/main/java/com/plotsquared/bukkit/util/SendChunk.java b/src/main/java/com/plotsquared/bukkit/util/SendChunk.java index 7104134f5..a244a3c6b 100644 --- a/src/main/java/com/plotsquared/bukkit/util/SendChunk.java +++ b/src/main/java/com/plotsquared/bukkit/util/SendChunk.java @@ -32,7 +32,7 @@ import java.util.Map.Entry; */ public class SendChunk { - + // // Ref Class private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); @@ -47,13 +47,11 @@ public class SendChunk { private final RefField connection; private final RefMethod send; private final RefMethod methodInitLighting; - + /** * Constructor - * - * @throws NoSuchMethodException */ - public SendChunk() throws NoSuchMethodException { + public SendChunk() { methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); methodInitLighting = classChunk.getMethod("initLighting"); @@ -61,7 +59,7 @@ public class SendChunk { connection = classEntityPlayer.getField("playerConnection"); send = classConnection.getMethod("sendPacket", classPacket.getRealClass()); } - + public void sendChunk(final Collection input) { final HashSet chunks = new HashSet(input); final HashMap> map = new HashMap<>(); @@ -99,7 +97,7 @@ public class SendChunk { final int cz = loc.getZ() >> 4; final Player player = ((BukkitPlayer) pp).player; final Object entity = methodGetHandlePlayer.of(player).call(); - + for (final Chunk chunk : list) { final int dx = Math.abs(cx - chunk.getX()); final int dz = Math.abs(cz - chunk.getZ()); @@ -127,7 +125,8 @@ public class SendChunk { final String worldname = chunk.getWorld().getName(); PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); - PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "/level_old.dat may be corrupt (try repairing or removing these)"); + PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + + "/level_old.dat may be corrupt (try repairing or removing these)"); } } }); @@ -173,7 +172,8 @@ public class SendChunk { // String worldname = chunk.getWorld().getName(); // PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); // PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); - // PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing or removing these)"); + // PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing + // or removing these)"); // } // } // }); @@ -181,7 +181,7 @@ public class SendChunk { // // } } - + public void sendChunk(final String worldname, final List locs) { final World myworld = Bukkit.getWorld(worldname); final ArrayList chunks = new ArrayList<>(); diff --git a/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java b/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java index ccaa02a81..fec7d3240 100644 --- a/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java +++ b/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java @@ -1,19 +1,19 @@ package com.plotsquared.bukkit.util; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Iterator; - -import org.bukkit.World; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.generator.GeneratorWrapper; import com.intellectualcrafters.plot.util.SetupUtils; import com.plotsquared.bukkit.generator.BukkitAugmentedGenerator; +import org.bukkit.World; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Iterator; public class SetGenCB { + public static void setGenerator(final World world) throws Exception { SetupUtils.manager.updateGenerators(); PS.get().removePlotAreas(world.getName()); diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java b/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java index 04ec01372..939b1610a 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java @@ -1,17 +1,22 @@ package com.plotsquared.bukkit.util.block; -import java.util.Arrays; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; - import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.PlotChunk; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; import com.plotsquared.bukkit.util.BukkitUtil; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; + +import java.util.Arrays; public class FastChunk_1_8_3 extends PlotChunk { - + + public char[][] ids; + public short[] count; + public short[] air; + public short[] relight; + public int[][] biomes; + public Chunk chunk; public FastChunk_1_8_3(final ChunkWrapper chunk) { super(chunk); ids = new char[16][]; @@ -19,21 +24,13 @@ public class FastChunk_1_8_3 extends PlotChunk { air = new short[16]; relight = new short[16]; } - + @Override public Chunk getChunkAbs() { ChunkWrapper loc = getChunkWrapper(); return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z); } - - public char[][] ids; - public short[] count; - public short[] air; - public short[] relight; - public int[][] biomes; - - public Chunk chunk; - + @Override public Chunk getChunk() { if (chunk == null) { @@ -42,13 +39,13 @@ public class FastChunk_1_8_3 extends PlotChunk { } return chunk; } - + @Override public void setChunkWrapper(final ChunkWrapper loc) { super.setChunkWrapper(loc); chunk = null; } - + /** * Get the number of block changes in a specified section * @param i @@ -57,7 +54,7 @@ public class FastChunk_1_8_3 extends PlotChunk { public int getCount(final int i) { return count[i]; } - + public int getAir(final int i) { return air[i]; } @@ -82,7 +79,7 @@ public class FastChunk_1_8_3 extends PlotChunk { } return total; } - + public int getTotalRelight() { if (getTotalCount() == 0) { Arrays.fill(count, (short) 1); @@ -95,7 +92,7 @@ public class FastChunk_1_8_3 extends PlotChunk { } return total; } - + /** * Get the raw data for a section * @param i @@ -104,7 +101,7 @@ public class FastChunk_1_8_3 extends PlotChunk { public char[] getIdArray(final int i) { return ids[i]; } - + @Override public void setBlock(final int x, final int y, final int z, final int id, byte data) { final int i = MainUtil.CACHE_I[y][x][z]; @@ -211,7 +208,7 @@ public class FastChunk_1_8_3 extends PlotChunk { return; } } - + @Override public PlotChunk clone() { FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper()); @@ -219,17 +216,16 @@ public class FastChunk_1_8_3 extends PlotChunk { toReturn.count = count.clone(); toReturn.relight = relight.clone(); toReturn.ids = new char[ids.length][]; - for(int i = 0; i < ids.length; i++) - { + for (int i = 0; i < ids.length; i++) { char[] matrix = ids[i]; if (matrix != null) { toReturn.ids[i] = new char[matrix.length]; System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length); - } + } } return toReturn; } - + @Override public PlotChunk shallowClone() { FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper()); @@ -239,7 +235,7 @@ public class FastChunk_1_8_3 extends PlotChunk { toReturn.ids = ids; return toReturn; } - + @Override public void setBiome(int x, int z, int biome) { if (biomes == null) { diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java b/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java index dbce5f7d2..8320b4210 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java @@ -24,7 +24,7 @@ import java.util.Iterator; import java.util.Map.Entry; public class FastQueue_1_7 extends SlowQueue { - + public final RefClass classBlock = getRefClass("{nms}.Block"); public final RefClass classChunk = getRefClass("{nms}.Chunk"); public final RefClass classWorld = getRefClass("{nms}.World"); @@ -36,7 +36,7 @@ public class FastQueue_1_7 extends SlowQueue { public final RefMethod methodInitLighting; public final SendChunk chunksender; - + public HashMap toUpdate = new HashMap<>(); public FastQueue_1_7() throws NoSuchMethodException { @@ -49,7 +49,7 @@ public class FastQueue_1_7 extends SlowQueue { TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.size() == 0) { + if (toUpdate.isEmpty()) { return; } int count = 0; @@ -68,9 +68,9 @@ public class FastQueue_1_7 extends SlowQueue { }, 1); MainUtil.initCache(); } - + public void update(final Collection chunks) { - if (chunks.size() == 0) { + if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { @@ -141,7 +141,7 @@ public class FastQueue_1_7 extends SlowQueue { } } } - + /** * This should be overriden by any specialized queues * @param wrap @@ -150,7 +150,7 @@ public class FastQueue_1_7 extends SlowQueue { public PlotChunk getChunk(ChunkWrapper wrap) { return new SlowChunk(wrap); } - + /** * This should be overriden by any specialized queues * @param chunk @@ -162,7 +162,7 @@ public class FastQueue_1_7 extends SlowQueue { methodInitLighting.of(c).call(); return true; } - + /** * This should be overriden by any specialized queues * @param world diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java b/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java index 6b9dd2fd0..1309eb063 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java @@ -2,17 +2,6 @@ package com.plotsquared.bukkit.util.block; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; - import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; @@ -25,24 +14,33 @@ import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.SendChunk; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; public class FastQueue_1_8 extends SlowQueue { - + + public final RefMethod methodInitLighting; private final RefClass classBlock = getRefClass("{nms}.Block"); private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); private final RefClass classIBlockData = getRefClass("{nms}.IBlockData"); private final RefClass classChunk = getRefClass("{nms}.Chunk"); private final RefClass classWorld = getRefClass("{nms}.World"); private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); + public HashMap toUpdate = new HashMap<>(); private RefMethod methodGetHandle; private RefMethod methodGetChunkAt; private RefMethod methodA; private RefMethod methodGetByCombinedId; private RefConstructor constructorBlockPosition; private SendChunk chunksender; - public final RefMethod methodInitLighting; - - public HashMap toUpdate = new HashMap<>(); public FastQueue_1_8() throws NoSuchMethodException { methodInitLighting = classChunk.getMethod("initLighting"); @@ -55,7 +53,7 @@ public class FastQueue_1_8 extends SlowQueue { TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.size() == 0) { + if (toUpdate.isEmpty()) { return; } int count = 0; @@ -74,9 +72,9 @@ public class FastQueue_1_8 extends SlowQueue { }, 1); MainUtil.initCache(); } - + public void update(final Collection chunks) { - if (chunks.size() == 0) { + if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { @@ -94,7 +92,7 @@ public class FastQueue_1_8 extends SlowQueue { MainUtil.canSendChunk = false; } } - + /** * This should be overriden by any specialized queues * @param pc @@ -179,7 +177,7 @@ public class FastQueue_1_8 extends SlowQueue { continue; } } - + // Start data value shortcut final Block block = world.getBlockAt(x, y, z); final int currentId = block.getTypeId(); @@ -323,7 +321,7 @@ public class FastQueue_1_8 extends SlowQueue { } } // End blockstate workaround // - + // check sign final Object pos = constructorBlockPosition.create(x, y, z); final Object combined = methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); @@ -348,19 +346,19 @@ public class FastQueue_1_8 extends SlowQueue { } } } - + /** * This should be overriden by any specialized queues - * @param pc + * @param wrap */ @Override public PlotChunk getChunk(ChunkWrapper wrap) { return new SlowChunk(wrap); } - + /** * This should be overriden by any specialized queues - * @param pc + * @param fixAll */ @Override public boolean fixLighting(PlotChunk chunk, boolean fixAll) { @@ -368,10 +366,10 @@ public class FastQueue_1_8 extends SlowQueue { methodInitLighting.of(c).call(); return true; } - + /** * This should be overriden by any specialized queues - * @param pc + * @param locs */ @Override public void sendChunk(String world, Collection locs) { diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java b/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java index a2c362d95..7f22cd9d0 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java @@ -2,22 +2,6 @@ package com.plotsquared.bukkit.util.block; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import org.bukkit.Chunk; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.World.Environment; -import org.bukkit.block.Biome; - import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.PseudoRandom; import com.intellectualcrafters.plot.util.ChunkManager; @@ -33,9 +17,26 @@ import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.SendChunk; +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.block.Biome; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; public class FastQueue_1_8_3 extends SlowQueue { - + + public final SendChunk chunksender; private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); private final RefClass classPacket = getRefClass("{nms}.Packet"); @@ -47,7 +48,7 @@ public class FastQueue_1_8_3 extends SlowQueue { private final RefField mustSave = classChunk.getField("mustSave"); private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); private final RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); - + public HashMap toUpdate = new HashMap<>(); private RefMethod methodGetHandlePlayer; private RefMethod methodGetHandleChunk; private RefConstructor MapChunk; @@ -61,10 +62,6 @@ public class FastQueue_1_8_3 extends SlowQueue { private RefField fieldSections; private RefField fieldWorld; private RefMethod methodGetIdArray; - - public final SendChunk chunksender; - - public HashMap toUpdate = new HashMap<>(); public FastQueue_1_8_3() throws NoSuchMethodException { methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); @@ -84,7 +81,7 @@ public class FastQueue_1_8_3 extends SlowQueue { TaskManager.runTaskRepeat(new Runnable() { @Override public void run() { - if (toUpdate.size() == 0) { + if (toUpdate.isEmpty()) { return; } int count = 0; @@ -103,9 +100,9 @@ public class FastQueue_1_8_3 extends SlowQueue { }, 1); MainUtil.initCache(); } - + public void update(final Collection chunks) { - if (chunks.size() == 0) { + if (chunks.isEmpty()) { return; } if (!MainUtil.canSendChunk) { @@ -123,7 +120,7 @@ public class FastQueue_1_8_3 extends SlowQueue { MainUtil.canSendChunk = false; } } - + /** * This should be overriden by any specialized queues * @param pc @@ -140,7 +137,7 @@ public class FastQueue_1_8_3 extends SlowQueue { chunk.load(true); try { final boolean flag = world.getEnvironment() == Environment.NORMAL; - + // Sections final Method getHandele = chunk.getClass().getDeclaredMethod("getHandle"); final Object c = getHandele.invoke(chunk); @@ -149,15 +146,15 @@ public class FastQueue_1_8_3 extends SlowQueue { sf.setAccessible(true); final Field tf = clazz.getDeclaredField("tileEntities"); final Field ef = clazz.getDeclaredField("entitySlices"); - + final Object[] sections = (Object[]) sf.get(c); final HashMap tiles = (HashMap) tf.get(c); final List[] entities = (List[]) ef.get(c); - + Method xm = null; Method ym = null; Method zm = null; - + // Trim tiles final Set> entryset = (Set>) (Set) tiles.entrySet(); final Iterator> iter = entryset.iterator(); @@ -183,14 +180,14 @@ public class FastQueue_1_8_3 extends SlowQueue { iter.remove(); } } - + // Trim entities for (int i = 0; i < 16; i++) { if ((entities[i] != null) && (fs.getCount(i) >= 4096)) { entities[i].clear(); } } - + // Efficiently merge sections for (int j = 0; j < sections.length; j++) { if (fs.getCount(j) == 0) { @@ -227,7 +224,8 @@ public class FastQueue_1_8_3 extends SlowQueue { } } // Clear - } catch (final Exception e) { + } catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException | + NoSuchFieldException e) { e.printStackTrace(); } int[][] biomes = fs.biomes; @@ -248,11 +246,11 @@ public class FastQueue_1_8_3 extends SlowQueue { } } } - + public Object newChunkSection(final int i, final boolean flag, final char[] ids) { return classChunkSectionConstructor.create(i, flag, ids); } - + public char[] getIdArray(final Object obj) { return (char[]) methodGetIdArray.of(obj).call(); } @@ -265,7 +263,7 @@ public class FastQueue_1_8_3 extends SlowQueue { public PlotChunk getChunk(ChunkWrapper wrap) { return new FastChunk_1_8_3(wrap); } - + /** * This should be overriden by any specialized queues * @param pc @@ -277,15 +275,14 @@ public class FastQueue_1_8_3 extends SlowQueue { final Chunk chunk = bc.getChunk(); if (!chunk.isLoaded()) { chunk.load(false); - } - else { + } else { chunk.unload(true, false); chunk.load(false); } - + // Initialize lighting final Object c = methodGetHandleChunk.of(chunk).call(); - + if (fixAll && !(boolean) methodAreNeighborsLoaded.of(c).call(1)) { World world = chunk.getWorld(); ChunkWrapper wrapper = bc.getChunkWrapper(); @@ -305,19 +302,19 @@ public class FastQueue_1_8_3 extends SlowQueue { return false; } } - + methodInitLighting.of(c).call(); - + if ((bc.getTotalRelight() == 0 && !fixAll)) { return true; } - + final Object[] sections = (Object[]) fieldSections.of(c).get(); final Object w = fieldWorld.of(c).get(); - + final int X = chunk.getX() << 4; final int Z = chunk.getZ() << 4; - + RefExecutor relight = methodX.of(w); for (int j = 0; j < sections.length; j++) { final Object section = sections[j]; @@ -376,22 +373,19 @@ public class FastQueue_1_8_3 extends SlowQueue { } return false; } - + public boolean isSurrounded(Object[] sections, int x, int y, int z) { return isSolid(getId(sections, x, y + 1, z)) - && isSolid(getId(sections, x + 1, y - 1, z)) - && isSolid(getId(sections, x - 1, y, z)) - && isSolid(getId(sections, x, y, z + 1)) - && isSolid(getId(sections, x, y, z - 1)); + && isSolid(getId(sections, x + 1, y - 1, z)) + && isSolid(getId(sections, x - 1, y, z)) + && isSolid(getId(sections, x, y, z + 1)) + && isSolid(getId(sections, x, y, z - 1)); } - + public boolean isSolid(int i) { - if (i == 0) { - return false; - } - return Material.getMaterial(i).isOccluding(); + return i != 0 && Material.getMaterial(i).isOccluding(); } - + public int getId(Object[] sections, int x, int y, int z) { if (x < 0 || x > 15 || z < 0 || z > 15) { return 1; diff --git a/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java b/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java index c1270bd45..a79ab772a 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java @@ -1,28 +1,24 @@ package com.plotsquared.bukkit.util.block; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.PlotChunk; +import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; +import com.plotsquared.bukkit.util.BukkitUtil; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.PlotChunk; -import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; -import com.plotsquared.bukkit.util.BukkitUtil; - -public class GenChunk extends PlotChunk{ +public class GenChunk extends PlotChunk { + public final Biome[] biomes; public Chunk chunk; - public short[][] result; public byte[][] result_data; public ChunkData cd; - public boolean modified = false; - public BiomeGrid grid; - public final Biome[] biomes; public GenChunk(Chunk chunk, ChunkWrapper wrap) { super(wrap); @@ -34,10 +30,10 @@ public class GenChunk extends PlotChunk{ } this.biomes = Biome.values(); } - + @Override public Chunk getChunkAbs() { - ChunkWrapper wrap = getChunkWrapper(); + ChunkWrapper wrap = getChunkWrapper(); if (wrap.x != chunk.getX() || wrap.z != chunk.getZ()) { chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z); } @@ -55,7 +51,7 @@ public class GenChunk extends PlotChunk{ grid.setBiome(x, z, biome); } } - + @Override public void setBlock(int x, int y, int z, int id, byte data) { if (result == null) { @@ -74,7 +70,7 @@ public class GenChunk extends PlotChunk{ getChunk().getBlock(x, y, z).setData(data); } } - + @Override public PlotChunk clone() { GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper()); @@ -97,7 +93,7 @@ public class GenChunk extends PlotChunk{ toReturn.cd = cd; return toReturn; } - + @Override public PlotChunk shallowClone() { GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper()); diff --git a/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java b/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java index 51e6ad5b0..4c27a14bc 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java @@ -1,30 +1,27 @@ package com.plotsquared.bukkit.util.block; -import org.bukkit.Chunk; - import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.PlotChunk; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; import com.plotsquared.bukkit.util.BukkitUtil; +import org.bukkit.Chunk; public class SlowChunk extends PlotChunk { - + + public PlotBlock[][] result = new PlotBlock[16][]; + public int[][] biomes; + private PlotBlock lastBlock; public SlowChunk(ChunkWrapper chunk) { super(chunk); } - + @Override public Chunk getChunkAbs() { ChunkWrapper loc = getChunkWrapper(); return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z); } - - public PlotBlock[][] result = new PlotBlock[16][]; - public int[][] biomes; - - private PlotBlock lastBlock; - + @Override public void setBiome(int x, int z, int biome) { if (biomes == null) { @@ -32,7 +29,7 @@ public class SlowChunk extends PlotChunk { } biomes[x][z] = biome; } - + @Override public void setBlock(int x, int y, int z, int id, byte data) { if (result[y >> 4] == null) { @@ -44,7 +41,7 @@ public class SlowChunk extends PlotChunk { result[MainUtil.CACHE_I[x][y][z]][MainUtil.CACHE_J[x][y][z]] = new PlotBlock((short) id, data); } } - + @Override public PlotChunk clone() { SlowChunk toReturn = new SlowChunk(getChunkWrapper()); @@ -57,7 +54,7 @@ public class SlowChunk extends PlotChunk { } return toReturn; } - + @Override public PlotChunk shallowClone() { SlowChunk toReturn = new SlowChunk(getChunkWrapper()); diff --git a/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java b/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java index 5d7d8dd30..8a655511f 100644 --- a/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java +++ b/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java @@ -1,14 +1,5 @@ package com.plotsquared.bukkit.util.block; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; - -import org.bukkit.Chunk; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.PlotBlock; @@ -17,18 +8,26 @@ import com.intellectualcrafters.plot.util.PlotChunk; import com.intellectualcrafters.plot.util.PlotQueue; import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; +import org.bukkit.Chunk; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; public class SlowQueue implements PlotQueue { - + + private final ConcurrentHashMap> blocks = new ConcurrentHashMap<>(); + public SlowQueue() { MainUtil.initCache(); } - private final ConcurrentHashMap> blocks = new ConcurrentHashMap<>(); - @Override public boolean setBlock(String world, int x, int y, int z, short id, byte data) { - if ((y > 255) || (y < 0)) { + if (y > 255 || y < 0) { return false; } final ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4); @@ -48,19 +47,19 @@ public class SlowQueue implements PlotQueue { result.setBlock(x, y, z, id, data); return true; } - + @Override public void setChunk(PlotChunk chunk) { blocks.put(chunk.getChunkWrapper(), chunk); } - + @Override public PlotChunk next() { if (!PS.get().isMainThread(Thread.currentThread())) { throw new IllegalStateException("Must be called from main thread!"); } try { - if (blocks.size() == 0) { + if (blocks.isEmpty()) { return null; } final Iterator>> iter = blocks.entrySet().iterator(); @@ -77,14 +76,14 @@ public class SlowQueue implements PlotQueue { return null; } } - + @Override public PlotChunk next(ChunkWrapper wrap, boolean fixLighting) { if (!PS.get().isMainThread(Thread.currentThread())) { throw new IllegalStateException("Must be called from main thread!"); } try { - if (blocks.size() == 0) { + if (blocks.isEmpty()) { return null; } final PlotChunk toReturn = blocks.remove(wrap); @@ -99,12 +98,12 @@ public class SlowQueue implements PlotQueue { return null; } } - + @Override public void clear() { blocks.clear(); } - + /** * This should be overriden by any specialized queues * @param pc @@ -125,13 +124,12 @@ public class SlowQueue implements PlotQueue { Block block = chunk.getBlock(x, y, z); PlotBlock newBlock = result2[j]; switch (newBlock.id) { - case -1: { + case -1: if (block.getData() == newBlock.data) { continue; } block.setData(newBlock.data); continue; - } case 0: case 2: case 4: @@ -212,14 +210,13 @@ public class SlowQueue implements PlotQueue { case 189: case 190: case 191: - case 192: { + case 192: if (block.getTypeId() == newBlock.id) { continue; } block.setTypeId(newBlock.id, false); continue; - } - default: { + default: if (block.getTypeId() == newBlock.id && block.getData() == newBlock.data) { continue; } @@ -229,7 +226,6 @@ public class SlowQueue implements PlotQueue { block.setTypeIdAndData(newBlock.id, newBlock.data, false); } continue; - } } } } @@ -251,29 +247,29 @@ public class SlowQueue implements PlotQueue { } } } - + /** * This should be overriden by any specialized queues - * @param pc + * @param wrap */ @Override public PlotChunk getChunk(ChunkWrapper wrap) { return new SlowChunk(wrap); } - + /** * This should be overriden by any specialized queues - * @param pc + * @param fixAll */ @Override public boolean fixLighting(PlotChunk chunk, boolean fixAll) { // Do nothing return true; } - + /** * This should be overriden by any specialized queues - * @param pc + * @param locs */ @Override public void sendChunk(String world, Collection locs) { diff --git a/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java b/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java index f88a77a89..4170c9207 100644 --- a/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -1,21 +1,7 @@ package com.plotsquared.bukkit.uuid; -import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.World; - import com.google.common.collect.HashBiMap; -import com.google.common.io.InputSupplier; +import com.google.common.io.ByteSource; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -30,6 +16,18 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.util.NbtFactory; +import org.bukkit.Bukkit; +import org.bukkit.World; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; public class FileUUIDHandler extends UUIDHandlerImplementation { @@ -39,17 +37,14 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { @Override public boolean startCaching(final Runnable whenDone) { - if (!super.startCaching(whenDone)) { - return false; - } - return cache(whenDone); + return super.startCaching(whenDone) && cache(whenDone); } public boolean cache(final Runnable whenDone) { final File container = Bukkit.getWorldContainer(); final List worlds = Bukkit.getWorlds(); final String world; - if (worlds.size() == 0) { + if (worlds.isEmpty()) { world = "world"; } else { world = worlds.get(0).getName(); @@ -65,13 +60,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { for (String line : lines) { try { line = line.trim(); - if (line.length() == 0) { + if (line.isEmpty()) { continue; } line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); final String[] split = line.split("\\|"); 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; } final UUID uuid = uuidWrapper.getUUID(name); @@ -99,7 +94,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { return s.endsWith(".dat"); } }); - final boolean check = all.size() == 0; + final boolean check = all.isEmpty(); if (dat != null) { for (final String current : dat) { final String s = current.replaceAll(".dat$", ""); @@ -107,7 +102,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { final UUID uuid = UUID.fromString(s); if (check || all.remove(uuid)) { final File file = new File(playerdataFolder + File.separator + current); - final InputSupplier is = com.google.common.io.Files.newInputStreamSupplier(file); + final ByteSource is = com.google.common.io.Files.asByteSource(file); final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); final String name = (String) bukkit.get("lastKnownName"); @@ -122,7 +117,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } } add(toAdd); - if (all.size() == 0) { + if (all.isEmpty()) { if (whenDone != null) { whenDone.run(); } @@ -178,7 +173,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { for (UUID uuid : uuids) { try { final File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat"); - final InputSupplier is = com.google.common.io.Files.newInputStreamSupplier(file); + final ByteSource is = com.google.common.io.Files.asByteSource(file); final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); final String name = (String) bukkit.get("lastKnownName"); @@ -203,8 +198,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { final StringWrapper nameWrap = new StringWrapper(name); toAdd.put(nameWrap, uuid); } - - if (getUUIDMap().size() == 0) { + + if (getUUIDMap().isEmpty()) { for (final OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers()) { final long last = op.getLastPlayed(); if (last != 0) { diff --git a/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java index 976809f19..859c4f2ea 100644 --- a/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -1,5 +1,21 @@ package com.plotsquared.bukkit.uuid; +import com.google.common.collect.HashBiMap; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.database.SQLite; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; +import com.intellectualcrafters.plot.uuid.UUIDWrapper; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; @@ -13,29 +29,13 @@ import java.util.Collections; import java.util.HashMap; import java.util.UUID; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import com.google.common.collect.HashBiMap; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; - public class SQLUUIDHandler extends UUIDHandlerImplementation { final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; final int MAX_REQUESTS = 500; final int INTERVAL = 12000; final JSONParser jsonParser = new JSONParser(); + private final SQLite _sqLite; public SQLUUIDHandler(final UUIDWrapper wrapper) { super(wrapper); @@ -45,7 +45,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } catch (final Exception e) { e.printStackTrace(); } - + try { final PreparedStatement stmt = getConnection().prepareStatement( "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))"); @@ -57,14 +57,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { startCaching(null); } - private class SQLUUIDHandlerException extends RuntimeException { - SQLUUIDHandlerException(final String s, final Throwable c) { - super("SQLUUIDHandler caused an exception: " + s, c); - } - } - - private final SQLite _sqLite; - private Connection getConnection() { synchronized (_sqLite) { return _sqLite.getConnection(); @@ -93,7 +85,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { statement.close(); add(toAdd); add(new StringWrapper("*"), DBFunc.everyone); - + // This should be called as long as there are some unknown plots final ArrayDeque toFetch = new ArrayDeque<>(); for (final UUID u : UUIDHandler.getAllUUIDS()) { @@ -119,12 +111,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } return; } - + TaskManager.runTaskAsync(new Runnable() { @Override public void run() { try { - if (toFetch.size() == 0) { + if (toFetch.isEmpty()) { if (whenDone != null) { whenDone.run(); } @@ -227,7 +219,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { stream.close(); JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); JSONObject jsonProfile = (JSONObject) array.get(0); - String id = (String) jsonProfile.get("id"); + String id = (String) jsonProfile.get("type"); String name = (String) jsonProfile.get("name"); ifFetch.value = UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); } catch (Exception e) { @@ -292,4 +284,11 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } }); } + + private class SQLUUIDHandlerException extends RuntimeException { + + SQLUUIDHandlerException(final String s, final Throwable c) { + super("SQLUUIDHandler caused an exception: " + s, c); + } + } } diff --git a/src/main/java/com/plotsquared/general/commands/Command.java b/src/main/java/com/plotsquared/general/commands/Command.java index 3245996c6..809e2d480 100644 --- a/src/main/java/com/plotsquared/general/commands/Command.java +++ b/src/main/java/com/plotsquared/general/commands/Command.java @@ -1,21 +1,22 @@ package com.plotsquared.general.commands; +import com.intellectualcrafters.plot.commands.CommandCategory; +import com.intellectualcrafters.plot.commands.RequiredType; + import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.RequiredType; - public abstract class Command extends CommandManager { - + + protected Argument[] requiredArguments; private RequiredType requiredType = RequiredType.NONE; private String command, usage = "", description = "", permission = ""; private Set aliases = new HashSet<>(); private CommandCategory category; - protected Argument[] requiredArguments; + private int hash; public Command() { super(null, new ArrayList()); @@ -114,14 +115,14 @@ public abstract class Command extends CommandManager { } public String getUsage() { - if (this.usage.length() == 0) { + if (this.usage.isEmpty()) { return "/{label} " + command; } return this.usage; } public String getPermission() { - if ((this.permission == null) || (this.permission.length() == 0)) { + if ((this.permission == null) || (this.permission.isEmpty())) { this.permission = "plots." + command.toLowerCase(); } return this.permission; @@ -167,8 +168,6 @@ public abstract class Command extends CommandManager { return this.command.equals(other.command); } - private int hash; - @Override public int hashCode() { if (hash == 0) { diff --git a/src/main/java/com/plotsquared/listener/PlotListener.java b/src/main/java/com/plotsquared/listener/PlotListener.java index b076b48f6..9b159eb7f 100644 --- a/src/main/java/com/plotsquared/listener/PlotListener.java +++ b/src/main/java/com/plotsquared/listener/PlotListener.java @@ -20,10 +20,6 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.listener; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.flag.Flag; @@ -45,6 +41,10 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.UUIDHandler; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + /** @@ -159,7 +159,7 @@ public class PlotListener { return true; } if (titles) { - if ((C.TITLE_ENTERED_PLOT.s().length() != 0) || (C.TITLE_ENTERED_PLOT_SUB.s().length() != 0)) { + if ((!C.TITLE_ENTERED_PLOT.s().isEmpty()) || (!C.TITLE_ENTERED_PLOT_SUB.s().isEmpty())) { TaskManager.runTaskLaterAsync(new Runnable() { @Override public void run() { diff --git a/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java b/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java index 448b76df0..f244a6f8f 100644 --- a/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java +++ b/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java @@ -1,8 +1,5 @@ package com.plotsquared.listener; -import java.lang.reflect.Field; -import java.util.HashSet; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.PlotBlock; @@ -19,14 +16,17 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; +import java.lang.reflect.Field; +import java.util.HashSet; + public class ProcessedWEExtent extends AbstractDelegateExtent { private final HashSet mask; + private final String world; + private final int max; int BScount = 0; int Ecount = 0; boolean BSblocked = false; boolean Eblocked = false; - private final String world; - private final int max; private int count; private Extent parent; @@ -225,7 +225,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { } } return true; - // WorldUtil.IMP.functionSetBlock(world, x, y, z, id, data); + // WorldUtil.IMP.functionSetBlock(world, x, y, z, type, data); // return super.setBlock(location, block); } } diff --git a/src/main/java/com/plotsquared/listener/WESubscriber.java b/src/main/java/com/plotsquared/listener/WESubscriber.java index f3caea847..717d82561 100644 --- a/src/main/java/com/plotsquared/listener/WESubscriber.java +++ b/src/main/java/com/plotsquared/listener/WESubscriber.java @@ -1,8 +1,5 @@ package com.plotsquared.listener; -import java.lang.reflect.Field; -import java.util.HashSet; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -26,6 +23,9 @@ import com.sk89q.worldedit.util.eventbus.EventHandler.Priority; import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.world.World; +import java.lang.reflect.Field; +import java.util.HashSet; + public class WESubscriber { @Subscribe(priority = Priority.VERY_EARLY) @@ -38,14 +38,14 @@ public class WESubscriber { final World worldObj = event.getWorld(); final String world = worldObj.getName(); final Actor actor = event.getActor(); - if ((actor != null) && actor.isPlayer()) { + if (actor != null && actor.isPlayer()) { final String name = actor.getName(); final PlotPlayer pp = PlotPlayer.wrap(name); - if ((pp != null) && pp.getAttribute("worldedit")) { + if (pp != null && pp.getAttribute("worldedit")) { return; } final HashSet mask = WEManager.getMask(pp); - if (mask.size() == 0) { + if (mask.isEmpty()) { if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) { MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS); } @@ -57,33 +57,34 @@ public class WESubscriber { if (Settings.CHUNK_PROCESSOR) { if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) { try { - final LocalSession session = worldedit.getSession(name); + final LocalSession session = worldedit.getSessionManager().findByName(name); boolean hasMask = session.getMask() != null; final Player objPlayer = (Player) actor; final int item = objPlayer.getItemInHand(); if (!hasMask) { try { final Tool tool = session.getTool(item); - if ((tool != null) && (tool instanceof BrushTool)) { + if (tool instanceof BrushTool) { hasMask = ((BrushTool) tool).getMask() != null; } - } catch (final Exception e) {} + } catch (final Exception e) { + } } AbstractDelegateExtent extent = (AbstractDelegateExtent) event.getExtent(); ChangeSetExtent history = null; MultiStageReorder reorder = null; MaskingExtent maskextent = null; final boolean fast = session.hasFastMode(); - while ((extent.getExtent() != null) && (extent.getExtent() instanceof AbstractDelegateExtent)) { + while (extent.getExtent() != null && extent.getExtent() instanceof AbstractDelegateExtent) { final AbstractDelegateExtent tmp = (AbstractDelegateExtent) extent.getExtent(); - if ((tmp.getExtent() != null) && (tmp.getExtent() instanceof AbstractDelegateExtent)) { + if (tmp.getExtent() != null && tmp.getExtent() instanceof AbstractDelegateExtent) { if (tmp instanceof ChangeSetExtent) { history = (ChangeSetExtent) tmp; } if (tmp instanceof MultiStageReorder) { reorder = (MultiStageReorder) tmp; } - if (hasMask && (tmp instanceof MaskingExtent)) { + if (hasMask && tmp instanceof MaskingExtent) { maskextent = (MaskingExtent) tmp; } extent = tmp; @@ -116,7 +117,7 @@ public class WESubscriber { } } return; - } catch (final Exception e) { + } catch (IllegalAccessException | SecurityException | NoSuchFieldException | IllegalArgumentException e) { e.printStackTrace(); } } diff --git a/src/main/java/com/plotsquared/sponge/SpongeSchematicHandler.java b/src/main/java/com/plotsquared/sponge/SpongeSchematicHandler.java index 56f6a6e2b..a9fbbc1a2 100644 --- a/src/main/java/com/plotsquared/sponge/SpongeSchematicHandler.java +++ b/src/main/java/com/plotsquared/sponge/SpongeSchematicHandler.java @@ -1,14 +1,5 @@ package com.plotsquared.sponge; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.world.World; - import com.intellectualcrafters.jnbt.ByteArrayTag; import com.intellectualcrafters.jnbt.CompoundTag; import com.intellectualcrafters.jnbt.IntTag; @@ -25,6 +16,14 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.sponge.util.SpongeUtil; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.world.World; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; public class SpongeSchematicHandler extends SchematicHandler { @@ -63,7 +62,7 @@ public class SpongeSchematicHandler extends SchematicHandler { TaskManager.runTask(new Runnable() { @Override public void run() { - if (queue.size() == 0) { + if (queue.isEmpty()) { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { @@ -108,7 +107,7 @@ public class SpongeSchematicHandler extends SchematicHandler { @Override public void run() { final long start = System.currentTimeMillis(); - while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < 20)) { + while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < 20)) { // save schematics final ChunkLoc chunk = chunks.remove(0); final int X = chunk.x; @@ -268,7 +267,7 @@ public class SpongeSchematicHandler extends SchematicHandler { } } } - if (chunks.size() != 0) { + if (!chunks.isEmpty()) { TaskManager.runTaskLater(this, 1); } else { regionTask.run(); diff --git a/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java b/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java index d05ef6814..d927e2968 100644 --- a/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java +++ b/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java @@ -1,11 +1,5 @@ package com.plotsquared.sponge; -import java.io.IOException; -import java.util.Map.Entry; - -import org.spongepowered.api.world.World; -import org.spongepowered.api.world.gen.WorldGenerator; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.ConfigurationNode; import com.intellectualcrafters.plot.generator.PlotGenerator; @@ -18,12 +12,17 @@ import com.plotsquared.sponge.generator.SpongeBasicGen; import com.plotsquared.sponge.generator.SpongeGeneratorWrapper; import com.plotsquared.sponge.generator.SpongePlotGenerator; import com.plotsquared.sponge.util.SpongeUtil; +import org.spongepowered.api.world.World; +import org.spongepowered.api.world.gen.WorldGenerator; + +import java.io.IOException; +import java.util.Map.Entry; public class SpongeSetupUtils extends SetupUtils { @Override public void updateGenerators() { - if (SetupUtils.generators.size() > 0) { + if (!SetupUtils.generators.isEmpty()) { return; } // TODO get external world generators @@ -33,7 +32,7 @@ public class SpongeSetupUtils extends SetupUtils { @Override public String getGenerator(final PlotArea plotworld) { - if (SetupUtils.generators.size() == 0) { + if (SetupUtils.generators.isEmpty()) { updateGenerators(); } final World world = SpongeUtil.getWorld(plotworld.worldname); diff --git a/src/main/java/com/plotsquared/sponge/generator/SpongePlotPopulator.java b/src/main/java/com/plotsquared/sponge/generator/SpongePlotPopulator.java index 6981c2642..d94ae525f 100644 --- a/src/main/java/com/plotsquared/sponge/generator/SpongePlotPopulator.java +++ b/src/main/java/com/plotsquared/sponge/generator/SpongePlotPopulator.java @@ -1,24 +1,23 @@ package com.plotsquared.sponge.generator; +import com.flowpowered.math.vector.Vector3i; +import com.intellectualcrafters.plot.object.PseudoRandom; +import com.intellectualcrafters.plot.object.RegionWrapper; +import com.intellectualcrafters.plot.util.ChunkManager; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.world.World; import org.spongepowered.api.world.extent.ImmutableBiomeArea; import org.spongepowered.api.world.extent.MutableBlockVolume; import org.spongepowered.api.world.gen.GenerationPopulator; -import com.flowpowered.math.vector.Vector3i; -import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.util.ChunkManager; - public abstract class SpongePlotPopulator implements GenerationPopulator { - + + public final T generator; + private final PseudoRandom random = new PseudoRandom(); public int X; public int Z; public String worldname; - private final PseudoRandom random = new PseudoRandom(); private MutableBlockVolume buffer; - public final T generator; public SpongePlotPopulator(final T generator) { this.generator = generator; @@ -59,7 +58,7 @@ public abstract class SpongePlotPopulator impleme public abstract void populate(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz); /** - * Set the id and data at a location. (x, y, z) must be between [0,15], [0,255], [0,15] + * Set the type and data at a location. (x, y, z) must be between [0,15], [0,255], [0,15] * @param x * @param y * @param z diff --git a/src/main/java/com/plotsquared/sponge/listener/MainListener.java b/src/main/java/com/plotsquared/sponge/listener/MainListener.java index 53c9abd8a..2977b3d65 100644 --- a/src/main/java/com/plotsquared/sponge/listener/MainListener.java +++ b/src/main/java/com/plotsquared/sponge/listener/MainListener.java @@ -1,14 +1,31 @@ package com.plotsquared.sponge.listener; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.function.Predicate; - +import com.flowpowered.math.vector.Vector3d; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotBlock; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.StringWrapper; +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.StringMan; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.plotsquared.listener.PlotListener; +import com.plotsquared.sponge.SpongeMain; +import com.plotsquared.sponge.object.SpongePlayer; +import com.plotsquared.sponge.util.SpongeUtil; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.data.Transaction; @@ -43,32 +60,14 @@ import org.spongepowered.api.text.Text; import org.spongepowered.api.world.World; import org.spongepowered.api.world.extent.Extent; -import com.flowpowered.math.vector.Vector3d; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.StringWrapper; -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.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.listener.PlotListener; -import com.plotsquared.sponge.SpongeMain; -import com.plotsquared.sponge.object.SpongePlayer; -import com.plotsquared.sponge.util.SpongeUtil; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Predicate; public class MainListener { @@ -401,7 +400,7 @@ public class MainListener { final PlotId id = plot.getId(); final String newMessage = StringMan.replaceAll(C.PLOT_CHAT_FORMAT.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender); final Text forcedMessage = event.getMessage(); - // String forcedMessage = StringMan.replaceAll(C.PLOT_CHAT_FORCED.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender); + // String forcedMessage = StringMan.replaceAll(C.PLOT_CHAT_FORCED.s(), "%plot_id%", type.x + ";" + type.y, "%sender%", sender); for (Entry entry : UUIDHandler.getPlayers().entrySet()) { PlotPlayer user = entry.getValue(); String toSend; diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java b/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java index 6c5bc7217..72ab257be 100644 --- a/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java +++ b/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java @@ -1,11 +1,9 @@ package com.plotsquared.sponge.util; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.object.ConsolePlayer; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.plotsquared.sponge.SpongeMain; import org.spongepowered.api.command.CommandCallable; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; @@ -13,10 +11,11 @@ import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.sponge.SpongeMain; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.UUID; public class SpongeCommand implements CommandCallable { @@ -31,7 +30,7 @@ public class SpongeCommand implements CommandCallable { } catch (final Exception e) { pp = ConsolePlayer.getConsole(); } - if (MainCommand.onCommand(pp, cmd.getName(), string.length() == 0 ? new String[] {} : string.split(" "))) { + if (MainCommand.onCommand(pp, cmd.getName(), string.isEmpty() ? new String[]{} : string.split(" "))) { return CommandResult.success(); } else { return CommandResult.empty(); diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java b/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java index c8a029761..c2359e708 100644 --- a/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java +++ b/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java @@ -28,6 +28,14 @@ package com.plotsquared.sponge.util; * either expressed or implied, of anybody else. */ +import com.intellectualcrafters.plot.PS; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import ninja.leaping.configurate.loader.ConfigurationLoader; +import org.spongepowered.api.Game; +import org.spongepowered.api.plugin.PluginContainer; +import org.spongepowered.api.scheduler.Task; + import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; @@ -45,16 +53,6 @@ import java.util.zip.GZIPOutputStream; import javax.inject.Inject; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.loader.ConfigurationLoader; - -import org.spongepowered.api.Game; -import org.spongepowered.api.plugin.PluginContainer; -import org.spongepowered.api.scheduler.Task; - -import com.intellectualcrafters.plot.PS; - public class SpongeMetrics { /** @@ -86,37 +84,30 @@ public class SpongeMetrics { * The plugin this metrics submits for */ private final PluginContainer plugin; - - /** - * The plugin configuration file - */ - private CommentedConfigurationNode config; - - /** - * The configuration loader - */ - private ConfigurationLoader configurationLoader; - - /** - * The plugin configuration file - */ - private File configurationFile; - - /** - * Unique server id - */ - private String guid; - - /** - * Debug mode - */ - private boolean debug; - /** * Lock for synchronization */ private final Object optOutLock = new Object(); - + /** + * The plugin configuration file + */ + private CommentedConfigurationNode config; + /** + * The configuration loader + */ + private ConfigurationLoader configurationLoader; + /** + * The plugin configuration file + */ + private File configurationFile; + /** + * Unique server type + */ + private String guid; + /** + * Debug mode + */ + private boolean debug; /** * The scheduled task */ @@ -134,6 +125,123 @@ public class SpongeMetrics { loadConfiguration(); } + /** + * GZip compress a string of bytes + * + * @param input + * @return + */ + public static byte[] gzip(final String input) { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gzos = null; + + try { + gzos = new GZIPOutputStream(baos); + gzos.write(input.getBytes("UTF-8")); + } catch (final IOException e) { + e.printStackTrace(); + } finally { + if (gzos != null) { + try { + gzos.close(); + } catch (final IOException ignore) { + } + } + } + + return baos.toByteArray(); + } + + /** + * Appends a json encoded key/value pair to the given string builder. + * + * @param json + * @param key + * @param value + * @throws java.io.UnsupportedEncodingException + */ + private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException { + boolean isValueNumeric = false; + + try { + if (value.equals("0") || !value.endsWith("0")) { + Double.parseDouble(value); + isValueNumeric = true; + } + } catch (final NumberFormatException e) { + isValueNumeric = false; + } + + if (json.charAt(json.length() - 1) != '{') { + json.append(','); + } + + json.append(escapeJSON(key)); + json.append(':'); + + if (isValueNumeric) { + json.append(value); + } else { + json.append(escapeJSON(value)); + } + } + + /** + * Escape a string to create a valid JSON string + * + * @param text + * @return + */ + private static String escapeJSON(final String text) { + final StringBuilder builder = new StringBuilder(); + + builder.append('"'); + for (int index = 0; index < text.length(); index++) { + final char chr = text.charAt(index); + + switch (chr) { + case '"': + case '\\': + builder.append('\\'); + builder.append(chr); + break; + case '\b': + builder.append("\\b"); + break; + case '\t': + builder.append("\\t"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + default: + if (chr < ' ') { + final String t = "000" + Integer.toHexString(chr); + builder.append("\\u" + t.substring(t.length() - 4)); + } else { + builder.append(chr); + } + break; + } + } + builder.append('"'); + + return builder.toString(); + } + + /** + * Encode text as UTF-8 + * + * @param text the text to encode + * @return the encoded text, as UTF-8 + */ + private static String urlEncode(final String text) throws UnsupportedEncodingException { + return URLEncoder.encode(text, "UTF-8"); + } + /** * Loads the configuration */ @@ -395,32 +503,6 @@ public class SpongeMetrics { } } - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(final String input) { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - - try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (final IOException e) { - e.printStackTrace(); - } finally { - if (gzos != null) { - try { - gzos.close(); - } catch (final IOException ignore) {} - } - } - - return baos.toByteArray(); - } - /** * Check if mineshafter is present. If it is, we need to bypass it to send POST requests * @@ -435,94 +517,4 @@ public class SpongeMetrics { } } - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws java.io.UnsupportedEncodingException - */ - private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException { - boolean isValueNumeric = false; - - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (final NumberFormatException e) { - isValueNumeric = false; - } - - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - - json.append(escapeJSON(key)); - json.append(':'); - - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(final String text) { - final StringBuilder builder = new StringBuilder(); - - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - final char chr = text.charAt(index); - - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - final String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - }