diff --git a/PlotSquared/.gitignore b/PlotSquared/.gitignore new file mode 100644 index 000000000..ea8c4bf7f --- /dev/null +++ b/PlotSquared/.gitignore @@ -0,0 +1 @@ +/target diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java index 4d0d89322..1eea41719 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java @@ -10,9 +10,10 @@ public final class ByteArrayTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public ByteArrayTag(byte[] value) { + public ByteArrayTag(final byte[] value) { super(); this.value = value; } @@ -20,32 +21,34 @@ public final class ByteArrayTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public ByteArrayTag(String name, byte[] value) { + public ByteArrayTag(final String name, final byte[] value) { super(name); this.value = value; } @Override public byte[] getValue() { - return value; + return this.value; } @Override public String toString() { - StringBuilder hex = new StringBuilder(); - for (byte b : value) { - String hexDigits = Integer.toHexString(b).toUpperCase(); + final StringBuilder hex = new StringBuilder(); + for (final byte b : this.value) { + final String hexDigits = Integer.toHexString(b).toUpperCase(); if (hexDigits.length() == 1) { hex.append("0"); } hex.append(hexDigits).append(" "); } - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Byte_Array" + append + ": " + hex; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java index 46e247e63..15e355dfc 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java @@ -10,9 +10,10 @@ public final class ByteTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public ByteTag(byte value) { + public ByteTag(final byte value) { super(); this.value = value; } @@ -20,27 +21,29 @@ public final class ByteTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public ByteTag(String name, byte value) { + public ByteTag(final String name, final byte value) { super(name); this.value = value; } @Override public Byte getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Byte" + append + ": " + value; + return "TAG_Byte" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java index 2052d65b3..24159bfcb 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java @@ -15,9 +15,10 @@ public final class CompoundTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public CompoundTag(Map value) { + public CompoundTag(final Map value) { super(); this.value = Collections.unmodifiableMap(value); } @@ -25,10 +26,12 @@ public final class CompoundTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public CompoundTag(String name, Map value) { + public CompoundTag(final String name, final Map value) { super(name); this.value = Collections.unmodifiableMap(value); } @@ -36,25 +39,27 @@ public final class CompoundTag extends Tag { /** * Returns whether this compound tag contains the given key. * - * @param key the given key + * @param key + * the given key * @return true if the tag contains the given key */ - public boolean containsKey(String key) { - return value.containsKey(key); + public boolean containsKey(final String key) { + return this.value.containsKey(key); } @Override public Map getValue() { - return value; + return this.value; } /** * Return a new compound tag with the given values. * - * @param value the value + * @param value + * the value * @return the new compound tag */ - public CompoundTag setValue(Map value) { + public CompoundTag setValue(final Map value) { return new CompoundTag(getName(), value); } @@ -64,23 +69,27 @@ public final class CompoundTag extends Tag { * @return the builder */ public CompoundTagBuilder createBuilder() { - return new CompoundTagBuilder(new HashMap(value)); + return new CompoundTagBuilder(new HashMap(this.value)); } /** * Get a byte array named with the given key. * - *

If the key does not exist or its value is not a byte array tag, - * then an empty byte array will be returned.

+ *

+ * If the key does not exist or its value is not a byte array tag, then an + * empty byte array will be returned. + *

* - * @param key the key + * @param key + * the key * @return a byte array */ - public byte[] getByteArray(String key) { - Tag tag = value.get(key); + public byte[] getByteArray(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ByteArrayTag) { return ((ByteArrayTag) tag).getValue(); - } else { + } + else { return new byte[0]; } } @@ -88,17 +97,21 @@ public final class CompoundTag extends Tag { /** * Get a byte named with the given key. * - *

If the key does not exist or its value is not a byte tag, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a byte tag, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return a byte */ - public byte getByte(String key) { - Tag tag = value.get(key); + public byte getByte(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else { + } + else { return (byte) 0; } } @@ -106,17 +119,21 @@ public final class CompoundTag extends Tag { /** * Get a double named with the given key. * - *

If the key does not exist or its value is not a double tag, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a double tag, then + * {@code 0} will be returned. + *

* - * @param key the key + * @param key + * the key * @return a double */ - public double getDouble(String key) { - Tag tag = value.get(key); + public double getDouble(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -125,33 +142,42 @@ public final class CompoundTag extends Tag { * Get a double named with the given key, even if it's another * type of number. * - *

If the key does not exist or its value is not a number, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a number, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return a double */ - public double asDouble(String key) { - Tag tag = value.get(key); + public double asDouble(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -159,17 +185,21 @@ public final class CompoundTag extends Tag { /** * Get a float named with the given key. * - *

If the key does not exist or its value is not a float tag, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a float tag, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return a float */ - public float getFloat(String key) { - Tag tag = value.get(key); + public float getFloat(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -177,17 +207,21 @@ public final class CompoundTag extends Tag { /** * Get a {@code int[]} named with the given key. * - *

If the key does not exist or its value is not an int array tag, - * then an empty array will be returned.

+ *

+ * If the key does not exist or its value is not an int array tag, then an + * empty array will be returned. + *

* - * @param key the key + * @param key + * the key * @return an int array */ - public int[] getIntArray(String key) { - Tag tag = value.get(key); + public int[] getIntArray(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof IntArrayTag) { return ((IntArrayTag) tag).getValue(); - } else { + } + else { return new int[0]; } } @@ -195,17 +229,21 @@ public final class CompoundTag extends Tag { /** * Get an int named with the given key. * - *

If the key does not exist or its value is not an int tag, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not an int tag, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return an int */ - public int getInt(String key) { - Tag tag = value.get(key); + public int getInt(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -214,33 +252,42 @@ public final class CompoundTag extends Tag { * Get an int named with the given key, even if it's another * type of number. * - *

If the key does not exist or its value is not a number, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a number, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return an int */ - public int asInt(String key) { - Tag tag = value.get(key); + public int asInt(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) { return ((LongTag) tag).getValue().intValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue().intValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue().intValue(); - } else { + } + else { return 0; } } @@ -248,17 +295,21 @@ public final class CompoundTag extends Tag { /** * Get a list of tags named with the given key. * - *

If the key does not exist or its value is not a list tag, - * then an empty list will be returned.

+ *

+ * If the key does not exist or its value is not a list tag, then an empty + * list will be returned. + *

* - * @param key the key + * @param key + * the key * @return a list of tags */ - public List getList(String key) { - Tag tag = value.get(key); + public List getList(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ListTag) { return ((ListTag) tag).getValue(); - } else { + } + else { return Collections.emptyList(); } } @@ -266,45 +317,55 @@ public final class CompoundTag extends Tag { /** * Get a {@code TagList} named with the given key. * - *

If the key does not exist or its value is not a list tag, - * then an empty tag list will be returned.

+ *

+ * If the key does not exist or its value is not a list tag, then an empty + * tag list will be returned. + *

* - * @param key the key + * @param key + * the key * @return a tag list instance */ - public ListTag getListTag(String key) { - Tag tag = value.get(key); + public ListTag getListTag(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ListTag) { return (ListTag) tag; - } else { - return new ListTag(key, StringTag.class, Collections.emptyList()); + } + else { + return new ListTag(key, StringTag.class, Collections. emptyList()); } } /** * Get a list of tags named with the given key. * - *

If the key does not exist or its value is not a list tag, - * then an empty list will be returned. If the given key references - * a list but the list of of a different type, then an empty - * list will also be returned.

+ *

+ * If the key does not exist or its value is not a list tag, then an empty + * list will be returned. If the given key references a list but the list of + * of a different type, then an empty list will also be returned. + *

* - * @param key the key - * @param listType the class of the contained type + * @param key + * the key + * @param listType + * the class of the contained type * @return a list of tags - * @param the type of list + * @param + * the type of list */ @SuppressWarnings("unchecked") - public List getList(String key, Class listType) { - Tag tag = value.get(key); + public List getList(final String key, final Class listType) { + final Tag tag = this.value.get(key); if (tag instanceof ListTag) { - ListTag listTag = (ListTag) tag; + final ListTag listTag = (ListTag) tag; if (listTag.getType().equals(listType)) { return (List) listTag.getValue(); - } else { + } + else { return Collections.emptyList(); } - } else { + } + else { return Collections.emptyList(); } } @@ -312,17 +373,21 @@ public final class CompoundTag extends Tag { /** * Get a long named with the given key. * - *

If the key does not exist or its value is not a long tag, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a long tag, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return a long */ - public long getLong(String key) { - Tag tag = value.get(key); + public long getLong(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof LongTag) { return ((LongTag) tag).getValue(); - } else { + } + else { return 0L; } } @@ -331,33 +396,42 @@ public final class CompoundTag extends Tag { * Get a long named with the given key, even if it's another * type of number. * - *

If the key does not exist or its value is not a number, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a number, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return a long */ - public long asLong(String key) { - Tag tag = value.get(key); + public long asLong(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue().longValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue().longValue(); - } else { + } + else { return 0L; } } @@ -365,17 +439,21 @@ public final class CompoundTag extends Tag { /** * Get a short named with the given key. * - *

If the key does not exist or its value is not a short tag, - * then {@code 0} will be returned.

+ *

+ * If the key does not exist or its value is not a short tag, then {@code 0} + * will be returned. + *

* - * @param key the key + * @param key + * the key * @return a short */ - public short getShort(String key) { - Tag tag = value.get(key); + public short getShort(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -383,31 +461,35 @@ public final class CompoundTag extends Tag { /** * Get a string named with the given key. * - *

If the key does not exist or its value is not a string tag, - * then {@code ""} will be returned.

+ *

+ * If the key does not exist or its value is not a string tag, then + * {@code ""} will be returned. + *

* - * @param key the key + * @param key + * the key * @return a string */ - public String getString(String key) { - Tag tag = value.get(key); + public String getString(final String key) { + final Tag tag = this.value.get(key); if (tag instanceof StringTag) { return ((StringTag) tag).getValue(); - } else { + } + else { return ""; } } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n"); - for (Map.Entry entry : value.entrySet()) { + final StringBuilder bldr = new StringBuilder(); + bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n"); + for (final Map.Entry entry : this.value.entrySet()) { bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); } bldr.append("}"); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java index bdca78428..90b3812b9 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java @@ -1,10 +1,10 @@ package com.intellectualcrafters.jnbt; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.HashMap; import java.util.Map; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Helps create compound tags. */ @@ -22,9 +22,10 @@ public class CompoundTagBuilder { /** * Create a new instance and use the given map (which will be modified). * - * @param value the value + * @param value + * the value */ - CompoundTagBuilder(Map value) { + CompoundTagBuilder(final Map value) { checkNotNull(value); this.entries = value; } @@ -32,14 +33,16 @@ public class CompoundTagBuilder { /** * Put the given key and tag into the compound tag. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder put(String key, Tag value) { + public CompoundTagBuilder put(final String key, final Tag value) { checkNotNull(key); checkNotNull(value); - entries.put(key, value); + this.entries.put(key, value); return this; } @@ -47,47 +50,52 @@ public class CompoundTagBuilder { * Put the given key and value into the compound tag as a * {@code ByteArrayTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putByteArray(String key, byte[] value) { + public CompoundTagBuilder putByteArray(final String key, final byte[] value) { return put(key, new ByteArrayTag(key, value)); } /** - * Put the given key and value into the compound tag as a - * {@code ByteTag}. + * Put the given key and value into the compound tag as a {@code ByteTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putByte(String key, byte value) { + public CompoundTagBuilder putByte(final String key, final byte value) { return put(key, new ByteTag(key, value)); } /** - * Put the given key and value into the compound tag as a - * {@code DoubleTag}. + * Put the given key and value into the compound tag as a {@code DoubleTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putDouble(String key, double value) { + public CompoundTagBuilder putDouble(final String key, final double value) { return put(key, new DoubleTag(key, value)); } /** - * Put the given key and value into the compound tag as a - * {@code FloatTag}. + * Put the given key and value into the compound tag as a {@code FloatTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putFloat(String key, float value) { + public CompoundTagBuilder putFloat(final String key, final float value) { return put(key, new FloatTag(key, value)); } @@ -95,70 +103,78 @@ public class CompoundTagBuilder { * Put the given key and value into the compound tag as a * {@code IntArrayTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putIntArray(String key, int[] value) { + public CompoundTagBuilder putIntArray(final String key, final int[] value) { return put(key, new IntArrayTag(key, value)); } /** * Put the given key and value into the compound tag as an {@code IntTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putInt(String key, int value) { + public CompoundTagBuilder putInt(final String key, final int value) { return put(key, new IntTag(key, value)); } /** - * Put the given key and value into the compound tag as a - * {@code LongTag}. + * Put the given key and value into the compound tag as a {@code LongTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putLong(String key, long value) { + public CompoundTagBuilder putLong(final String key, final long value) { return put(key, new LongTag(key, value)); } /** - * Put the given key and value into the compound tag as a - * {@code ShortTag}. + * Put the given key and value into the compound tag as a {@code ShortTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putShort(String key, short value) { + public CompoundTagBuilder putShort(final String key, final short value) { return put(key, new ShortTag(key, value)); } /** - * Put the given key and value into the compound tag as a - * {@code StringTag}. + * Put the given key and value into the compound tag as a {@code StringTag}. * - * @param key they key - * @param value the value + * @param key + * they key + * @param value + * the value * @return this object */ - public CompoundTagBuilder putString(String key, String value) { + public CompoundTagBuilder putString(final String key, final String value) { return put(key, new StringTag(key, value)); } /** * Put all the entries from the given map into this map. * - * @param value the map of tags + * @param value + * the map of tags * @return this object */ - public CompoundTagBuilder putAll(Map value) { + public CompoundTagBuilder putAll(final Map value) { checkNotNull(value); - for (Map.Entry entry : value.entrySet()) { + for (final Map.Entry entry : value.entrySet()) { put(entry.getKey(), entry.getValue()); } return this; @@ -170,17 +186,18 @@ public class CompoundTagBuilder { * @return the new compound tag */ public CompoundTag build() { - return new CompoundTag(new HashMap(entries)); + return new CompoundTag(new HashMap(this.entries)); } /** * Build a new compound tag with this builder's entries. * - * @param name the name of the tag + * @param name + * the name of the tag * @return the created compound tag */ - public CompoundTag build(String name) { - return new CompoundTag(name, new HashMap(entries)); + public CompoundTag build(final String name) { + return new CompoundTag(name, new HashMap(this.entries)); } /** diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java index b660eb681..d4ce6f75c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java @@ -2,7 +2,7 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Double} tag. - * + * */ public final class DoubleTag extends Tag { @@ -11,9 +11,10 @@ public final class DoubleTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public DoubleTag(double value) { + public DoubleTag(final double value) { super(); this.value = value; } @@ -21,27 +22,29 @@ public final class DoubleTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public DoubleTag(String name, double value) { + public DoubleTag(final String name, final double value) { super(name); this.value = value; } @Override public Double getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Double" + append + ": " + value; + return "TAG_Double" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java index ad333dad1..32dbe86ff 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java @@ -10,9 +10,10 @@ public final class FloatTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public FloatTag(float value) { + public FloatTag(final float value) { super(); this.value = value; } @@ -20,27 +21,29 @@ public final class FloatTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public FloatTag(String name, float value) { + public FloatTag(final String name, final float value) { super(name); this.value = value; } @Override public Float getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Float" + append + ": " + value; + return "TAG_Float" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java index 4c80b1cf7..bfca5e264 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java @@ -12,9 +12,10 @@ public final class IntArrayTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public IntArrayTag(int[] value) { + public IntArrayTag(final int[] value) { super(); checkNotNull(value); this.value = value; @@ -23,10 +24,12 @@ public final class IntArrayTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public IntArrayTag(String name, int[] value) { + public IntArrayTag(final String name, final int[] value) { super(name); checkNotNull(value); this.value = value; @@ -34,22 +37,22 @@ public final class IntArrayTag extends Tag { @Override public int[] getValue() { - return value; + return this.value; } @Override public String toString() { - StringBuilder hex = new StringBuilder(); - for (int b : value) { - String hexDigits = Integer.toHexString(b).toUpperCase(); + final StringBuilder hex = new StringBuilder(); + for (final int b : this.value) { + final String hexDigits = Integer.toHexString(b).toUpperCase(); if (hexDigits.length() == 1) { hex.append("0"); } hex.append(hexDigits).append(" "); } - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Int_Array" + append + ": " + hex; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntTag.java index bea176238..334e347df 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/IntTag.java @@ -10,9 +10,10 @@ public final class IntTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public IntTag(int value) { + public IntTag(final int value) { super(); this.value = value; } @@ -20,27 +21,29 @@ public final class IntTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public IntTag(String name, int value) { + public IntTag(final String name, final int value) { super(name); this.value = value; } @Override public Integer getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Int" + append + ": " + value; + return "TAG_Int" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTag.java index bea5d8158..04272d8c0 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTag.java @@ -1,11 +1,12 @@ package com.intellectualcrafters.jnbt; -import javax.annotation.Nullable; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; -import static com.google.common.base.Preconditions.checkNotNull; +import javax.annotation.Nullable; /** * The {@code TAG_List} tag. @@ -13,15 +14,17 @@ import static com.google.common.base.Preconditions.checkNotNull; public final class ListTag extends Tag { private final Class type; - private final List value; + private final List value; /** * Creates the tag with an empty name. * - * @param type the type of tag - * @param value the value of the tag + * @param type + * the type of tag + * @param value + * the value of the tag */ - public ListTag(Class type, List value) { + public ListTag(final Class type, final List value) { super(); checkNotNull(value); this.type = type; @@ -31,11 +34,14 @@ public final class ListTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param type the type of tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param type + * the type of tag + * @param value + * the value of the tag */ - public ListTag(String name, Class type, List value) { + public ListTag(final String name, final Class type, final List value) { super(name); checkNotNull(value); this.type = type; @@ -48,35 +54,38 @@ public final class ListTag extends Tag { * @return The type of item in this list. */ public Class getType() { - return type; + return this.type; } @Override public List getValue() { - return value; + return this.value; } /** * Create a new list tag with this tag's name and type. * - * @param list the new list + * @param list + * the new list * @return a new list tag */ - public ListTag setValue(List list) { + public ListTag setValue(final List list) { return new ListTag(getName(), getType(), list); } /** * Get the tag if it exists at the given index. - * - * @param index the index + * + * @param index + * the index * @return the tag or null */ @Nullable - public Tag getIfExists(int index) { + public Tag getIfExists(final int index) { try { - return value.get(index); - } catch (NoSuchElementException e) { + return this.value.get(index); + } + catch (final NoSuchElementException e) { return null; } } @@ -84,17 +93,21 @@ public final class ListTag extends Tag { /** * Get a byte array named with the given index. * - *

If the index does not exist or its value is not a byte array tag, - * then an empty byte array will be returned.

+ *

+ * If the index does not exist or its value is not a byte array tag, then an + * empty byte array will be returned. + *

* - * @param index the index + * @param index + * the index * @return a byte array */ - public byte[] getByteArray(int index) { - Tag tag = getIfExists(index); + public byte[] getByteArray(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ByteArrayTag) { return ((ByteArrayTag) tag).getValue(); - } else { + } + else { return new byte[0]; } } @@ -102,17 +115,21 @@ public final class ListTag extends Tag { /** * Get a byte named with the given index. * - *

If the index does not exist or its value is not a byte tag, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a byte tag, then + * {@code 0} will be returned. + *

* - * @param index the index + * @param index + * the index * @return a byte */ - public byte getByte(int index) { - Tag tag = getIfExists(index); + public byte getByte(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else { + } + else { return (byte) 0; } } @@ -120,17 +137,21 @@ public final class ListTag extends Tag { /** * Get a double named with the given index. * - *

If the index does not exist or its value is not a double tag, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a double tag, then + * {@code 0} will be returned. + *

* - * @param index the index + * @param index + * the index * @return a double */ - public double getDouble(int index) { - Tag tag = getIfExists(index); + public double getDouble(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -139,33 +160,42 @@ public final class ListTag extends Tag { * Get a double named with the given index, even if it's another * type of number. * - *

If the index does not exist or its value is not a number, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a number, then {@code 0} + * will be returned. + *

* - * @param index the index + * @param index + * the index * @return a double */ - public double asDouble(int index) { - Tag tag = getIfExists(index); + public double asDouble(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -173,17 +203,21 @@ public final class ListTag extends Tag { /** * Get a float named with the given index. * - *

If the index does not exist or its value is not a float tag, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a float tag, then + * {@code 0} will be returned. + *

* - * @param index the index + * @param index + * the index * @return a float */ - public float getFloat(int index) { - Tag tag = getIfExists(index); + public float getFloat(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -191,17 +225,21 @@ public final class ListTag extends Tag { /** * Get a {@code int[]} named with the given index. * - *

If the index does not exist or its value is not an int array tag, - * then an empty array will be returned.

+ *

+ * If the index does not exist or its value is not an int array tag, then an + * empty array will be returned. + *

* - * @param index the index + * @param index + * the index * @return an int array */ - public int[] getIntArray(int index) { - Tag tag = getIfExists(index); + public int[] getIntArray(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof IntArrayTag) { return ((IntArrayTag) tag).getValue(); - } else { + } + else { return new int[0]; } } @@ -209,17 +247,21 @@ public final class ListTag extends Tag { /** * Get an int named with the given index. * - *

If the index does not exist or its value is not an int tag, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not an int tag, then + * {@code 0} will be returned. + *

* - * @param index the index + * @param index + * the index * @return an int */ - public int getInt(int index) { - Tag tag = getIfExists(index); + public int getInt(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -228,33 +270,42 @@ public final class ListTag extends Tag { * Get an int named with the given index, even if it's another * type of number. * - *

If the index does not exist or its value is not a number, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a number, then {@code 0} + * will be returned. + *

* - * @param index the index + * @param index + * the index * @return an int */ - public int asInt(int index) { - Tag tag = getIfExists(index); + public int asInt(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) { return ((LongTag) tag).getValue().intValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue().intValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue().intValue(); - } else { + } + else { return 0; } } @@ -262,17 +313,21 @@ public final class ListTag extends Tag { /** * Get a list of tags named with the given index. * - *

If the index does not exist or its value is not a list tag, - * then an empty list will be returned.

+ *

+ * If the index does not exist or its value is not a list tag, then an empty + * list will be returned. + *

* - * @param index the index + * @param index + * the index * @return a list of tags */ - public List getList(int index) { - Tag tag = getIfExists(index); + public List getList(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ListTag) { return ((ListTag) tag).getValue(); - } else { + } + else { return Collections.emptyList(); } } @@ -280,45 +335,55 @@ public final class ListTag extends Tag { /** * Get a {@code TagList} named with the given index. * - *

If the index does not exist or its value is not a list tag, - * then an empty tag list will be returned.

+ *

+ * If the index does not exist or its value is not a list tag, then an empty + * tag list will be returned. + *

* - * @param index the index + * @param index + * the index * @return a tag list instance */ - public ListTag getListTag(int index) { - Tag tag = getIfExists(index); + public ListTag getListTag(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ListTag) { return (ListTag) tag; - } else { - return new ListTag(StringTag.class, Collections.emptyList()); + } + else { + return new ListTag(StringTag.class, Collections. emptyList()); } } /** * Get a list of tags named with the given index. * - *

If the index does not exist or its value is not a list tag, - * then an empty list will be returned. If the given index references - * a list but the list of of a different type, then an empty - * list will also be returned.

+ *

+ * If the index does not exist or its value is not a list tag, then an empty + * list will be returned. If the given index references a list but the list + * of of a different type, then an empty list will also be returned. + *

* - * @param index the index - * @param listType the class of the contained type + * @param index + * the index + * @param listType + * the class of the contained type * @return a list of tags - * @param the NBT type + * @param + * the NBT type */ @SuppressWarnings("unchecked") - public List getList(int index, Class listType) { - Tag tag = getIfExists(index); + public List getList(final int index, final Class listType) { + final Tag tag = getIfExists(index); if (tag instanceof ListTag) { - ListTag listTag = (ListTag) tag; + final ListTag listTag = (ListTag) tag; if (listTag.getType().equals(listType)) { return (List) listTag.getValue(); - } else { + } + else { return Collections.emptyList(); } - } else { + } + else { return Collections.emptyList(); } } @@ -326,17 +391,21 @@ public final class ListTag extends Tag { /** * Get a long named with the given index. * - *

If the index does not exist or its value is not a long tag, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a long tag, then + * {@code 0} will be returned. + *

* - * @param index the index + * @param index + * the index * @return a long */ - public long getLong(int index) { - Tag tag = getIfExists(index); + public long getLong(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof LongTag) { return ((LongTag) tag).getValue(); - } else { + } + else { return 0L; } } @@ -345,33 +414,42 @@ public final class ListTag extends Tag { * Get a long named with the given index, even if it's another * type of number. * - *

If the index does not exist or its value is not a number, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a number, then {@code 0} + * will be returned. + *

* - * @param index the index + * @param index + * the index * @return a long */ - public long asLong(int index) { - Tag tag = getIfExists(index); + public long asLong(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ByteTag) { return ((ByteTag) tag).getValue(); - } else if (tag instanceof ShortTag) { + } + else if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else if (tag instanceof IntTag) { + } + else if (tag instanceof IntTag) { return ((IntTag) tag).getValue(); - } else if (tag instanceof LongTag) { + } + else if (tag instanceof LongTag) { return ((LongTag) tag).getValue(); - } else if (tag instanceof FloatTag) { + } + else if (tag instanceof FloatTag) { return ((FloatTag) tag).getValue().longValue(); - } else if (tag instanceof DoubleTag) { + } + else if (tag instanceof DoubleTag) { return ((DoubleTag) tag).getValue().longValue(); - } else { + } + else { return 0; } } @@ -379,17 +457,21 @@ public final class ListTag extends Tag { /** * Get a short named with the given index. * - *

If the index does not exist or its value is not a short tag, - * then {@code 0} will be returned.

+ *

+ * If the index does not exist or its value is not a short tag, then + * {@code 0} will be returned. + *

* - * @param index the index + * @param index + * the index * @return a short */ - public short getShort(int index) { - Tag tag = getIfExists(index); + public short getShort(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof ShortTag) { return ((ShortTag) tag).getValue(); - } else { + } + else { return 0; } } @@ -397,31 +479,35 @@ public final class ListTag extends Tag { /** * Get a string named with the given index. * - *

If the index does not exist or its value is not a string tag, - * then {@code ""} will be returned.

+ *

+ * If the index does not exist or its value is not a string tag, then + * {@code ""} will be returned. + *

* - * @param index the index + * @param index + * the index * @return a string */ - public String getString(int index) { - Tag tag = getIfExists(index); + public String getString(final int index) { + final Tag tag = getIfExists(index); if (tag instanceof StringTag) { return ((StringTag) tag).getValue(); - } else { + } + else { return ""; } } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_List").append(append).append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n"); - for (Tag t : value) { + final StringBuilder bldr = new StringBuilder(); + bldr.append("TAG_List").append(append).append(": ").append(this.value.size()).append(" entries of type ").append(NBTUtils.getTypeName(this.type)).append("\r\n{\r\n"); + for (final Tag t : this.value) { bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); } bldr.append("}"); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java index 758bc52eb..322bdf514 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java @@ -1,26 +1,27 @@ package com.intellectualcrafters.jnbt; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Helps create list tags. */ public class ListTagBuilder { private final Class type; - private final List entries; + private final List entries; /** * Create a new instance. * - * @param type of tag contained in this list + * @param type + * of tag contained in this list */ - ListTagBuilder(Class type) { + ListTagBuilder(final Class type) { checkNotNull(type); this.type = type; this.entries = new ArrayList(); @@ -29,27 +30,29 @@ public class ListTagBuilder { /** * Add the given tag. * - * @param value the tag + * @param value + * the tag * @return this object */ - public ListTagBuilder add(Tag value) { + public ListTagBuilder add(final Tag value) { checkNotNull(value); - if (!type.isInstance(value)) { - throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName()); + if (!this.type.isInstance(value)) { + throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + this.type.getCanonicalName()); } - entries.add(value); + this.entries.add(value); return this; } /** * Add all the tags in the given list. * - * @param value a list of tags + * @param value + * a list of tags * @return this object */ - public ListTagBuilder addAll(Collection value) { + public ListTagBuilder addAll(final Collection value) { checkNotNull(value); - for (Tag v : value) { + for (final Tag v : value) { add(v); } return this; @@ -61,17 +64,18 @@ public class ListTagBuilder { * @return the new list tag */ public ListTag build() { - return new ListTag(type, new ArrayList(entries)); + return new ListTag(this.type, new ArrayList(this.entries)); } /** * Build a new list tag with this builder's entries. * - * @param name the name of the tag + * @param name + * the name of the tag * @return the created list tag */ - public ListTag build(String name) { - return new ListTag(name, type, new ArrayList(entries)); + public ListTag build(final String name) { + return new ListTag(name, this.type, new ArrayList(this.entries)); } /** @@ -79,7 +83,7 @@ public class ListTagBuilder { * * @return a new builder */ - public static ListTagBuilder create(Class type) { + public static ListTagBuilder create(final Class type) { return new ListTagBuilder(type); } @@ -88,21 +92,21 @@ public class ListTagBuilder { * * @return a new builder */ - public static ListTagBuilder createWith(T ... entries) { + public static ListTagBuilder createWith(final T... entries) { checkNotNull(entries); if (entries.length == 0) { throw new IllegalArgumentException("This method needs an array of at least one entry"); } - Class type = entries[0].getClass(); + final Class type = entries[0].getClass(); for (int i = 1; i < entries.length; i++) { if (!type.isInstance(entries[i])) { throw new IllegalArgumentException("An array of different tag types was provided"); } } - ListTagBuilder builder = new ListTagBuilder(type); + final ListTagBuilder builder = new ListTagBuilder(type); builder.addAll(Arrays.asList(entries)); return builder; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/LongTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/LongTag.java index 19ab6b44f..bf48de965 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/LongTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/LongTag.java @@ -2,7 +2,7 @@ package com.intellectualcrafters.jnbt; /** * The {@code TAG_Long} tag. - * + * */ public final class LongTag extends Tag { @@ -11,9 +11,10 @@ public final class LongTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public LongTag(long value) { + public LongTag(final long value) { super(); this.value = value; } @@ -21,27 +22,29 @@ public final class LongTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public LongTag(String name, long value) { + public LongTag(final String name, final long value) { super(name); this.value = value; } @Override public Long getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Long" + append + ": " + value; + return "TAG_Long" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java index f1bef6d4f..ab2e6d557 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java @@ -9,10 +9,7 @@ public final class NBTConstants { public static final Charset CHARSET = Charset.forName("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; + 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; /** * Default private constructor. @@ -20,42 +17,44 @@ public final class NBTConstants { private NBTConstants() { } - + /** * Convert a type ID to its corresponding {@link Tag} class. - * - * @param id type ID + * + * @param id + * type ID * @return tag class - * @throws IllegalArgumentException thrown if the tag ID is not valid + * @throws IllegalArgumentException + * thrown if the tag ID is not valid */ - public static Class getClassFromType(int id) { + public static Class getClassFromType(final int id) { switch (id) { - case TYPE_END: - return EndTag.class; - case TYPE_BYTE: - return ByteTag.class; - case TYPE_SHORT: - return ShortTag.class; - case TYPE_INT: - return IntTag.class; - case TYPE_LONG: - return LongTag.class; - case TYPE_FLOAT: - return FloatTag.class; - case TYPE_DOUBLE: - return DoubleTag.class; - case TYPE_BYTE_ARRAY: - return ByteArrayTag.class; - case TYPE_STRING: - return StringTag.class; - case TYPE_LIST: - return ListTag.class; - case TYPE_COMPOUND: - return CompoundTag.class; - case TYPE_INT_ARRAY: - return IntArrayTag.class; - default: - throw new IllegalArgumentException("Unknown tag type ID of " + id); + case TYPE_END: + return EndTag.class; + case TYPE_BYTE: + return ByteTag.class; + case TYPE_SHORT: + return ShortTag.class; + case TYPE_INT: + return IntTag.class; + case TYPE_LONG: + return LongTag.class; + case TYPE_FLOAT: + return FloatTag.class; + case TYPE_DOUBLE: + return DoubleTag.class; + case TYPE_BYTE_ARRAY: + return ByteArrayTag.class; + case TYPE_STRING: + return StringTag.class; + case TYPE_LIST: + return ListTag.class; + case TYPE_COMPOUND: + return CompoundTag.class; + case TYPE_INT_ARRAY: + return IntArrayTag.class; + default: + throw new IllegalArgumentException("Unknown tag type ID of " + id); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java index fc6609f35..a6fe45b6c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java @@ -13,10 +13,12 @@ import java.util.Map; * This class reads NBT, or Named Binary Tag * streams, and produces an object graph of subclasses of the {@code Tag} * object. - * - *

The NBT format was created by Markus Persson, and the specification may be + * + *

+ * The NBT format was created by Markus Persson, and the specification may be * found at - * http://www.minecraft.net/docs/NBT.txt.

+ * http://www.minecraft.net/docs/NBT.txt. + *

*/ public final class NBTInputStream implements Closeable { @@ -25,19 +27,22 @@ public final class NBTInputStream implements Closeable { /** * Creates a new {@code NBTInputStream}, which will source its data * from the specified input stream. - * - * @param is the input stream - * @throws IOException if an I/O error occurs + * + * @param is + * the input stream + * @throws IOException + * if an I/O error occurs */ - public NBTInputStream(InputStream is) throws IOException { + public NBTInputStream(final InputStream is) throws IOException { this.is = new DataInputStream(is); } /** * Reads an NBT tag from the stream. - * + * * @return The tag that was read. - * @throws IOException if an I/O error occurs. + * @throws IOException + * if an I/O error occurs. */ public Tag readTag() throws IOException { return readTag(0); @@ -45,21 +50,24 @@ public final class NBTInputStream implements Closeable { /** * Reads an NBT from the stream. - * - * @param depth the depth of this tag + * + * @param depth + * the depth of this tag * @return The tag that was read. - * @throws IOException if an I/O error occurs. + * @throws IOException + * if an I/O error occurs. */ - private Tag readTag(int depth) throws IOException { - int type = is.readByte() & 0xFF; + private Tag readTag(final int depth) throws IOException { + final int type = this.is.readByte() & 0xFF; String name; if (type != NBTConstants.TYPE_END) { - int nameLength = is.readShort() & 0xFFFF; - byte[] nameBytes = new byte[nameLength]; - is.readFully(nameBytes); + final int nameLength = this.is.readShort() & 0xFFFF; + final byte[] nameBytes = new byte[nameLength]; + this.is.readFully(nameBytes); name = new String(nameBytes, NBTConstants.CHARSET); - } else { + } + else { name = ""; } @@ -68,85 +76,90 @@ public final class NBTInputStream implements Closeable { /** * Reads the payload of a tag, given the name and type. - * - * @param type the type - * @param name the name - * @param depth the depth + * + * @param type + * the type + * @param name + * the name + * @param depth + * the depth * @return the tag - * @throws IOException if an I/O error occurs. + * @throws IOException + * if an I/O error occurs. */ - private Tag readTagPayload(int type, String name, int depth) throws IOException { + private Tag readTagPayload(final int type, final String name, final int depth) throws IOException { switch (type) { - case NBTConstants.TYPE_END: - if (depth == 0) { - throw new IOException( - "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); - } else { - return new EndTag(); - } - case NBTConstants.TYPE_BYTE: - return new ByteTag(name, is.readByte()); - case NBTConstants.TYPE_SHORT: - return new ShortTag(name, is.readShort()); - case NBTConstants.TYPE_INT: - return new IntTag(name, is.readInt()); - case NBTConstants.TYPE_LONG: - return new LongTag(name, is.readLong()); - case NBTConstants.TYPE_FLOAT: - return new FloatTag(name, is.readFloat()); - case NBTConstants.TYPE_DOUBLE: - return new DoubleTag(name, is.readDouble()); - case NBTConstants.TYPE_BYTE_ARRAY: - int length = is.readInt(); - byte[] bytes = new byte[length]; - is.readFully(bytes); - return new ByteArrayTag(name, bytes); - case NBTConstants.TYPE_STRING: - length = is.readShort(); - bytes = new byte[length]; - is.readFully(bytes); - return new StringTag(name, new String(bytes, NBTConstants.CHARSET)); - case NBTConstants.TYPE_LIST: - int childType = is.readByte(); - length = is.readInt(); - - List tagList = new ArrayList(); - for (int i = 0; i < length; ++i) { - Tag tag = readTagPayload(childType, "", depth + 1); - if (tag instanceof EndTag) { - throw new IOException("TAG_End not permitted in a list."); + case NBTConstants.TYPE_END: + if (depth == 0) { + throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it."); } - tagList.add(tag); - } - - return new ListTag(name, NBTUtils.getTypeClass(childType), tagList); - case NBTConstants.TYPE_COMPOUND: - Map tagMap = new HashMap(); - while (true) { - Tag tag = readTag(depth + 1); - if (tag instanceof EndTag) { - break; - } else { - tagMap.put(tag.getName(), tag); + else { + return new EndTag(); } - } + case NBTConstants.TYPE_BYTE: + return new ByteTag(name, this.is.readByte()); + case NBTConstants.TYPE_SHORT: + return new ShortTag(name, this.is.readShort()); + case NBTConstants.TYPE_INT: + return new IntTag(name, this.is.readInt()); + case NBTConstants.TYPE_LONG: + return new LongTag(name, this.is.readLong()); + case NBTConstants.TYPE_FLOAT: + return new FloatTag(name, this.is.readFloat()); + case NBTConstants.TYPE_DOUBLE: + return new DoubleTag(name, this.is.readDouble()); + case NBTConstants.TYPE_BYTE_ARRAY: + int length = this.is.readInt(); + byte[] bytes = new byte[length]; + this.is.readFully(bytes); + return new ByteArrayTag(name, bytes); + case NBTConstants.TYPE_STRING: + length = this.is.readShort(); + bytes = new byte[length]; + this.is.readFully(bytes); + return new StringTag(name, new String(bytes, NBTConstants.CHARSET)); + case NBTConstants.TYPE_LIST: + final int childType = this.is.readByte(); + length = this.is.readInt(); - return new CompoundTag(name, tagMap); - case NBTConstants.TYPE_INT_ARRAY: - length = is.readInt(); - int[] data = new int[length]; - for (int i = 0; i < length; i++) { - data[i] = is.readInt(); - } - return new IntArrayTag(name, data); - default: - throw new IOException("Invalid tag type: " + type + "."); + final List tagList = new ArrayList(); + for (int i = 0; i < length; ++i) { + final Tag tag = readTagPayload(childType, "", depth + 1); + if (tag instanceof EndTag) { + throw new IOException("TAG_End not permitted in a list."); + } + tagList.add(tag); + } + + return new ListTag(name, NBTUtils.getTypeClass(childType), tagList); + case NBTConstants.TYPE_COMPOUND: + final Map tagMap = new HashMap(); + while (true) { + final Tag tag = readTag(depth + 1); + if (tag instanceof EndTag) { + break; + } + else { + tagMap.put(tag.getName(), tag); + } + } + + return new CompoundTag(name, tagMap); + case NBTConstants.TYPE_INT_ARRAY: + length = this.is.readInt(); + final int[] data = new int[length]; + for (int i = 0; i < length; i++) { + data[i] = this.is.readInt(); + } + return new IntArrayTag(name, data); + default: + throw new IOException("Invalid tag type: " + type + "."); } } @Override public void close() throws IOException { - is.close(); + this.is.close(); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java index 37a004268..acfe18a1c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java @@ -11,15 +11,15 @@ import java.util.List; * This class writes NBT, or Named Binary Tag * Tag objects to an underlying OutputStream. *

- * + * *

* The NBT format was created by Markus Persson, and the specification may be * found at * http://www.minecraft.net/docs/NBT.txt. *

- * + * * @author Graham Edgecombe - * + * */ public final class NBTOutputStream implements Closeable { @@ -31,32 +31,32 @@ public final class NBTOutputStream implements Closeable { /** * Creates a new NBTOutputStream, which will write data to the * specified underlying output stream. - * + * * @param os * The output stream. * @throws IOException * if an I/O error occurs. */ - public NBTOutputStream(OutputStream os) throws IOException { + public NBTOutputStream(final OutputStream os) throws IOException { this.os = new DataOutputStream(os); } /** * Writes a tag. - * + * * @param tag * The tag to write. * @throws IOException * if an I/O error occurs. */ - public void writeTag(Tag tag) throws IOException { - int type = NBTUtils.getTypeCode(tag.getClass()); - String name = tag.getName(); - byte[] nameBytes = name.getBytes(NBTConstants.CHARSET); + public void writeTag(final Tag tag) throws IOException { + final int type = NBTUtils.getTypeCode(tag.getClass()); + final String name = tag.getName(); + final byte[] nameBytes = name.getBytes(NBTConstants.CHARSET); - os.writeByte(type); - os.writeShort(nameBytes.length); - os.write(nameBytes); + this.os.writeByte(type); + this.os.writeShort(nameBytes.length); + this.os.write(nameBytes); if (type == NBTConstants.TYPE_END) { throw new IOException("Named TAG_End not permitted."); @@ -67,112 +67,112 @@ public final class NBTOutputStream implements Closeable { /** * Writes tag payload. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeTagPayload(Tag tag) throws IOException { - int type = NBTUtils.getTypeCode(tag.getClass()); + private void writeTagPayload(final Tag tag) throws IOException { + final int type = NBTUtils.getTypeCode(tag.getClass()); switch (type) { - case NBTConstants.TYPE_END: - writeEndTagPayload((EndTag) tag); - break; - case NBTConstants.TYPE_BYTE: - writeByteTagPayload((ByteTag) tag); - break; - case NBTConstants.TYPE_SHORT: - writeShortTagPayload((ShortTag) tag); - break; - case NBTConstants.TYPE_INT: - writeIntTagPayload((IntTag) tag); - break; - case NBTConstants.TYPE_LONG: - writeLongTagPayload((LongTag) tag); - break; - case NBTConstants.TYPE_FLOAT: - writeFloatTagPayload((FloatTag) tag); - break; - case NBTConstants.TYPE_DOUBLE: - writeDoubleTagPayload((DoubleTag) tag); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - writeByteArrayTagPayload((ByteArrayTag) tag); - break; - case NBTConstants.TYPE_STRING: - writeStringTagPayload((StringTag) tag); - break; - case NBTConstants.TYPE_LIST: - writeListTagPayload((ListTag) tag); - break; - case NBTConstants.TYPE_COMPOUND: - writeCompoundTagPayload((CompoundTag) tag); - break; - case NBTConstants.TYPE_INT_ARRAY: - writeIntArrayTagPayload((IntArrayTag) tag); - break; - default: - throw new IOException("Invalid tag type: " + type + "."); + case NBTConstants.TYPE_END: + writeEndTagPayload((EndTag) tag); + break; + case NBTConstants.TYPE_BYTE: + writeByteTagPayload((ByteTag) tag); + break; + case NBTConstants.TYPE_SHORT: + writeShortTagPayload((ShortTag) tag); + break; + case NBTConstants.TYPE_INT: + writeIntTagPayload((IntTag) tag); + break; + case NBTConstants.TYPE_LONG: + writeLongTagPayload((LongTag) tag); + break; + case NBTConstants.TYPE_FLOAT: + writeFloatTagPayload((FloatTag) tag); + break; + case NBTConstants.TYPE_DOUBLE: + writeDoubleTagPayload((DoubleTag) tag); + break; + case NBTConstants.TYPE_BYTE_ARRAY: + writeByteArrayTagPayload((ByteArrayTag) tag); + break; + case NBTConstants.TYPE_STRING: + writeStringTagPayload((StringTag) tag); + break; + case NBTConstants.TYPE_LIST: + writeListTagPayload((ListTag) tag); + break; + case NBTConstants.TYPE_COMPOUND: + writeCompoundTagPayload((CompoundTag) tag); + break; + case NBTConstants.TYPE_INT_ARRAY: + writeIntArrayTagPayload((IntArrayTag) tag); + break; + default: + throw new IOException("Invalid tag type: " + type + "."); } } /** * Writes a TAG_Byte tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeByteTagPayload(ByteTag tag) throws IOException { - os.writeByte(tag.getValue()); + private void writeByteTagPayload(final ByteTag tag) throws IOException { + this.os.writeByte(tag.getValue()); } /** * Writes a TAG_Byte_Array tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeByteArrayTagPayload(ByteArrayTag tag) throws IOException { - byte[] bytes = tag.getValue(); - os.writeInt(bytes.length); - os.write(bytes); + private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException { + final byte[] bytes = tag.getValue(); + this.os.writeInt(bytes.length); + this.os.write(bytes); } /** * Writes a TAG_Compound tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeCompoundTagPayload(CompoundTag tag) throws IOException { - for (Tag childTag : tag.getValue().values()) { + private void writeCompoundTagPayload(final CompoundTag tag) throws IOException { + for (final Tag childTag : tag.getValue().values()) { writeTag(childTag); } - os.writeByte((byte) 0); // end tag - better way? + this.os.writeByte((byte) 0); // end tag - better way? } /** * Writes a TAG_List tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeListTagPayload(ListTag tag) throws IOException { - Class clazz = tag.getType(); - List tags = tag.getValue(); - int size = tags.size(); + private void writeListTagPayload(final ListTag tag) throws IOException { + final Class clazz = tag.getType(); + final List tags = tag.getValue(); + final int size = tags.size(); - os.writeByte(NBTUtils.getTypeCode(clazz)); - os.writeInt(size); + this.os.writeByte(NBTUtils.getTypeCode(clazz)); + this.os.writeInt(size); for (int i = 0; i < size; ++i) { writeTagPayload(tags.get(i)); } @@ -180,100 +180,101 @@ public final class NBTOutputStream implements Closeable { /** * Writes a TAG_String tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeStringTagPayload(StringTag tag) throws IOException { - byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET); - os.writeShort(bytes.length); - os.write(bytes); + private void writeStringTagPayload(final StringTag tag) throws IOException { + final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET); + this.os.writeShort(bytes.length); + this.os.write(bytes); } /** * Writes a TAG_Double tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeDoubleTagPayload(DoubleTag tag) throws IOException { - os.writeDouble(tag.getValue()); + private void writeDoubleTagPayload(final DoubleTag tag) throws IOException { + this.os.writeDouble(tag.getValue()); } /** * Writes a TAG_Float tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeFloatTagPayload(FloatTag tag) throws IOException { - os.writeFloat(tag.getValue()); + private void writeFloatTagPayload(final FloatTag tag) throws IOException { + this.os.writeFloat(tag.getValue()); } /** * Writes a TAG_Long tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeLongTagPayload(LongTag tag) throws IOException { - os.writeLong(tag.getValue()); + private void writeLongTagPayload(final LongTag tag) throws IOException { + this.os.writeLong(tag.getValue()); } /** * Writes a TAG_Int tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeIntTagPayload(IntTag tag) throws IOException { - os.writeInt(tag.getValue()); + private void writeIntTagPayload(final IntTag tag) throws IOException { + this.os.writeInt(tag.getValue()); } /** * Writes a TAG_Short tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeShortTagPayload(ShortTag tag) throws IOException { - os.writeShort(tag.getValue()); + private void writeShortTagPayload(final ShortTag tag) throws IOException { + this.os.writeShort(tag.getValue()); } /** * Writes a TAG_Empty tag. - * + * * @param tag * The tag. * @throws IOException * if an I/O error occurs. */ - private void writeEndTagPayload(EndTag tag) { + private void writeEndTagPayload(final EndTag tag) { /* empty */ } - - private void writeIntArrayTagPayload(IntArrayTag tag) throws IOException { - int[] data = tag.getValue(); - os.writeInt(data.length); - for (int i = 0; i < data.length; i++) { - os.writeInt(data[i]); - } + + private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException { + final int[] data = tag.getValue(); + this.os.writeInt(data.length); + for (final int element : data) { + this.os.writeInt(element); + } } + @Override public void close() throws IOException { - os.close(); + this.os.close(); } -} \ No newline at end of file +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java index 611f109df..06dd71b4f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java @@ -17,131 +17,160 @@ public final class NBTUtils { /** * Gets the type name of a tag. * - * @param clazz the tag class + * @param clazz + * the tag class * @return The type name. */ - public static String getTypeName(Class clazz) { + public static String getTypeName(final Class clazz) { if (clazz.equals(ByteArrayTag.class)) { return "TAG_Byte_Array"; - } else if (clazz.equals(ByteTag.class)) { + } + else if (clazz.equals(ByteTag.class)) { return "TAG_Byte"; - } else if (clazz.equals(CompoundTag.class)) { + } + else if (clazz.equals(CompoundTag.class)) { return "TAG_Compound"; - } else if (clazz.equals(DoubleTag.class)) { + } + else if (clazz.equals(DoubleTag.class)) { return "TAG_Double"; - } else if (clazz.equals(EndTag.class)) { + } + else if (clazz.equals(EndTag.class)) { return "TAG_End"; - } else if (clazz.equals(FloatTag.class)) { + } + else if (clazz.equals(FloatTag.class)) { return "TAG_Float"; - } else if (clazz.equals(IntTag.class)) { + } + else if (clazz.equals(IntTag.class)) { return "TAG_Int"; - } else if (clazz.equals(ListTag.class)) { + } + else if (clazz.equals(ListTag.class)) { return "TAG_List"; - } else if (clazz.equals(LongTag.class)) { + } + else if (clazz.equals(LongTag.class)) { return "TAG_Long"; - } else if (clazz.equals(ShortTag.class)) { + } + else if (clazz.equals(ShortTag.class)) { return "TAG_Short"; - } else if (clazz.equals(StringTag.class)) { + } + else if (clazz.equals(StringTag.class)) { return "TAG_String"; - } else if (clazz.equals(IntArrayTag.class)) { + } + else if (clazz.equals(IntArrayTag.class)) { return "TAG_Int_Array"; - } else { - throw new IllegalArgumentException("Invalid tag classs (" - + clazz.getName() + ")."); + } + else { + throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ")."); } } /** * Gets the type code of a tag class. * - * @param clazz the tag class + * @param clazz + * the tag class * @return The type code. - * @throws IllegalArgumentException if the tag class is invalid. + * @throws IllegalArgumentException + * if the tag class is invalid. */ - public static int getTypeCode(Class clazz) { + public static int getTypeCode(final Class clazz) { if (clazz.equals(ByteArrayTag.class)) { return NBTConstants.TYPE_BYTE_ARRAY; - } else if (clazz.equals(ByteTag.class)) { + } + else if (clazz.equals(ByteTag.class)) { return NBTConstants.TYPE_BYTE; - } else if (clazz.equals(CompoundTag.class)) { + } + else if (clazz.equals(CompoundTag.class)) { return NBTConstants.TYPE_COMPOUND; - } else if (clazz.equals(DoubleTag.class)) { + } + else if (clazz.equals(DoubleTag.class)) { return NBTConstants.TYPE_DOUBLE; - } else if (clazz.equals(EndTag.class)) { + } + else if (clazz.equals(EndTag.class)) { return NBTConstants.TYPE_END; - } else if (clazz.equals(FloatTag.class)) { + } + else if (clazz.equals(FloatTag.class)) { return NBTConstants.TYPE_FLOAT; - } else if (clazz.equals(IntTag.class)) { + } + else if (clazz.equals(IntTag.class)) { return NBTConstants.TYPE_INT; - } else if (clazz.equals(ListTag.class)) { + } + else if (clazz.equals(ListTag.class)) { return NBTConstants.TYPE_LIST; - } else if (clazz.equals(LongTag.class)) { + } + else if (clazz.equals(LongTag.class)) { return NBTConstants.TYPE_LONG; - } else if (clazz.equals(ShortTag.class)) { + } + else if (clazz.equals(ShortTag.class)) { return NBTConstants.TYPE_SHORT; - } else if (clazz.equals(StringTag.class)) { + } + else if (clazz.equals(StringTag.class)) { return NBTConstants.TYPE_STRING; - } else if (clazz.equals(IntArrayTag.class)) { + } + else if (clazz.equals(IntArrayTag.class)) { return NBTConstants.TYPE_INT_ARRAY; - } else { - throw new IllegalArgumentException("Invalid tag classs (" - + clazz.getName() + ")."); + } + else { + throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ")."); } } /** * Gets the class of a type of tag. * - * @param type the type + * @param type + * the type * @return The class. - * @throws IllegalArgumentException if the tag type is invalid. + * @throws IllegalArgumentException + * if the tag type is invalid. */ - public static Class getTypeClass(int type) { + public static Class getTypeClass(final int type) { switch (type) { - case NBTConstants.TYPE_END: - return EndTag.class; - case NBTConstants.TYPE_BYTE: - return ByteTag.class; - case NBTConstants.TYPE_SHORT: - return ShortTag.class; - case NBTConstants.TYPE_INT: - return IntTag.class; - case NBTConstants.TYPE_LONG: - return LongTag.class; - case NBTConstants.TYPE_FLOAT: - return FloatTag.class; - case NBTConstants.TYPE_DOUBLE: - return DoubleTag.class; - case NBTConstants.TYPE_BYTE_ARRAY: - return ByteArrayTag.class; - case NBTConstants.TYPE_STRING: - return StringTag.class; - case NBTConstants.TYPE_LIST: - return ListTag.class; - case NBTConstants.TYPE_COMPOUND: - return CompoundTag.class; - case NBTConstants.TYPE_INT_ARRAY: - return IntArrayTag.class; - default: - throw new IllegalArgumentException("Invalid tag type : " + type - + "."); + case NBTConstants.TYPE_END: + return EndTag.class; + case NBTConstants.TYPE_BYTE: + return ByteTag.class; + case NBTConstants.TYPE_SHORT: + return ShortTag.class; + case NBTConstants.TYPE_INT: + return IntTag.class; + case NBTConstants.TYPE_LONG: + return LongTag.class; + case NBTConstants.TYPE_FLOAT: + return FloatTag.class; + case NBTConstants.TYPE_DOUBLE: + return DoubleTag.class; + case NBTConstants.TYPE_BYTE_ARRAY: + return ByteArrayTag.class; + case NBTConstants.TYPE_STRING: + return StringTag.class; + case NBTConstants.TYPE_LIST: + return ListTag.class; + case NBTConstants.TYPE_COMPOUND: + return CompoundTag.class; + case NBTConstants.TYPE_INT_ARRAY: + return IntArrayTag.class; + default: + throw new IllegalArgumentException("Invalid tag type : " + type + "."); } } /** * Get child tag of a NBT structure. * - * @param items the map to read from - * @param key the key to look for - * @param expected the expected NBT class type + * @param items + * the map to read from + * @param key + * the key to look for + * @param expected + * the expected NBT class type * @return child tag * @throws InvalidFormatException */ - public static T getChildTag(Map items, String key, Class expected) throws IllegalArgumentException { + public static T getChildTag(final Map items, final String key, final Class expected) throws IllegalArgumentException { if (!items.containsKey(key)) { throw new IllegalArgumentException("Missing a \"" + key + "\" tag"); } - Tag tag = items.get(key); + final Tag tag = items.get(key); if (!expected.isInstance(tag)) { throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName()); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java index e488968d1..1c4e48c29 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java @@ -10,9 +10,10 @@ public final class ShortTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public ShortTag(short value) { + public ShortTag(final short value) { super(); this.value = value; } @@ -20,27 +21,29 @@ public final class ShortTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public ShortTag(String name, short value) { + public ShortTag(final String name, final short value) { super(name); this.value = value; } @Override public Short getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Short" + append + ": " + value; + return "TAG_Short" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/StringTag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/StringTag.java index 6a66458eb..05069471a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/StringTag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/StringTag.java @@ -12,9 +12,10 @@ public final class StringTag extends Tag { /** * Creates the tag with an empty name. * - * @param value the value of the tag + * @param value + * the value of the tag */ - public StringTag(String value) { + public StringTag(final String value) { super(); checkNotNull(value); this.value = value; @@ -23,10 +24,12 @@ public final class StringTag extends Tag { /** * Creates the tag. * - * @param name the name of the tag - * @param value the value of the tag + * @param name + * the name of the tag + * @param value + * the value of the tag */ - public StringTag(String name, String value) { + public StringTag(final String name, final String value) { super(name); checkNotNull(value); this.value = value; @@ -34,17 +37,17 @@ public final class StringTag extends Tag { @Override public String getValue() { - return value; + return this.value; } @Override public String toString() { - String name = getName(); + final String name = getName(); String append = ""; - if (name != null && !name.equals("")) { + if ((name != null) && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_String" + append + ": " + value; + return "TAG_String" + append + ": " + this.value; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/Tag.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/Tag.java index 2fab21bd2..26ad12c8b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/Tag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/Tag.java @@ -16,8 +16,9 @@ public abstract class Tag { /** * Creates the tag with the specified name. - * - * @param name the name + * + * @param name + * the name */ Tag(String name) { if (name == null) { @@ -28,16 +29,16 @@ public abstract class Tag { /** * Gets the name of this tag. - * + * * @return the name of this tag */ public final String getName() { - return name; + return this.name; } /** * Gets the value of this tag. - * + * * @return the value */ public abstract Object getValue(); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/WorldEditUtils.java b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/WorldEditUtils.java new file mode 100644 index 000000000..6c393fad5 --- /dev/null +++ b/PlotSquared/src/main/java/com/intellectualcrafters/jnbt/WorldEditUtils.java @@ -0,0 +1,29 @@ +package com.intellectualcrafters.jnbt; + +import org.bukkit.World; + +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.LocalWorld; +import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.bukkit.BukkitUtil; + +public class WorldEditUtils { + public static void setNBT(final World world, final short id, final byte data, final int x, final int y, final int z, final com.intellectualcrafters.jnbt.CompoundTag tag) { + +// final LocalWorld bukkitWorld = BukkitUtil.getLocalWorld(world); + + // I need to somehow convert our CompoundTag to WorldEdit's + +// final BaseBlock block = new BaseBlock(5, 5, (CompoundTag) tag); +// final Vector vector = new Vector(x, y, z); +// try { +// bukkitWorld.setBlock(vector, block); +// } +// catch (final WorldEditException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } + } +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/CDL.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/CDL.java index 2dd1af8db..225df4ad1 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/CDL.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/CDL.java @@ -1,28 +1,28 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ /** * This provides static methods to convert comma delimited text into a @@ -30,16 +30,17 @@ SOFTWARE. * delimited text is a very popular format for data interchange. It is * understood by most database, spreadsheet, and organizer programs. *

- * Each row of text represents a row in a table or a data record. Each row - * ends with a NEWLINE character. Each row contains one or more values. - * Values are separated by commas. A value can contain any character except - * for comma, unless is is wrapped in single quotes or double quotes. + * Each row of text represents a row in a table or a data record. Each row ends + * with a NEWLINE character. Each row contains one or more values. Values are + * separated by commas. A value can contain any character except for comma, + * unless is is wrapped in single quotes or double quotes. *

* The first row usually contains the names of the columns. *

- * A comma delimited list can be converted into a JSONArray of JSONObjects. - * The names for the elements in the JSONObjects can be taken from the names - * in the first row. + * A comma delimited list can be converted into a JSONArray of JSONObjects. The + * names for the elements in the JSONObjects can be taken from the names in the + * first row. + * * @author JSON.org * @version 2014-05-03 */ @@ -48,57 +49,62 @@ public class CDL { /** * Get the next value. The value can be wrapped in quotes. The value can * be empty. - * @param x A JSONTokener of the source text. + * + * @param x + * A JSONTokener of the source text. * @return The value string, or null if empty. - * @throws JSONException if the quoted string is badly formed. + * @throws JSONException + * if the quoted string is badly formed. */ - private static String getValue(JSONTokener x) throws JSONException { + private static String getValue(final JSONTokener x) throws JSONException { char c; char q; StringBuffer sb; do { c = x.next(); - } while (c == ' ' || c == '\t'); + } + while ((c == ' ') || (c == '\t')); switch (c) { - case 0: - return null; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = x.next(); - if (c == q) { - break; + case 0: + return null; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (;;) { + c = x.next(); + if (c == q) { + break; + } + if ((c == 0) || (c == '\n') || (c == '\r')) { + throw x.syntaxError("Missing close quote '" + q + "'."); + } + sb.append(c); } - if (c == 0 || c == '\n' || c == '\r') { - throw x.syntaxError("Missing close quote '" + q + "'."); - } - sb.append(c); - } - return sb.toString(); - case ',': - x.back(); - return ""; - default: - x.back(); - return x.nextTo(','); + return sb.toString(); + case ',': + x.back(); + return ""; + default: + x.back(); + return x.nextTo(','); } } /** * Produce a JSONArray of strings from a row of comma delimited values. - * @param x A JSONTokener of the source text. + * + * @param x + * A JSONTokener of the source text. * @return A JSONArray of strings. * @throws JSONException */ - public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { - JSONArray ja = new JSONArray(); + public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException { + final JSONArray ja = new JSONArray(); for (;;) { - String value = getValue(x); + 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.length() == 0) && (c != ','))) { return null; } ja.put(value); @@ -107,11 +113,10 @@ public class CDL { break; } if (c != ' ') { - if (c == '\n' || c == '\r' || c == 0) { + if ((c == '\n') || (c == '\r') || (c == 0)) { return ja; } - throw x.syntaxError("Bad character '" + c + "' (" + - (int)c + ")."); + throw x.syntaxError("Bad character '" + c + "' (" + (int) c + ")."); } c = x.next(); } @@ -121,48 +126,52 @@ public class CDL { /** * Produce a JSONObject from a row of comma delimited text, using a * parallel JSONArray of strings to provides the names of the elements. - * @param names A JSONArray of names. This is commonly obtained from the - * first row of a comma delimited text file using the rowToJSONArray - * method. - * @param x A JSONTokener of the source text. + * + * @param names + * A JSONArray of names. This is commonly obtained from the + * first row of a comma delimited text file using the + * rowToJSONArray + * method. + * @param x + * A JSONTokener of the source text. * @return A JSONObject combining the names and values. * @throws JSONException */ - public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) - throws JSONException { - JSONArray ja = rowToJSONArray(x); - return ja != null ? ja.toJSONObject(names) : null; + public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException { + final JSONArray ja = rowToJSONArray(x); + return ja != null ? ja.toJSONObject(names) : null; } /** * Produce a comma delimited text row from a JSONArray. Values containing * the comma character will be quoted. Troublesome characters may be * removed. - * @param ja A JSONArray of strings. + * + * @param ja + * A JSONArray of strings. * @return A string ending in NEWLINE. */ - public static String rowToString(JSONArray ja) { - StringBuilder sb = new StringBuilder(); + public static String rowToString(final JSONArray ja) { + final StringBuilder sb = new StringBuilder(); for (int i = 0; i < ja.length(); i += 1) { if (i > 0) { sb.append(','); } - Object object = ja.opt(i); + final Object object = ja.opt(i); if (object != null) { - 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) == '"')) { + 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) == '"'))) { sb.append('"'); - int length = string.length(); + final int length = string.length(); for (int j = 0; j < length; j += 1) { - char c = string.charAt(j); - if (c >= ' ' && c != '"') { + final char c = string.charAt(j); + if ((c >= ' ') && (c != '"')) { sb.append(c); } } sb.append('"'); - } else { + } + else { sb.append(string); } } @@ -174,54 +183,62 @@ public class CDL { /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. - * @param string The comma delimited text. + * + * @param string + * The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ - public static JSONArray toJSONArray(String string) throws JSONException { + public static JSONArray toJSONArray(final String string) throws JSONException { return toJSONArray(new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. - * @param x The JSONTokener containing the comma delimited text. + * + * @param x + * The JSONTokener containing the comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ - public static JSONArray toJSONArray(JSONTokener x) throws JSONException { + public static JSONArray toJSONArray(final JSONTokener x) throws JSONException { return toJSONArray(rowToJSONArray(x), x); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. - * @param string The comma delimited text. + * + * @param names + * A JSONArray of strings. + * @param string + * The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ - public static JSONArray toJSONArray(JSONArray names, String string) - throws JSONException { + public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException { return toJSONArray(names, new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. - * @param x A JSONTokener of the source text. + * + * @param names + * A JSONArray of strings. + * @param x + * A JSONTokener of the source text. * @return A JSONArray of JSONObjects. * @throws JSONException */ - public static JSONArray toJSONArray(JSONArray names, JSONTokener x) - throws JSONException { - if (names == null || names.length() == 0) { + public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException { + if ((names == null) || (names.length() == 0)) { return null; } - JSONArray ja = new JSONArray(); + final JSONArray ja = new JSONArray(); for (;;) { - JSONObject jo = rowToJSONObject(names, x); + final JSONObject jo = rowToJSONObject(names, x); if (jo == null) { break; } @@ -233,19 +250,20 @@ public class CDL { return ja; } - /** * Produce a comma delimited text from a JSONArray of JSONObjects. The * first row will be a list of names obtained by inspecting the first * JSONObject. - * @param ja A JSONArray of JSONObjects. + * + * @param ja + * A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ - public static String toString(JSONArray ja) throws JSONException { - JSONObject jo = ja.optJSONObject(0); + public static String toString(final JSONArray ja) throws JSONException { + final JSONObject jo = ja.optJSONObject(0); if (jo != null) { - JSONArray names = jo.names(); + final JSONArray names = jo.names(); if (names != null) { return rowToString(names) + toString(names, ja); } @@ -257,19 +275,21 @@ public class CDL { * Produce a comma delimited text from a JSONArray of JSONObjects using * a provided list of names. The list of names is not included in the * output. - * @param names A JSONArray of strings. - * @param ja A JSONArray of JSONObjects. + * + * @param names + * A JSONArray of strings. + * @param ja + * A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ - public static String toString(JSONArray names, JSONArray ja) - throws JSONException { - if (names == null || names.length() == 0) { + public static String toString(final JSONArray names, final JSONArray ja) throws JSONException { + if ((names == null) || (names.length() == 0)) { return null; } - StringBuffer sb = new StringBuffer(); + final StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { - JSONObject jo = ja.optJSONObject(i); + final JSONObject jo = ja.optJSONObject(i); if (jo != null) { sb.append(rowToString(jo.toJSONArray(names))); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/Cookie.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/Cookie.java index db32467b7..180997462 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/Cookie.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/Cookie.java @@ -1,31 +1,33 @@ package com.intellectualcrafters.json; + /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ /** * Convert a web browser cookie specification to a JSONObject and back. * JSON and Cookies are both notations for name/value pairs. + * * @author JSON.org * @version 2014-05-03 */ @@ -40,28 +42,30 @@ public class Cookie { * only a convention, not a standard. Often, cookies are expected to have * encoded values. We encode '=' and ';' because we must. We encode '%' and * '+' because they are meta characters in URL encoding. - * @param string The source string. - * @return The escaped result. + * + * @param string + * The source string. + * @return The escaped result. */ - public static String escape(String string) { - char c; - String s = string.trim(); - int length = s.length(); - StringBuilder sb = new StringBuilder(length); + public static String escape(final String string) { + char c; + final String s = string.trim(); + final int length = s.length(); + final StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i += 1) { c = s.charAt(i); - if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { + if ((c < ' ') || (c == '+') || (c == '%') || (c == '=') || (c == ';')) { sb.append('%'); - sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); - sb.append(Character.forDigit((char)(c & 0x0f), 16)); - } else { + sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16)); + sb.append(Character.forDigit((char) (c & 0x0f), 16)); + } + else { sb.append(c); } } return sb.toString(); } - /** * Convert a cookie specification string into a JSONObject. The string * will contain a name value pair separated by '='. The name and the value @@ -72,16 +76,18 @@ public class Cookie { * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into * a JSONObject. - * @param string The cookie specification string. + * + * @param string + * The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other - * members. + * members. * @throws JSONException */ - public static JSONObject toJSONObject(String string) throws JSONException { - String name; - JSONObject jo = new JSONObject(); - Object value; - JSONTokener x = new JSONTokener(string); + public static JSONObject toJSONObject(final String string) throws JSONException { + String name; + final JSONObject jo = new JSONObject(); + Object value; + final JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); jo.put("value", x.nextTo(';')); @@ -91,10 +97,12 @@ public class Cookie { if (x.next() != '=') { if (name.equals("secure")) { value = Boolean.TRUE; - } else { + } + else { throw x.syntaxError("Missing '=' in cookie parameter."); } - } else { + } + else { value = unescape(x.nextTo(';')); x.next(); } @@ -103,19 +111,20 @@ public class Cookie { return jo; } - /** * Convert a JSONObject into a cookie specification string. The JSONObject * must contain "name" and "value" members. * If the JSONObject contains "expires", "domain", "path", or "secure" * members, they will be appended to the cookie specification string. * All other members are ignored. - * @param jo A JSONObject + * + * @param jo + * A JSONObject * @return A cookie specification string * @throws JSONException */ - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); + public static String toString(final JSONObject jo) throws JSONException { + final StringBuilder sb = new StringBuilder(); sb.append(escape(jo.getString("name"))); sb.append("="); @@ -141,23 +150,26 @@ public class Cookie { /** * Convert %hh sequences to single characters, and * convert plus to space. - * @param string A string that may contain - * + (plus) and - * %hh sequences. + * + * @param string + * A string that may contain + + *  (plus) and %hh + * sequences. * @return The unescaped string. */ - public static String unescape(String string) { - int length = string.length(); - StringBuilder sb = new StringBuilder(length); + public static String unescape(final String string) { + final int length = string.length(); + final StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; - } else if (c == '%' && i + 2 < length) { - int d = JSONTokener.dehexchar(string.charAt(i + 1)); - int e = JSONTokener.dehexchar(string.charAt(i + 2)); - if (d >= 0 && e >= 0) { - c = (char)(d * 16 + e); + } + else if ((c == '%') && ((i + 2) < length)) { + final int d = JSONTokener.dehexchar(string.charAt(i + 1)); + final int e = JSONTokener.dehexchar(string.charAt(i + 2)); + if ((d >= 0) && (e >= 0)) { + c = (char) ((d * 16) + e); i += 2; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/CookieList.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/CookieList.java index 5b7f13c8a..146cecbaa 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/CookieList.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/CookieList.java @@ -1,33 +1,34 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ import java.util.Iterator; /** * Convert a web browser cookie list string to a JSONObject and back. + * * @author JSON.org * @version 2014-05-03 */ @@ -41,16 +42,18 @@ public class CookieList { * * To add a cookie to a cooklist, * cookielistJSONObject.put(cookieJSONObject.getString("name"), - * cookieJSONObject.getString("value")); - * @param string A cookie list string + * cookieJSONObject.getString("value")); + * + * @param string + * A cookie list string * @return A JSONObject * @throws JSONException */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - JSONTokener x = new JSONTokener(string); + public static JSONObject toJSONObject(final String string) throws JSONException { + final JSONObject jo = new JSONObject(); + final JSONTokener x = new JSONTokener(string); while (x.more()) { - String name = Cookie.unescape(x.nextTo('=')); + final String name = Cookie.unescape(x.nextTo('=')); x.next('='); jo.put(name, Cookie.unescape(x.nextTo(';'))); x.next(); @@ -63,15 +66,17 @@ public class CookieList { * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". - * @param jo A JSONObject + * + * @param jo + * A JSONObject * @return A cookie list string * @throws JSONException */ - public static String toString(JSONObject jo) throws JSONException { - boolean b = false; - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); + public static String toString(final JSONObject jo) throws JSONException { + boolean b = false; + final Iterator keys = jo.keys(); + String string; + final StringBuilder sb = new StringBuilder(); while (keys.hasNext()) { string = keys.next(); if (!jo.isNull(string)) { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTP.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTP.java index 2508ba760..7dfac0a04 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTP.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTP.java @@ -1,33 +1,34 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ import java.util.Iterator; /** * Convert an HTTP header to a JSONObject and back. + * * @author JSON.org * @version 2014-05-03 */ @@ -39,63 +40,82 @@ public class HTTP { /** * Convert an HTTP header string into a JSONObject. It can be a request * header or a response header. A request header will contain - *

{
+     *
+     * 
+     * {
      *    Method: "POST" (for example),
      *    "Request-URI": "/" (for example),
      *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
+ * } + *
+ * * A response header will contain - *
{
+     *
+     * 
+     * {
      *    "HTTP-Version": "HTTP/1.1" (for example),
      *    "Status-Code": "200" (for example),
      *    "Reason-Phrase": "OK" (for example)
-     * }
+ * } + *
+ * * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that
+     * the HTTP field names as JSON names, so that
+     *
+     * 
      *    Date: Sun, 26 May 2002 18:06:04 GMT
      *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
-     *    Cache-Control: no-cache
+ * Cache-Control: no-cache + *
+ * * become - *
{...
+     *
+     * 
+     * {...
      *    Date: "Sun, 26 May 2002 18:06:04 GMT",
      *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
      *    "Cache-Control": "no-cache",
-     * ...}
+ * ...} + *
+ * * It does no further checking or conversion. It does not parse dates. * It does not do '%' transforms on URLs. - * @param string An HTTP header string. + * + * @param string + * An HTTP header string. * @return A JSONObject containing the elements and attributes - * of the XML string. + * of the XML string. * @throws JSONException */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; + public static JSONObject toJSONObject(final String string) throws JSONException { + final JSONObject jo = new JSONObject(); + final HTTPTokener x = new HTTPTokener(string); + String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { -// Response + // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); - } else { + } + else { -// Request + // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } -// Fields + // Fields while (x.more()) { - String name = x.nextTo(':'); + final String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); x.next(); @@ -103,38 +123,49 @@ public class HTTP { return jo; } - /** * Convert a JSONObject into an HTTP header. A request header must contain - *
{
+     *
+     * 
+     * {
      *    Method: "POST" (for example),
      *    "Request-URI": "/" (for example),
      *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
+ * } + *
+ * * A response header must contain - *
{
+     *
+     * 
+     * {
      *    "HTTP-Version": "HTTP/1.1" (for example),
      *    "Status-Code": "200" (for example),
      *    "Reason-Phrase": "OK" (for example)
-     * }
+ * } + *
+ * * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. - * @param jo A JSONObject + * + * @param jo + * A JSONObject * @return An HTTP header string. - * @throws JSONException if the object does not contain enough - * information. + * @throws JSONException + * if the object does not contain enough + * information. */ - public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); + public static String toString(final JSONObject jo) throws JSONException { + final Iterator keys = jo.keys(); + String string; + final StringBuilder sb = new StringBuilder(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); - } else if (jo.has("Method") && jo.has("Request-URI")) { + } + else if (jo.has("Method") && jo.has("Request-URI")) { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); @@ -142,15 +173,14 @@ public class HTTP { sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); - } else { + } + else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { string = keys.next(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && - !"Reason-Phrase".equals(string) && !"Method".equals(string) && - !"Request-URI".equals(string) && !jo.isNull(string)) { + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTPTokener.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTPTokener.java index 513776f78..b232d404f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTPTokener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/HTTPTokener.java @@ -1,31 +1,33 @@ package com.intellectualcrafters.json; + /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ /** * The HTTPTokener extends the JSONTokener to provide additional methods * for the parsing of HTTP headers. + * * @author JSON.org * @version 2014-05-03 */ @@ -33,26 +35,29 @@ public class HTTPTokener extends JSONTokener { /** * Construct an HTTPTokener from a string. - * @param string A source string. + * + * @param string + * A source string. */ - public HTTPTokener(String string) { + public HTTPTokener(final String string) { super(string); } - /** * Get the next token or string. This is used in parsing HTTP headers. + * * @throws JSONException * @return A String. */ public String nextToken() throws JSONException { char c; char q; - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); do { c = next(); - } while (Character.isWhitespace(c)); - if (c == '"' || c == '\'') { + } + while (Character.isWhitespace(c)); + if ((c == '"') || (c == '\'')) { q = c; for (;;) { c = next(); @@ -66,7 +71,7 @@ public class HTTPTokener extends JSONTokener { } } for (;;) { - if (c == 0 || Character.isWhitespace(c)) { + if ((c == 0) || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONArray.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONArray.java index 099984df5..4fc8ef03e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONArray.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONArray.java @@ -69,8 +69,8 @@ import java.util.Map; *
  • Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, and * if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and - * if they are not the reserved words true, false, or + * { } [ ] / \ : , # and if they do not look like numbers and if + * they are not the reserved words true, false, or * null.
  • * * @@ -99,7 +99,7 @@ public class JSONArray { * @throws JSONException * If there is a syntax error. */ - public JSONArray(JSONTokener x) throws JSONException { + public JSONArray(final JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); @@ -110,21 +110,22 @@ public class JSONArray { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); - } else { + } + else { x.back(); this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { - case ',': - if (x.nextClean() == ']') { + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); + default: + throw x.syntaxError("Expected a ',' or ']'"); } } } @@ -140,7 +141,7 @@ public class JSONArray { * @throws JSONException * If there is a syntax error. */ - public JSONArray(String source) throws JSONException { + public JSONArray(final String source) throws JSONException { this(new JSONTokener(source)); } @@ -150,10 +151,10 @@ public class JSONArray { * @param collection * A Collection. */ - public JSONArray(Collection collection) { + public JSONArray(final Collection collection) { this.myArrayList = new ArrayList(); if (collection != null) { - Iterator iter = collection.iterator(); + final Iterator iter = collection.iterator(); while (iter.hasNext()) { this.myArrayList.add(JSONObject.wrap(iter.next())); } @@ -166,16 +167,16 @@ public class JSONArray { * @throws JSONException * If not an array. */ - public JSONArray(Object array) throws JSONException { + public JSONArray(final Object array) throws JSONException { this(); if (array.getClass().isArray()) { - int length = Array.getLength(array); + final int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } - } else { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); + } + else { + throw new JSONException("JSONArray initial value should be a string or collection or array."); } } @@ -188,8 +189,8 @@ public class JSONArray { * @throws JSONException * If there is no value for the index. */ - public Object get(int index) throws JSONException { - Object object = this.opt(index); + public Object get(final int index) throws JSONException { + final Object object = this.opt(index); if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); } @@ -207,15 +208,12 @@ public class JSONArray { * If there is no value for the index or if the value is not * convertible to boolean. */ - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if (object.equals(Boolean.FALSE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { + public boolean getBoolean(final int index) throws JSONException { + final Object object = this.get(index); + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { return false; - } else if (object.equals(Boolean.TRUE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { + } + else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); @@ -231,12 +229,12 @@ public class JSONArray { * If the key is not found or if the value cannot be converted * to a number. */ - public double getDouble(int index) throws JSONException { - Object object = this.get(index); + public double getDouble(final int index) throws JSONException { + final Object object = this.get(index); try { - return object instanceof Number ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); - } catch (Exception e) { + return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + } + catch (final Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -250,12 +248,12 @@ public class JSONArray { * @throws JSONException * If the key is not found or if the value is not a number. */ - public int getInt(int index) throws JSONException { - Object object = this.get(index); + public int getInt(final int index) throws JSONException { + final Object object = this.get(index); try { - return object instanceof Number ? ((Number) object).intValue() - : Integer.parseInt((String) object); - } catch (Exception e) { + return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + } + catch (final Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -270,8 +268,8 @@ public class JSONArray { * If there is no value for the index. or if the value is not a * JSONArray */ - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); + public JSONArray getJSONArray(final int index) throws JSONException { + final Object object = this.get(index); if (object instanceof JSONArray) { return (JSONArray) object; } @@ -288,8 +286,8 @@ public class JSONArray { * If there is no value for the index or if the value is not a * JSONObject */ - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); + public JSONObject getJSONObject(final int index) throws JSONException { + final Object object = this.get(index); if (object instanceof JSONObject) { return (JSONObject) object; } @@ -306,12 +304,12 @@ public class JSONArray { * If the key is not found or if the value cannot be converted * to a number. */ - public long getLong(int index) throws JSONException { - Object object = this.get(index); + public long getLong(final int index) throws JSONException { + final Object object = this.get(index); try { - return object instanceof Number ? ((Number) object).longValue() - : Long.parseLong((String) object); - } catch (Exception e) { + return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + } + catch (final Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } @@ -325,8 +323,8 @@ public class JSONArray { * @throws JSONException * If there is no string value for the index. */ - public String getString(int index) throws JSONException { - Object object = this.get(index); + public String getString(final int index) throws JSONException { + final Object object = this.get(index); if (object instanceof String) { return (String) object; } @@ -340,7 +338,7 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ - public boolean isNull(int index) { + public boolean isNull(final int index) { return JSONObject.NULL.equals(this.opt(index)); } @@ -355,9 +353,9 @@ public class JSONArray { * @throws JSONException * If the array contains an invalid number. */ - public String join(String separator) throws JSONException { - int len = this.length(); - StringBuilder sb = new StringBuilder(); + public String join(final String separator) throws JSONException { + final int len = this.length(); + final StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i += 1) { if (i > 0) { @@ -384,9 +382,8 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return An object value, or null if there is no object at that index. */ - public Object opt(int index) { - return (index < 0 || index >= this.length()) ? null : this.myArrayList - .get(index); + public Object opt(final int index) { + return ((index < 0) || (index >= this.length())) ? null : this.myArrayList.get(index); } /** @@ -398,7 +395,7 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return The truth. */ - public boolean optBoolean(int index) { + public boolean optBoolean(final int index) { return this.optBoolean(index, false); } @@ -413,10 +410,11 @@ public class JSONArray { * A boolean default. * @return The truth. */ - public boolean optBoolean(int index, boolean defaultValue) { + public boolean optBoolean(final int index, final boolean defaultValue) { try { return this.getBoolean(index); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -430,7 +428,7 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return The value. */ - public double optDouble(int index) { + public double optDouble(final int index) { return this.optDouble(index, Double.NaN); } @@ -445,10 +443,11 @@ public class JSONArray { * The default value. * @return The value. */ - public double optDouble(int index, double defaultValue) { + public double optDouble(final int index, final double defaultValue) { try { return this.getDouble(index); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -462,7 +461,7 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return The value. */ - public int optInt(int index) { + public int optInt(final int index) { return this.optInt(index, 0); } @@ -477,10 +476,11 @@ public class JSONArray { * The default value. * @return The value. */ - public int optInt(int index, int defaultValue) { + public int optInt(final int index, final int defaultValue) { try { return this.getInt(index); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -493,8 +493,8 @@ public class JSONArray { * @return A JSONArray value, or null if the index has no value, or if the * value is not a JSONArray. */ - public JSONArray optJSONArray(int index) { - Object o = this.opt(index); + public JSONArray optJSONArray(final int index) { + final Object o = this.opt(index); return o instanceof JSONArray ? (JSONArray) o : null; } @@ -507,8 +507,8 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return A JSONObject value. */ - public JSONObject optJSONObject(int index) { - Object o = this.opt(index); + public JSONObject optJSONObject(final int index) { + final Object o = this.opt(index); return o instanceof JSONObject ? (JSONObject) o : null; } @@ -521,7 +521,7 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return The value. */ - public long optLong(int index) { + public long optLong(final int index) { return this.optLong(index, 0); } @@ -536,10 +536,11 @@ public class JSONArray { * The default value. * @return The value. */ - public long optLong(int index, long defaultValue) { + public long optLong(final int index, final long defaultValue) { try { return this.getLong(index); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -553,7 +554,7 @@ public class JSONArray { * The index must be between 0 and length() - 1. * @return A String value. */ - public String optString(int index) { + public String optString(final int index) { return this.optString(index, ""); } @@ -567,10 +568,9 @@ public class JSONArray { * The default value. * @return A String value. */ - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) ? defaultValue : object - .toString(); + public String optString(final int index, final String defaultValue) { + final Object object = this.opt(index); + return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); } /** @@ -580,7 +580,7 @@ public class JSONArray { * A boolean value. * @return this. */ - public JSONArray put(boolean value) { + public JSONArray put(final boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -593,7 +593,7 @@ public class JSONArray { * A Collection value. * @return this. */ - public JSONArray put(Collection value) { + public JSONArray put(final Collection value) { this.put(new JSONArray(value)); return this; } @@ -607,8 +607,8 @@ public class JSONArray { * if the value is not finite. * @return this. */ - public JSONArray put(double value) throws JSONException { - Double d = new Double(value); + public JSONArray put(final double value) throws JSONException { + final Double d = new Double(value); JSONObject.testValidity(d); this.put(d); return this; @@ -621,7 +621,7 @@ public class JSONArray { * An int value. * @return this. */ - public JSONArray put(int value) { + public JSONArray put(final int value) { this.put(new Integer(value)); return this; } @@ -633,7 +633,7 @@ public class JSONArray { * A long value. * @return this. */ - public JSONArray put(long value) { + public JSONArray put(final long value) { this.put(new Long(value)); return this; } @@ -646,7 +646,7 @@ public class JSONArray { * A Map value. * @return this. */ - public JSONArray put(Map value) { + public JSONArray put(final Map value) { this.put(new JSONObject(value)); return this; } @@ -660,7 +660,7 @@ public class JSONArray { * JSONObject.NULL object. * @return this. */ - public JSONArray put(Object value) { + public JSONArray put(final Object value) { this.myArrayList.add(value); return this; } @@ -678,7 +678,7 @@ public class JSONArray { * @throws JSONException * If the index is negative. */ - public JSONArray put(int index, boolean value) throws JSONException { + public JSONArray put(final int index, final boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -695,7 +695,7 @@ public class JSONArray { * @throws JSONException * If the index is negative or if the value is not finite. */ - public JSONArray put(int index, Collection value) throws JSONException { + public JSONArray put(final int index, final Collection value) throws JSONException { this.put(index, new JSONArray(value)); return this; } @@ -713,7 +713,7 @@ public class JSONArray { * @throws JSONException * If the index is negative or if the value is not finite. */ - public JSONArray put(int index, double value) throws JSONException { + public JSONArray put(final int index, final double value) throws JSONException { this.put(index, new Double(value)); return this; } @@ -731,7 +731,7 @@ public class JSONArray { * @throws JSONException * If the index is negative. */ - public JSONArray put(int index, int value) throws JSONException { + public JSONArray put(final int index, final int value) throws JSONException { this.put(index, new Integer(value)); return this; } @@ -749,7 +749,7 @@ public class JSONArray { * @throws JSONException * If the index is negative. */ - public JSONArray put(int index, long value) throws JSONException { + public JSONArray put(final int index, final long value) throws JSONException { this.put(index, new Long(value)); return this; } @@ -767,7 +767,7 @@ public class JSONArray { * If the index is negative or if the the value is an invalid * number. */ - public JSONArray put(int index, Map value) throws JSONException { + public JSONArray put(final int index, final Map value) throws JSONException { this.put(index, new JSONObject(value)); return this; } @@ -788,14 +788,15 @@ public class JSONArray { * If the index is negative or if the the value is an invalid * number. */ - public JSONArray put(int index, Object value) throws JSONException { + public JSONArray put(final int index, final Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < this.length()) { this.myArrayList.set(index, value); - } else { + } + else { while (index != this.length()) { this.put(JSONObject.NULL); } @@ -812,39 +813,40 @@ public class JSONArray { * @return The value that was associated with the index, or null if there * was no value. */ - public Object remove(int index) { - return index >= 0 && index < this.length() - ? this.myArrayList.remove(index) - : null; + public Object remove(final int index) { + return (index >= 0) && (index < this.length()) ? this.myArrayList.remove(index) : null; } /** * Determine if two JSONArrays are similar. * They must contain similar sequences. * - * @param other The other JSONArray + * @param other + * The other JSONArray * @return true if they are equal */ - public boolean similar(Object other) { + public boolean similar(final Object other) { if (!(other instanceof JSONArray)) { return false; } - int len = this.length(); - if (len != ((JSONArray)other).length()) { + final int len = this.length(); + if (len != ((JSONArray) other).length()) { return false; } for (int i = 0; i < len; i += 1) { - Object valueThis = this.get(i); - Object valueOther = ((JSONArray)other).get(i); + final Object valueThis = this.get(i); + final Object valueOther = ((JSONArray) other).get(i); if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { + } + else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } - } else if (!valueThis.equals(valueOther)) { + } + else if (!valueThis.equals(valueOther)) { return false; } } @@ -863,11 +865,11 @@ public class JSONArray { * @throws JSONException * If any of the names are null. */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.length() == 0 || this.length() == 0) { + public JSONObject toJSONObject(final JSONArray names) throws JSONException { + if ((names == null) || (names.length() == 0) || (this.length() == 0)) { return null; } - JSONObject jo = new JSONObject(); + final JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } @@ -885,10 +887,12 @@ public class JSONArray { * @return a printable, displayable, transmittable representation of the * array. */ + @Override public String toString() { try { return this.toString(0); - } catch (Exception e) { + } + catch (final Exception e) { return null; } } @@ -905,8 +909,8 @@ public class JSONArray { *  (right bracket). * @throws JSONException */ - public String toString(int indentFactor) throws JSONException { - StringWriter sw = new StringWriter(); + public String toString(final int indentFactor) throws JSONException { + final StringWriter sw = new StringWriter(); synchronized (sw.getBuffer()) { return this.write(sw, indentFactor, 0).toString(); } @@ -921,7 +925,7 @@ public class JSONArray { * @return The writer. * @throws JSONException */ - public Writer write(Writer writer) throws JSONException { + public Writer write(final Writer writer) throws JSONException { return this.write(writer, 0, 0); } @@ -938,17 +942,16 @@ public class JSONArray { * @return The writer. * @throws JSONException */ - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { + Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { try { boolean commanate = false; - int length = this.length(); + final int length = this.length(); writer.write('['); if (length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), - indentFactor, indent); - } else if (length != 0) { + JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); + } + else if (length != 0) { final int newindent = indent + indentFactor; for (int i = 0; i < length; i += 1) { @@ -959,8 +962,7 @@ public class JSONArray { writer.write('\n'); } JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newindent); + JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); commanate = true; } if (indentFactor > 0) { @@ -970,7 +972,8 @@ public class JSONArray { } writer.write(']'); return writer; - } catch (IOException e) { + } + catch (final IOException e) { throw new JSONException(e); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONException.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONException.java index 1b50a4f0d..17f89893f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONException.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONException.java @@ -1,4 +1,5 @@ package com.intellectualcrafters.json; + /** * The JSONException is thrown by the JSON.org classes when things are amiss. * @@ -7,7 +8,7 @@ package com.intellectualcrafters.json; */ public class JSONException extends RuntimeException { private static final long serialVersionUID = 0; - private Throwable cause; + private Throwable cause; /** * Constructs a JSONException with an explanatory message. @@ -15,15 +16,17 @@ public class JSONException extends RuntimeException { * @param message * Detail about the reason for the exception. */ - public JSONException(String message) { + public JSONException(final String message) { super(message); } /** * Constructs a new JSONException with the specified cause. - * @param cause The cause. + * + * @param cause + * The cause. */ - public JSONException(Throwable cause) { + public JSONException(final Throwable cause) { super(cause.getMessage()); this.cause = cause; } @@ -33,7 +36,7 @@ public class JSONException extends RuntimeException { * or unknown. * * @return the cause of this exception or null if the cause is nonexistent - * or unknown. + * or unknown. */ @Override public Throwable getCause() { diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONML.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONML.java index 640d389be..607f2352d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONML.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONML.java @@ -1,32 +1,31 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2008 JSON.org + Copyright (c) 2008 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ import java.util.Iterator; - /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using @@ -39,32 +38,32 @@ public class JSONML { /** * Parse XML values and store them in a JSONArray. - * @param x The XMLTokener containing the source string. - * @param arrayForm true if array form, false if object form. - * @param ja The JSONArray that is containing the current tag or null - * if we are at the outermost level. + * + * @param x + * The XMLTokener containing the source string. + * @param arrayForm + * true if array form, false if object form. + * @param ja + * The JSONArray that is containing the current tag or null + * if we are at the outermost level. * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ - private static Object parse( - XMLTokener x, - boolean arrayForm, - JSONArray ja - ) throws JSONException { - String attribute; - char c; - String closeTag = null; - int i; - JSONArray newja = null; + private static Object parse(final XMLTokener x, final boolean arrayForm, final JSONArray ja) throws JSONException { + String attribute; + char c; + String closeTag = null; + int i; + JSONArray newja = null; JSONObject newjo = null; - Object token; - String tagName = null; + Object token; + String tagName = null; -// Test for and skip past these forms: -// -// -// -// + // Test for and skip past these forms: + // + // + // + // while (true) { if (!x.more()) { @@ -76,67 +75,76 @@ public class JSONML { if (token instanceof Character) { if (token == XML.SLASH) { -// Close tag "); - } else { + } + else { x.back(); } - } else if (c == '[') { + } + else if (c == '[') { token = x.nextToken(); - if (token.equals("CDATA") && x.next() == '[') { + if (token.equals("CDATA") && (x.next() == '[')) { if (ja != null) { ja.put(x.nextCDATA()); } - } else { + } + else { throw x.syntaxError("Expected 'CDATA['"); } - } else { + } + else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after ' 0); + } + while (i > 0); } - } else if (token == XML.QUEST) { + } + else if (token == XML.QUEST) { -// "); - } else { + } + else { throw x.syntaxError("Misshaped tag"); } -// Open tag < + // Open tag < - } else { + } + else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } - tagName = (String)token; + tagName = (String) token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { @@ -144,7 +152,8 @@ public class JSONML { if (ja != null) { ja.put(newja); } - } else { + } + else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); @@ -162,9 +171,9 @@ public class JSONML { break; } -// attribute = value + // attribute = value - attribute = (String)token; + attribute = (String) token; if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } @@ -174,17 +183,18 @@ public class JSONML { if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - newjo.accumulate(attribute, XML.stringToValue((String)token)); + newjo.accumulate(attribute, XML.stringToValue((String) token)); token = null; - } else { + } + else { newjo.accumulate(attribute, ""); } } - if (arrayForm && newjo.length() > 0) { + if (arrayForm && (newjo.length() > 0)) { newja.put(newjo); } -// Empty tag <.../> + // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { @@ -193,48 +203,48 @@ public class JSONML { if (ja == null) { if (arrayForm) { return newja; - } else { + } + else { return newjo; } } -// Content, between <...> and + // Content, between <...> and - } else { + } + else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } - closeTag = (String)parse(x, arrayForm, newja); + closeTag = (String) parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { - throw x.syntaxError("Mismatched '" + tagName + - "' and '" + closeTag + "'"); + throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; - if (!arrayForm && newja.length() > 0) { + if (!arrayForm && (newja.length() > 0)) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; - } else { + } + else { return newjo; } } } } } - } else { + } + else { if (ja != null) { - ja.put(token instanceof String - ? XML.stringToValue((String)token) - : token); + ja.put(token instanceof String ? XML.stringToValue((String) token) : token); } } } } - /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as @@ -243,15 +253,16 @@ public class JSONML { * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child tags. * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param string The source string. + * + * @param string + * The source string. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ - public static JSONArray toJSONArray(String string) throws JSONException { + public static JSONArray toJSONArray(final String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } - /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as @@ -260,15 +271,16 @@ public class JSONML { * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child content and tags. * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param x An XMLTokener. + * + * @param x + * An XMLTokener. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ - public static JSONArray toJSONArray(XMLTokener x) throws JSONException { - return (JSONArray)parse(x, true, null); + public static JSONArray toJSONArray(final XMLTokener x) throws JSONException { + return (JSONArray) parse(x, true, null); } - /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as @@ -276,17 +288,18 @@ public class JSONML { * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - + * * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param x An XMLTokener of the XML source text. + * + * @param x + * An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ - public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject)parse(x, false, null); + public static JSONObject toJSONObject(final XMLTokener x) throws JSONException { + return (JSONObject) parse(x, false, null); } - /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as @@ -294,35 +307,38 @@ public class JSONML { * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - + * * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param string The XML source text. + * + * @param string + * The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ - public static JSONObject toJSONObject(String string) throws JSONException { + public static JSONObject toJSONObject(final String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } - /** * Reverse the JSONML transformation, making an XML text from a JSONArray. - * @param ja A JSONArray. + * + * @param ja + * A JSONArray. * @return An XML string. * @throws JSONException */ - public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; - StringBuilder sb = new StringBuilder(); - String tagName; - String value; + public static String toString(final JSONArray ja) throws JSONException { + int i; + JSONObject jo; + String key; + Iterator keys; + int length; + Object object; + final StringBuilder sb = new StringBuilder(); + String tagName; + String value; -// Emit = length) { sb.append('/'); sb.append('>'); - } else { + } + else { sb.append('>'); do { object = ja.get(i); @@ -369,13 +387,16 @@ public class JSONML { if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); + } + else if (object instanceof JSONObject) { + sb.append(toString((JSONObject) object)); + } + else if (object instanceof JSONArray) { + sb.append(toString((JSONArray) object)); } } - } while (i < length); + } + while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); @@ -389,22 +410,24 @@ public class JSONML { * The JSONObject must contain a "tagName" property. If it has children, * then it must have a "childNodes" property containing an array of objects. * The other properties are attributes with string values. - * @param jo A JSONObject. + * + * @param jo + * A JSONObject. * @return An XML string. * @throws JSONException */ - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; + public static String toString(final JSONObject jo) throws JSONException { + final StringBuilder sb = new StringBuilder(); + int i; + JSONArray ja; + String key; + Iterator keys; + int length; + Object object; + String tagName; + String value; -//Emit '); - } else { + } + else { sb.append('>'); length = ja.length(); for (i = 0; i < length; i += 1) { @@ -448,11 +472,14 @@ public class JSONML { if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); - } else { + } + else if (object instanceof JSONObject) { + sb.append(toString((JSONObject) object)); + } + else if (object instanceof JSONArray) { + sb.append(toString((JSONArray) object)); + } + else { sb.append(object.toString()); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONObject.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONObject.java index 0491ad4b9..42e30213a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONObject.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONObject.java @@ -50,8 +50,8 @@ import java.util.Set; * JSONArray, JSONObject, Number, * String, or the JSONObject.NULL object. A * JSONObject constructor can be used to convert an external form JSON text - * into an internal form whose values can be retrieved with the - * get and opt methods, or to convert values into a + * into an internal form whose values can be retrieved with the get + * and opt methods, or to convert values into a * JSON text using the put and toString methods. A * get method returns a value if one can be found, and throws an * exception if one cannot be found. An opt method returns a @@ -61,15 +61,13 @@ import java.util.Set; * The generic get() and opt() methods return an * object, which you can cast or query for type. There are also typed * get and opt methods that do type checking and type - * coercion for you. The opt methods differ from the get methods in that they - * do not throw. Instead, they return a specified value, such as null. + * coercion for you. The opt methods differ from the get methods in that they do + * not throw. Instead, they return a specified value, such as null. *

    - * The put methods add or replace values in an object. For - * example, + * The put methods add or replace values in an object. For example, * *

    - * myString = new JSONObject()
    - *         .put("JSON", "Hello, World!").toString();
    + * myString = new JSONObject().put("JSON", "Hello, World!").toString();
      * 
    * * produces the string {"JSON": "Hello, World"}. @@ -82,12 +80,12 @@ import java.util.Set; * before the closing brace. *
  • Strings may be quoted with ' (single * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a - * quote or single quote, and if they do not contain leading or trailing - * spaces, and if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and - * if they are not the reserved words true, false, - * or null.
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, and + * if they do not contain any of these characters: + * { } [ ] / \ : , # and if they do not look like numbers and if + * they are not the reserved words true, false, or + * null.
  • * * * @author JSON.org @@ -121,8 +119,8 @@ public class JSONObject { * null. */ @Override - public boolean equals(Object object) { - return object == null || object == this; + public boolean equals(final Object object) { + return (object == null) || (object == this); } /** @@ -130,6 +128,7 @@ public class JSONObject { * * @return The string "null". */ + @Override public String toString() { return "null"; } @@ -146,7 +145,7 @@ public class JSONObject { * JSONObject.NULL.equals(null) returns true. * JSONObject.NULL.toString() returns "null". */ - public static final Object NULL = new Null(); + public static final Object NULL = new Null(); /** * Construct an empty JSONObject. @@ -169,12 +168,13 @@ public class JSONObject { * If a value is a non-finite number or if a name is * duplicated. */ - public JSONObject(JSONObject jo, String[] names) { + public JSONObject(final JSONObject jo, final String[] names) { this(); - for (int i = 0; i < names.length; i += 1) { + for (final String name : names) { try { - this.putOnce(names[i], jo.opt(names[i])); - } catch (Exception ignore) { + this.putOnce(name, jo.opt(name)); + } + catch (final Exception ignore) { } } } @@ -188,7 +188,7 @@ public class JSONObject { * If there is a syntax error in the source string or a * duplicated key. */ - public JSONObject(JSONTokener x) throws JSONException { + public JSONObject(final JSONTokener x) throws JSONException { this(); char c; String key; @@ -199,16 +199,16 @@ public class JSONObject { for (;;) { c = x.nextClean(); switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); } -// The key is followed by ':'. + // The key is followed by ':'. c = x.nextClean(); if (c != ':') { @@ -216,20 +216,20 @@ public class JSONObject { } this.putOnce(key, x.nextValue()); -// Pairs are separated by ','. + // Pairs are separated by ','. switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); + default: + throw x.syntaxError("Expected a ',' or '}'"); } } } @@ -242,13 +242,13 @@ public class JSONObject { * the JSONObject. * @throws JSONException */ - public JSONObject(Map map) { + public JSONObject(final Map map) { this.map = new HashMap(); if (map != null) { - Iterator> i = map.entrySet().iterator(); + final Iterator> i = map.entrySet().iterator(); while (i.hasNext()) { - Entry entry = i.next(); - Object value = entry.getValue(); + final Entry entry = i.next(); + final Object value = entry.getValue(); if (value != null) { this.map.put(entry.getKey(), wrap(value)); } @@ -277,7 +277,7 @@ public class JSONObject { * An object that has getter methods that should be used to make * a JSONObject. */ - public JSONObject(Object bean) { + public JSONObject(final Object bean) { this(); this.populateMap(bean); } @@ -296,14 +296,14 @@ public class JSONObject { * An array of strings, the names of the fields to be obtained * from the object. */ - public JSONObject(Object object, String names[]) { + public JSONObject(final Object object, final String names[]) { this(); - Class c = object.getClass(); - for (int i = 0; i < names.length; i += 1) { - String name = names[i]; + final Class c = object.getClass(); + for (final String name : names) { try { this.putOpt(name, c.getField(name).get(object)); - } catch (Exception ignore) { + } + catch (final Exception ignore) { } } } @@ -320,7 +320,7 @@ public class JSONObject { * If there is a syntax error in the source string or a * duplicated key. */ - public JSONObject(String source) throws JSONException { + public JSONObject(final String source) throws JSONException { this(new JSONTokener(source)); } @@ -334,27 +334,28 @@ public class JSONObject { * @throws JSONException * If any JSONExceptions are detected. */ - public JSONObject(String baseName, Locale locale) throws JSONException { + public JSONObject(final String baseName, final Locale locale) throws JSONException { this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, - Thread.currentThread().getContextClassLoader()); + final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); -// Iterate through the keys in the bundle. + // Iterate through the keys in the bundle. - Enumeration keys = bundle.getKeys(); + final Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { - Object key = keys.nextElement(); + final Object key = keys.nextElement(); if (key != null) { -// Go through the path, ensuring that there is a nested JSONObject for each -// segment except the last. Add the value using the last segment's name into -// the deepest nested JSONObject. + // Go through the path, ensuring that there is a nested + // JSONObject for each + // segment except the last. Add the value using the last + // segment's name into + // the deepest nested JSONObject. - String[] path = ((String) key).split("\\."); - int last = path.length - 1; + final String[] path = ((String) key).split("\\."); + final int last = path.length - 1; JSONObject target = this; for (int i = 0; i < last; i += 1) { - String segment = path[i]; + final String segment = path[i]; JSONObject nextTarget = target.optJSONObject(segment); if (nextTarget == null) { nextTarget = new JSONObject(); @@ -386,16 +387,16 @@ public class JSONObject { * @throws JSONException * If the value is an invalid number or if the key is null. */ - public JSONObject accumulate(String key, Object value) throws JSONException { + public JSONObject accumulate(final String key, final Object value) throws JSONException { testValidity(value); - Object object = this.opt(key); + final Object object = this.opt(key); if (object == null) { - this.put(key, - value instanceof JSONArray ? new JSONArray().put(value) - : value); - } else if (object instanceof JSONArray) { + this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } + else if (object instanceof JSONArray) { ((JSONArray) object).put(value); - } else { + } + else { this.put(key, new JSONArray().put(object).put(value)); } return this; @@ -416,16 +417,17 @@ public class JSONObject { * If the key is null or if the current value associated with * the key is not a JSONArray. */ - public JSONObject append(String key, Object value) throws JSONException { + public JSONObject append(final String key, final Object value) throws JSONException { testValidity(value); - Object object = this.opt(key); + final Object object = this.opt(key); if (object == null) { this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { + } + else if (object instanceof JSONArray) { this.put(key, ((JSONArray) object).put(value)); - } else { - throw new JSONException("JSONObject[" + key - + "] is not a JSONArray."); + } + else { + throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } @@ -438,16 +440,15 @@ public class JSONObject { * A double. * @return A String. */ - public static String doubleToString(double d) { + public static String doubleToString(final double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } -// Shave off trailing zeros and decimal point, if possible. + // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 - && string.indexOf('E') < 0) { + if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } @@ -467,11 +468,11 @@ public class JSONObject { * @throws JSONException * if the key is not found. */ - public Object get(String key) throws JSONException { + public Object get(final String key) throws JSONException { if (key == null) { throw new JSONException("Null key."); } - Object object = this.opt(key); + final Object object = this.opt(key); if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } @@ -488,19 +489,15 @@ public class JSONObject { * if the value is not a Boolean or the String "true" or * "false". */ - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - if (object.equals(Boolean.FALSE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { + public boolean getBoolean(final String key) throws JSONException { + final Object object = this.get(key); + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { return false; - } else if (object.equals(Boolean.TRUE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { + } + else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { return true; } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a Boolean."); + throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** @@ -513,14 +510,13 @@ public class JSONObject { * if the key is not found or if the value is not a Number * object and cannot be converted to a number. */ - public double getDouble(String key) throws JSONException { - Object object = this.get(key); + public double getDouble(final String key) throws JSONException { + final Object object = this.get(key); try { - return object instanceof Number ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not a number."); + return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + } + catch (final Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } @@ -534,14 +530,13 @@ public class JSONObject { * if the key is not found or if the value cannot be converted * to an integer. */ - public int getInt(String key) throws JSONException { - Object object = this.get(key); + public int getInt(final String key) throws JSONException { + final Object object = this.get(key); try { - return object instanceof Number ? ((Number) object).intValue() - : Integer.parseInt((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not an int."); + return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + } + catch (final Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } } @@ -554,13 +549,12 @@ public class JSONObject { * @throws JSONException * if the key is not found or if the value is not a JSONArray. */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); + public JSONArray getJSONArray(final String key) throws JSONException { + final Object object = this.get(key); if (object instanceof JSONArray) { return (JSONArray) object; } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a JSONArray."); + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** @@ -572,13 +566,12 @@ public class JSONObject { * @throws JSONException * if the key is not found or if the value is not a JSONObject. */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); + public JSONObject getJSONObject(final String key) throws JSONException { + final Object object = this.get(key); if (object instanceof JSONObject) { return (JSONObject) object; } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a JSONObject."); + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** @@ -591,14 +584,13 @@ public class JSONObject { * if the key is not found or if the value cannot be converted * to a long. */ - public long getLong(String key) throws JSONException { - Object object = this.get(key); + public long getLong(final String key) throws JSONException { + final Object object = this.get(key); try { - return object instanceof Number ? ((Number) object).longValue() - : Long.parseLong((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not a long."); + return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + } + catch (final Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } } @@ -607,13 +599,13 @@ public class JSONObject { * * @return An array of field names, or null if there are no names. */ - public static String[] getNames(JSONObject jo) { - int length = jo.length(); + public static String[] getNames(final JSONObject jo) { + final int length = jo.length(); if (length == 0) { return null; } - Iterator iterator = jo.keys(); - String[] names = new String[length]; + final Iterator iterator = jo.keys(); + final String[] names = new String[length]; int i = 0; while (iterator.hasNext()) { names[i] = iterator.next(); @@ -627,17 +619,17 @@ public class JSONObject { * * @return An array of field names, or null if there are no names. */ - public static String[] getNames(Object object) { + public static String[] getNames(final Object object) { if (object == null) { return null; } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; + final Class klass = object.getClass(); + final Field[] fields = klass.getFields(); + final int length = fields.length; if (length == 0) { return null; } - String[] names = new String[length]; + final String[] names = new String[length]; for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } @@ -653,8 +645,8 @@ public class JSONObject { * @throws JSONException * if there is no string value for the key. */ - public String getString(String key) throws JSONException { - Object object = this.get(key); + public String getString(final String key) throws JSONException { + final Object object = this.get(key); if (object instanceof String) { return (String) object; } @@ -668,7 +660,7 @@ public class JSONObject { * A key string. * @return true if the key exists in the JSONObject. */ - public boolean has(String key) { + public boolean has(final String key) { return this.map.containsKey(key); } @@ -684,19 +676,24 @@ public class JSONObject { * If there is already a property with this name that is not an * Integer, Long, Double, or Float. */ - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); + public JSONObject increment(final String key) throws JSONException { + final Object value = this.opt(key); if (value == null) { this.put(key, 1); - } else if (value instanceof Integer) { + } + else if (value instanceof Integer) { this.put(key, (Integer) value + 1); - } else if (value instanceof Long) { + } + else if (value instanceof Long) { this.put(key, (Long) value + 1); - } else if (value instanceof Double) { + } + else if (value instanceof Double) { this.put(key, (Double) value + 1); - } else if (value instanceof Float) { + } + else if (value instanceof Float) { this.put(key, (Float) value + 1); - } else { + } + else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } return this; @@ -711,7 +708,7 @@ public class JSONObject { * @return true if there is no value associated with the key or if the value * is the JSONObject.NULL object. */ - public boolean isNull(String key) { + public boolean isNull(final String key) { return JSONObject.NULL.equals(this.opt(key)); } @@ -750,8 +747,8 @@ public class JSONObject { * is empty. */ public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); + final JSONArray ja = new JSONArray(); + final Iterator keys = this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } @@ -767,17 +764,16 @@ public class JSONObject { * @throws JSONException * If n is a non-finite number. */ - public static String numberToString(Number number) throws JSONException { + public static String numberToString(final Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); -// Shave off trailing zeros and decimal point, if possible. + // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 - && string.indexOf('E') < 0) { + if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } @@ -795,7 +791,7 @@ public class JSONObject { * A key string. * @return An object which is the value, or null if there is no value. */ - public Object opt(String key) { + public Object opt(final String key) { return key == null ? null : this.map.get(key); } @@ -807,7 +803,7 @@ public class JSONObject { * A key string. * @return The truth. */ - public boolean optBoolean(String key) { + public boolean optBoolean(final String key) { return this.optBoolean(key, false); } @@ -822,10 +818,11 @@ public class JSONObject { * The default. * @return The truth. */ - public boolean optBoolean(String key, boolean defaultValue) { + public boolean optBoolean(final String key, final boolean defaultValue) { try { return this.getBoolean(key); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -839,7 +836,7 @@ public class JSONObject { * A string which is the key. * @return An object which is the value. */ - public double optDouble(String key) { + public double optDouble(final String key) { return this.optDouble(key, Double.NaN); } @@ -854,10 +851,11 @@ public class JSONObject { * The default. * @return An object which is the value. */ - public double optDouble(String key, double defaultValue) { + public double optDouble(final String key, final double defaultValue) { try { return this.getDouble(key); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -871,7 +869,7 @@ public class JSONObject { * A key string. * @return An object which is the value. */ - public int optInt(String key) { + public int optInt(final String key) { return this.optInt(key, 0); } @@ -886,10 +884,11 @@ public class JSONObject { * The default. * @return An object which is the value. */ - public int optInt(String key, int defaultValue) { + public int optInt(final String key, final int defaultValue) { try { return this.getInt(key); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -902,8 +901,8 @@ public class JSONObject { * A key string. * @return A JSONArray which is the value. */ - public JSONArray optJSONArray(String key) { - Object o = this.opt(key); + public JSONArray optJSONArray(final String key) { + final Object o = this.opt(key); return o instanceof JSONArray ? (JSONArray) o : null; } @@ -915,8 +914,8 @@ public class JSONObject { * A key string. * @return A JSONObject which is the value. */ - public JSONObject optJSONObject(String key) { - Object object = this.opt(key); + public JSONObject optJSONObject(final String key) { + final Object object = this.opt(key); return object instanceof JSONObject ? (JSONObject) object : null; } @@ -929,7 +928,7 @@ public class JSONObject { * A key string. * @return An object which is the value. */ - public long optLong(String key) { + public long optLong(final String key) { return this.optLong(key, 0); } @@ -944,10 +943,11 @@ public class JSONObject { * The default. * @return An object which is the value. */ - public long optLong(String key, long defaultValue) { + public long optLong(final String key, final long defaultValue) { try { return this.getLong(key); - } catch (Exception e) { + } + catch (final Exception e) { return defaultValue; } } @@ -961,7 +961,7 @@ public class JSONObject { * A key string. * @return A string which is the value. */ - public String optString(String key) { + public String optString(final String key) { return this.optString(key, ""); } @@ -975,53 +975,51 @@ public class JSONObject { * The default. * @return A string which is the value. */ - public String optString(String key, String defaultValue) { - Object object = this.opt(key); + public String optString(final String key, final String defaultValue) { + final Object object = this.opt(key); return NULL.equals(object) ? defaultValue : object.toString(); } - private void populateMap(Object bean) { - Class klass = bean.getClass(); + private void populateMap(final Object bean) { + final Class klass = bean.getClass(); -// If klass is a System class then set includeSuperClass to false. + // If klass is a System class then set includeSuperClass to false. - boolean includeSuperClass = klass.getClassLoader() != null; + final boolean includeSuperClass = klass.getClassLoader() != null; - Method[] methods = includeSuperClass ? klass.getMethods() : klass - .getDeclaredMethods(); - for (int i = 0; i < methods.length; i += 1) { + final Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); + for (final Method method : methods) { try { - Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); + final String name = method.getName(); String key = ""; if (name.startsWith("get")) { - if ("getClass".equals(name) - || "getDeclaringClass".equals(name)) { + if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key = ""; - } else { + } + else { key = name.substring(3); } - } else if (name.startsWith("is")) { + } + else if (name.startsWith("is")) { key = name.substring(2); } - if (key.length() > 0 - && Character.isUpperCase(key.charAt(0)) - && method.getParameterTypes().length == 0) { + if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) { if (key.length() == 1) { key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() - + key.substring(1); + } + else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + key.substring(1); } - Object result = method.invoke(bean, (Object[]) null); + final Object result = method.invoke(bean, (Object[]) null); if (result != null) { this.map.put(key, wrap(result)); } } } - } catch (Exception ignore) { + } + catch (final Exception ignore) { } } } @@ -1037,7 +1035,7 @@ public class JSONObject { * @throws JSONException * If the key is null. */ - public JSONObject put(String key, boolean value) throws JSONException { + public JSONObject put(final String key, final boolean value) throws JSONException { this.put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } @@ -1053,7 +1051,7 @@ public class JSONObject { * @return this. * @throws JSONException */ - public JSONObject put(String key, Collection value) throws JSONException { + public JSONObject put(final String key, final Collection value) throws JSONException { this.put(key, new JSONArray(value)); return this; } @@ -1069,7 +1067,7 @@ public class JSONObject { * @throws JSONException * If the key is null or if the number is invalid. */ - public JSONObject put(String key, double value) throws JSONException { + public JSONObject put(final String key, final double value) throws JSONException { this.put(key, new Double(value)); return this; } @@ -1085,7 +1083,7 @@ public class JSONObject { * @throws JSONException * If the key is null. */ - public JSONObject put(String key, int value) throws JSONException { + public JSONObject put(final String key, final int value) throws JSONException { this.put(key, new Integer(value)); return this; } @@ -1101,7 +1099,7 @@ public class JSONObject { * @throws JSONException * If the key is null. */ - public JSONObject put(String key, long value) throws JSONException { + public JSONObject put(final String key, final long value) throws JSONException { this.put(key, new Long(value)); return this; } @@ -1117,7 +1115,7 @@ public class JSONObject { * @return this. * @throws JSONException */ - public JSONObject put(String key, Map value) throws JSONException { + public JSONObject put(final String key, final Map value) throws JSONException { this.put(key, new JSONObject(value)); return this; } @@ -1136,14 +1134,15 @@ public class JSONObject { * @throws JSONException * If the value is non-finite number or if the key is null. */ - public JSONObject put(String key, Object value) throws JSONException { + public JSONObject put(final String key, final Object value) throws JSONException { if (key == null) { throw new NullPointerException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); - } else { + } + else { this.remove(key); } return this; @@ -1154,14 +1153,16 @@ public class JSONObject { * are both non-null, and only if there is not already a member with that * name. * - * @param key string - * @param value object + * @param key + * string + * @param value + * object * @return this. * @throws JSONException * if the key is a duplicate */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { + public JSONObject putOnce(final String key, final Object value) throws JSONException { + if ((key != null) && (value != null)) { if (this.opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } @@ -1184,8 +1185,8 @@ public class JSONObject { * @throws JSONException * If the value is a non-finite number. */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { + public JSONObject putOpt(final String key, final Object value) throws JSONException { + if ((key != null) && (value != null)) { this.put(key, value); } return this; @@ -1201,20 +1202,21 @@ public class JSONObject { * A String * @return A String correctly formatted for insertion in a JSON text. */ - public static String quote(String string) { - StringWriter sw = new StringWriter(); + public static String quote(final String string) { + final StringWriter sw = new StringWriter(); synchronized (sw.getBuffer()) { try { return quote(string, sw).toString(); - } catch (IOException ignored) { + } + catch (final IOException ignored) { // will never happen - we are writing to a string writer return ""; } } } - public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.length() == 0) { + public static Writer quote(final String string, final Writer w) throws IOException { + if ((string == null) || (string.length() == 0)) { w.write("\"\""); return w; } @@ -1223,49 +1225,49 @@ public class JSONObject { char c = 0; String hhhh; int i; - int len = string.length(); + final int len = string.length(); w.write('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { + case '\\': + case '"': w.write('\\'); - } - w.write(c); - break; - case '\b': - w.write("\\b"); - break; - case '\t': - w.write("\\t"); - break; - case '\n': - w.write("\\n"); - break; - case '\f': - w.write("\\f"); - break; - case '\r': - w.write("\\r"); - break; - default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - w.write("\\u"); - hhhh = Integer.toHexString(c); - w.write("0000", 0, 4 - hhhh.length()); - w.write(hhhh); - } else { w.write(c); - } + break; + case '/': + if (b == '<') { + w.write('\\'); + } + w.write(c); + break; + case '\b': + w.write("\\b"); + break; + case '\t': + w.write("\\t"); + break; + case '\n': + w.write("\\n"); + break; + case '\f': + w.write("\\f"); + break; + case '\r': + w.write("\\r"); + break; + default: + if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) { + w.write("\\u"); + hhhh = Integer.toHexString(c); + w.write("0000", 0, 4 - hhhh.length()); + w.write(hhhh); + } + else { + w.write(c); + } } } w.write('"'); @@ -1280,7 +1282,7 @@ public class JSONObject { * @return The value that was associated with the name, or null if there was * no value. */ - public Object remove(String key) { + public Object remove(final String key) { return this.map.remove(key); } @@ -1289,37 +1291,41 @@ public class JSONObject { * They must contain the same set of names which must be associated with * similar values. * - * @param other The other JSONObject + * @param other + * The other JSONObject * @return true if they are equal */ - public boolean similar(Object other) { + public boolean similar(final Object other) { try { if (!(other instanceof JSONObject)) { return false; } - Set set = this.keySet(); - if (!set.equals(((JSONObject)other).keySet())) { + final Set set = this.keySet(); + if (!set.equals(((JSONObject) other).keySet())) { return false; } - Iterator iterator = set.iterator(); + final Iterator iterator = set.iterator(); while (iterator.hasNext()) { - String name = iterator.next(); - Object valueThis = this.get(name); - Object valueOther = ((JSONObject)other).get(name); + final String name = iterator.next(); + final Object valueThis = this.get(name); + final Object valueOther = ((JSONObject) other).get(name); if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { + } + else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } - } else if (!valueThis.equals(valueOther)) { + } + else if (!valueThis.equals(valueOther)) { return false; } } return true; - } catch (Throwable exception) { + } + catch (final Throwable exception) { return false; } } @@ -1332,7 +1338,7 @@ public class JSONObject { * A String. * @return A simple JSON value. */ - public static Object stringToValue(String string) { + public static Object stringToValue(final String string) { Double d; if (string.equals("")) { return string; @@ -1352,26 +1358,28 @@ public class JSONObject { * produced, then the value will just be a string. */ - char b = string.charAt(0); - if ((b >= '0' && b <= '9') || b == '-') { + final char b = string.charAt(0); + if (((b >= '0') && (b <= '9')) || (b == '-')) { try { - if (string.indexOf('.') > -1 || string.indexOf('e') > -1 - || string.indexOf('E') > -1) { + if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1)) { d = Double.valueOf(string); if (!d.isInfinite() && !d.isNaN()) { return d; } - } else { - Long myLong = new Long(string); + } + else { + final Long myLong = new Long(string); if (string.equals(myLong.toString())) { if (myLong == myLong.intValue()) { return myLong.intValue(); - } else { + } + else { return myLong; } } } - } catch (Exception ignore) { + } + catch (final Exception ignore) { } } return string; @@ -1385,17 +1393,16 @@ public class JSONObject { * @throws JSONException * If o is a non-finite number. */ - public static void testValidity(Object o) throws JSONException { + public static void testValidity(final Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); + throw new JSONException("JSON does not allow non-finite numbers."); } - } else if (o instanceof Float) { + } + else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); + throw new JSONException("JSON does not allow non-finite numbers."); } } } @@ -1412,11 +1419,11 @@ public class JSONObject { * @throws JSONException * If any of the values are non-finite numbers. */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { + public JSONArray toJSONArray(final JSONArray names) throws JSONException { + if ((names == null) || (names.length() == 0)) { return null; } - JSONArray ja = new JSONArray(); + final JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } @@ -1435,10 +1442,12 @@ public class JSONObject { * brace) and ending with } (right * brace). */ + @Override public String toString() { try { return this.toString(0); - } catch (Exception e) { + } + catch (final Exception e) { return null; } } @@ -1457,8 +1466,8 @@ public class JSONObject { * @throws JSONException * If the object contains an invalid number. */ - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); + public String toString(final int indentFactor) throws JSONException { + final StringWriter w = new StringWriter(); synchronized (w.getBuffer()) { return this.write(w, indentFactor, 0).toString(); } @@ -1488,15 +1497,16 @@ public class JSONObject { * @throws JSONException * If the value is or contains an invalid number. */ - public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { + public static String valueToString(final Object value) throws JSONException { + if ((value == null) || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object object; try { object = ((JSONString) value).toJSONString(); - } catch (Exception e) { + } + catch (final Exception e) { throw new JSONException(e); } if (object instanceof String) { @@ -1507,12 +1517,11 @@ public class JSONObject { if (value instanceof Number) { return numberToString((Number) value); } - if (value instanceof Boolean || value instanceof JSONObject - || value instanceof JSONArray) { + if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { return value.toString(); } if (value instanceof Map) { - return new JSONObject((Map)value).toString(); + return new JSONObject((Map) value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection) value).toString(); @@ -1535,18 +1544,12 @@ public class JSONObject { * The object to wrap * @return The wrapped value */ - public static Object wrap(Object object) { + public static Object wrap(final Object object) { try { if (object == null) { return NULL; } - if (object instanceof JSONObject || object instanceof JSONArray - || NULL.equals(object) || object instanceof JSONString - || object instanceof Byte || object instanceof Character - || object instanceof Short || object instanceof Integer - || object instanceof Long || object instanceof Boolean - || object instanceof Float || object instanceof Double - || object instanceof String) { + if ((object instanceof JSONObject) || (object instanceof JSONArray) || NULL.equals(object) || (object instanceof JSONString) || (object instanceof Byte) || (object instanceof Character) || (object instanceof Short) || (object instanceof Integer) || (object instanceof Long) || (object instanceof Boolean) || (object instanceof Float) || (object instanceof Double) || (object instanceof String)) { return object; } @@ -1559,16 +1562,14 @@ public class JSONObject { if (object instanceof Map) { return new JSONObject((Map) object); } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null ? objectPackage - .getName() : ""; - if (objectPackageName.startsWith("java.") - || objectPackageName.startsWith("javax.") - || object.getClass().getClassLoader() == null) { + final Package objectPackage = object.getClass().getPackage(); + final String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) { return object.toString(); } return new JSONObject(object); - } catch (Exception exception) { + } + catch (final Exception exception) { return null; } } @@ -1582,44 +1583,52 @@ public class JSONObject { * @return The writer. * @throws JSONException */ - public Writer write(Writer writer) throws JSONException { + public Writer write(final Writer writer) throws JSONException { return this.write(writer, 0, 0); } - static final Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { - if (value == null || value.equals(null)) { + static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException { + if ((value == null) || value.equals(null)) { writer.write("null"); - } else if (value instanceof JSONObject) { + } + else if (value instanceof JSONObject) { ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { + } + else if (value instanceof JSONArray) { ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { + } + else if (value instanceof Map) { new JSONObject((Map) value).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { - new JSONArray((Collection) value).write(writer, indentFactor, - indent); - } else if (value.getClass().isArray()) { + } + else if (value instanceof Collection) { + new JSONArray((Collection) value).write(writer, indentFactor, indent); + } + else if (value.getClass().isArray()) { new JSONArray(value).write(writer, indentFactor, indent); - } else if (value instanceof Number) { + } + else if (value instanceof Number) { writer.write(numberToString((Number) value)); - } else if (value instanceof Boolean) { + } + else if (value instanceof Boolean) { writer.write(value.toString()); - } else if (value instanceof JSONString) { + } + else if (value instanceof JSONString) { Object o; try { o = ((JSONString) value).toJSONString(); - } catch (Exception e) { + } + catch (final Exception e) { throw new JSONException(e); } writer.write(o != null ? o.toString() : quote(value.toString())); - } else { + } + else { quote(value.toString(), writer); } return writer; } - static final void indent(Writer writer, int indent) throws IOException { + static final void indent(final Writer writer, final int indent) throws IOException { for (int i = 0; i < indent; i += 1) { writer.write(' '); } @@ -1634,26 +1643,26 @@ public class JSONObject { * @return The writer. * @throws JSONException */ - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { + Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { try { boolean commanate = false; final int length = this.length(); - Iterator keys = this.keys(); + final Iterator keys = this.keys(); writer.write('{'); if (length == 1) { - Object key = keys.next(); + final Object key = keys.next(); writer.write(quote(key.toString())); writer.write(':'); if (indentFactor > 0) { writer.write(' '); } writeValue(writer, this.map.get(key), indentFactor, indent); - } else if (length != 0) { + } + else if (length != 0) { final int newindent = indent + indentFactor; while (keys.hasNext()) { - Object key = keys.next(); + final Object key = keys.next(); if (commanate) { writer.write(','); } @@ -1676,7 +1685,8 @@ public class JSONObject { } writer.write('}'); return writer; - } catch (IOException exception) { + } + catch (final IOException exception) { throw new JSONException(exception); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONString.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONString.java index 5bc7c9e49..9e97b4512 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONString.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONString.java @@ -1,4 +1,5 @@ package com.intellectualcrafters.json; + /** * The JSONString interface allows a toJSONString() * method so that a class can change the behavior of @@ -9,7 +10,8 @@ package com.intellectualcrafters.json; */ public interface JSONString { /** - * The toJSONString method allows a class to produce its own JSON + * The toJSONString method allows a class to produce its own + * JSON * serialization. * * @return A strictly syntactically correct JSON text. diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONStringer.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONStringer.java index 789413189..4e6160aac 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONStringer.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONStringer.java @@ -1,28 +1,28 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2006 JSON.org + Copyright (c) 2006 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ import java.io.StringWriter; @@ -33,26 +33,29 @@ import java.io.StringWriter; * JSONStringer can produce one JSON text. *

    * A JSONStringer instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting cascade style. For example,

    - * myString = new JSONStringer()
    - *     .object()
    - *         .key("JSON")
    - *         .value("Hello, World!")
    - *     .endObject()
    - *     .toString();
    which produces the string
    - * {"JSON":"Hello, World!"}
    + * values to the text, and a key method for adding keys before + * values in objects. There are array and endArray + * methods that make and bound array values, and object and + * endObject methods which make and bound object values. All of + * these methods return the JSONWriter instance, permitting cascade style. For + * example, + * + *
    + * myString = new JSONStringer().object().key("JSON").value("Hello, World!").endObject().toString();
    + * 
    + * + * which produces the string + * + *
    + * {"JSON":"Hello, World!"}
    + * 
    *

    * The first method called must be array or object. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 20 levels deep. *

    * This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2008-09-18 */ @@ -70,8 +73,10 @@ public class JSONStringer extends JSONWriter { * problem in the construction of the JSON text (such as the calls to * array were not properly balanced with calls to * endArray). + * * @return The JSON text. */ + @Override public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONTokener.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONTokener.java index 8c71feacf..aae93fbf2 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONTokener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONTokener.java @@ -8,56 +8,55 @@ import java.io.Reader; import java.io.StringReader; /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. + * * @author JSON.org * @version 2014-05-03 */ public class JSONTokener { - private long character; - private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; - private boolean usePrevious; - + private long character; + private boolean eof; + private long index; + private long line; + private char previous; + private final Reader reader; + private boolean usePrevious; /** * Construct a JSONTokener from a Reader. * - * @param reader A reader. + * @param reader + * A reader. */ - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); + public JSONTokener(final Reader reader) { + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; @@ -66,33 +65,33 @@ public class JSONTokener { this.line = 1; } - /** * Construct a JSONTokener from an InputStream. - * @param inputStream The source. + * + * @param inputStream + * The source. */ - public JSONTokener(InputStream inputStream) throws JSONException { + public JSONTokener(final InputStream inputStream) throws JSONException { this(new InputStreamReader(inputStream)); } - /** * Construct a JSONTokener from a string. * - * @param s A source string. + * @param s + * A source string. */ - public JSONTokener(String s) { + public JSONTokener(final String s) { this(new StringReader(s)); } - /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { + if (this.usePrevious || (this.index <= 0)) { throw new JSONException("Stepping back two steps is not supported"); } this.index -= 1; @@ -101,21 +100,22 @@ public class JSONTokener { this.eof = false; } - /** * Get the hex value of a character (base16). - * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. + * + * @param c + * A character between '0' and '9' or between 'A' and 'F' or + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. */ - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { + public static int dehexchar(final char c) { + if ((c >= '0') && (c <= '9')) { return c - '0'; } - if (c >= 'A' && c <= 'F') { + if ((c >= 'A') && (c <= 'F')) { return c - ('A' - 10); } - if (c >= 'a' && c <= 'f') { + if ((c >= 'a') && (c <= 'f')) { return c - ('a' - 10); } return -1; @@ -125,10 +125,10 @@ public class JSONTokener { return this.eof && !this.usePrevious; } - /** * Determine if the source string still contains characters that next() * can consume. + * * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { @@ -140,7 +140,6 @@ public class JSONTokener { return true; } - /** * Get the next character in the source string. * @@ -151,10 +150,12 @@ public class JSONTokener { if (this.usePrevious) { this.usePrevious = false; c = this.previous; - } else { + } + else { try { c = this.reader.read(); - } catch (IOException exception) { + } + catch (final IOException exception) { throw new JSONException(exception); } @@ -167,150 +168,156 @@ public class JSONTokener { if (this.previous == '\r') { this.line += 1; this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { + } + else if (c == '\n') { this.line += 1; this.character = 0; - } else { + } + else { this.character += 1; } this.previous = (char) c; return this.previous; } - /** * Consume the next character, and check that it matches a specified * character. - * @param c The character to match. + * + * @param c + * The character to match. * @return The character. - * @throws JSONException if the character does not match. + * @throws JSONException + * if the character does not match. */ - public char next(char c) throws JSONException { - char n = this.next(); + public char next(final char c) throws JSONException { + final char n = this.next(); if (n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); + throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } - /** * Get the next n characters. * - * @param n The number of characters to take. - * @return A string of n characters. + * @param n + * The number of characters to take. + * @return A string of n characters. * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. + * Substring bounds error if there are not + * n characters remaining in the source string. */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } + public String next(final int n) throws JSONException { + if (n == 0) { + return ""; + } - char[] chars = new char[n]; - int pos = 0; - - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } + final char[] chars = new char[n]; + int pos = 0; + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } /** * Get the next char in the string, skipping whitespace. + * * @throws JSONException - * @return A character, or 0 if there are no more characters. + * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { - char c = this.next(); - if (c == 0 || c > ' ') { + final char c = this.next(); + if ((c == 0) || (c > ' ')) { return c; } } } - /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. - * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. - * @throws JSONException Unterminated string. + * + * @param quote + * The quoting character, either " + *  (double quote) or ' + *  (single quote). + * @return A String. + * @throws JSONException + * Unterminated string. */ - public String nextString(char quote) throws JSONException { + public String nextString(final char quote) throws JSONException { char c; - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); for (;;) { c = this.next(); switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char)Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); case '\\': - case '/': - sb.append(c); + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char) Integer.parseInt(this.next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } break; default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); + if (c == quote) { + return sb.toString(); + } + sb.append(c); } } } - /** * Get the text up but not including the specified character or the * end of line, whichever comes first. - * @param delimiter A delimiter character. - * @return A string. + * + * @param delimiter + * A delimiter character. + * @return A string. */ - public String nextTo(char delimiter) throws JSONException { - StringBuilder sb = new StringBuilder(); + public String nextTo(final char delimiter) throws JSONException { + final StringBuilder sb = new StringBuilder(); for (;;) { - char c = this.next(); - if (c == delimiter || c == 0 || c == '\n' || c == '\r') { + final char c = this.next(); + if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) { if (c != 0) { this.back(); } @@ -320,20 +327,20 @@ public class JSONTokener { } } - /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. - * @param delimiters A set of delimiter characters. + * + * @param delimiters + * A set of delimiter characters. * @return A string, trimmed. */ - public String nextTo(String delimiters) throws JSONException { + public String nextTo(final String delimiters) throws JSONException { char c; - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); for (;;) { c = this.next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { + if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) { if (c != 0) { this.back(); } @@ -343,11 +350,12 @@ public class JSONTokener { } } - /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. + * + * @throws JSONException + * If syntax error. * * @return An object. */ @@ -371,13 +379,12 @@ public class JSONTokener { * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. - * * Accumulate characters until we reach the end of the text or a * formatting character. */ - StringBuilder sb = new StringBuilder(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + final StringBuilder sb = new StringBuilder(); + while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0)) { sb.append(c); c = this.next(); } @@ -390,20 +397,21 @@ public class JSONTokener { return JSONObject.stringToValue(string); } - /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. - * @param to A character to skip to. + * + * @param to + * A character to skip to. * @return The requested character, or zero if the requested character - * is not found. + * is not found. */ - public char skipTo(char to) throws JSONException { + public char skipTo(final char to) throws JSONException { char c; try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; + final long startIndex = this.index; + final long startCharacter = this.character; + final long startLine = this.line; this.reader.mark(1000000); do { c = this.next(); @@ -414,33 +422,34 @@ public class JSONTokener { this.line = startLine; return c; } - } while (c != to); - } catch (IOException exception) { + } + while (c != to); + } + catch (final IOException exception) { throw new JSONException(exception); } this.back(); return c; } - /** * Make a JSONException to signal a syntax error. * - * @param message The error message. - * @return A JSONException object, suitable for throwing + * @param message + * The error message. + * @return A JSONException object, suitable for throwing */ - public JSONException syntaxError(String message) { + public JSONException syntaxError(final String message) { return new JSONException(message + this.toString()); } - /** * Make a printable string of this JSONTokener. * * @return " at {index} [character {character} line {line}]" */ + @Override public String toString() { - return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; + return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONWriter.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONWriter.java index c53fb7f87..e08702cce 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONWriter.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/JSONWriter.java @@ -1,30 +1,31 @@ package com.intellectualcrafters.json; + import java.io.IOException; import java.io.Writer; /* -Copyright (c) 2006 JSON.org + Copyright (c) 2006 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ /** * JSONWriter provides a quick and convenient way of producing JSON text. @@ -33,25 +34,29 @@ SOFTWARE. * JSONWriter can produce one JSON text. *

    * A JSONWriter instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting a cascade style. For example,

    - * new JSONWriter(myWriter)
    - *     .object()
    - *         .key("JSON")
    - *         .value("Hello, World!")
    - *     .endObject();
    which writes
    - * {"JSON":"Hello, World!"}
    + * values to the text, and a key method for adding keys before + * values in objects. There are array and endArray + * methods that make and bound array values, and object and + * endObject methods which make and bound object values. All of + * these methods return the JSONWriter instance, permitting a cascade style. For + * example, + * + *
    + * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
    + * 
    + * + * which writes + * + *
    + * {"JSON":"Hello, World!"}
    + * 
    *

    * The first method called must be array or object. * There are no methods for adding commas or colons. JSONWriter adds them for * you. Objects and arrays can be nested up to 20 levels deep. *

    * This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2011-11-24 */ @@ -62,7 +67,7 @@ public class JSONWriter { * The comma flag determines if a comma should be output before the next * value. */ - private boolean comma; + private boolean comma; /** * The current mode. Values: @@ -72,7 +77,7 @@ public class JSONWriter { * 'k' (key), * 'o' (object). */ - protected char mode; + protected char mode; /** * The object/array stack. @@ -82,17 +87,17 @@ public class JSONWriter { /** * The stack top index. A value of 0 indicates that the stack is empty. */ - private int top; + private int top; /** * The writer that will receive the output. */ - protected Writer writer; + protected Writer writer; /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ - public JSONWriter(Writer w) { + public JSONWriter(final Writer w) { this.comma = false; this.mode = 'i'; this.stack = new JSONObject[maxdepth]; @@ -102,21 +107,25 @@ public class JSONWriter { /** * Append a value. - * @param string A string value. + * + * @param string + * A string value. * @return this - * @throws JSONException If the value is out of sequence. + * @throws JSONException + * If the value is out of sequence. */ - private JSONWriter append(String string) throws JSONException { + private JSONWriter append(final String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } - if (this.mode == 'o' || this.mode == 'a') { + if ((this.mode == 'o') || (this.mode == 'a')) { try { - if (this.comma && this.mode == 'a') { + if (this.comma && (this.mode == 'a')) { this.writer.write(','); } this.writer.write(string); - } catch (IOException e) { + } + catch (final IOException e) { throw new JSONException(e); } if (this.mode == 'o') { @@ -132,13 +141,16 @@ public class JSONWriter { * Begin appending a new array. All values until the balancing * endArray will be appended to this array. The * endArray method must be called to mark the array's end. + * * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). + * @throws JSONException + * If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the + * end of the + * outermost array or object). */ public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + if ((this.mode == 'i') || (this.mode == 'o') || (this.mode == 'a')) { this.push(null); this.append("["); this.comma = false; @@ -149,21 +161,24 @@ public class JSONWriter { /** * End something. - * @param mode Mode - * @param c Closing character + * + * @param mode + * Mode + * @param c + * Closing character * @return this - * @throws JSONException If unbalanced. + * @throws JSONException + * If unbalanced. */ - private JSONWriter end(char mode, char c) throws JSONException { + private JSONWriter end(final char mode, final char c) throws JSONException { if (this.mode != mode) { - throw new JSONException(mode == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); + throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); - } catch (IOException e) { + } + catch (final IOException e) { throw new JSONException(e); } this.comma = true; @@ -173,8 +188,10 @@ public class JSONWriter { /** * End an array. This method most be called to balance calls to * array. + * * @return this - * @throws JSONException If incorrectly nested. + * @throws JSONException + * If incorrectly nested. */ public JSONWriter endArray() throws JSONException { return this.end('a', ']'); @@ -183,8 +200,10 @@ public class JSONWriter { /** * End an object. This method most be called to balance calls to * object. + * * @return this - * @throws JSONException If incorrectly nested. + * @throws JSONException + * If incorrectly nested. */ public JSONWriter endObject() throws JSONException { return this.end('k', '}'); @@ -193,12 +212,15 @@ public class JSONWriter { /** * Append a key. The key will be associated with the next value. In an * object, every value must be preceded by a key. - * @param string A key string. + * + * @param string + * A key string. * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. + * @throws JSONException + * If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. */ - public JSONWriter key(String string) throws JSONException { + public JSONWriter key(final String string) throws JSONException { if (string == null) { throw new JSONException("Null key."); } @@ -213,28 +235,31 @@ public class JSONWriter { this.comma = false; this.mode = 'o'; return this; - } catch (IOException e) { + } + catch (final IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); } - /** * Begin appending a new object. All keys and values until the balancing * endObject will be appended to this object. The * endObject method must be called to mark the object's end. + * * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). + * @throws JSONException + * If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the + * end of the + * outermost array or object). */ public JSONWriter object() throws JSONException { if (this.mode == 'i') { this.mode = 'o'; } - if (this.mode == 'o' || this.mode == 'a') { + if ((this.mode == 'o') || (this.mode == 'a')) { this.append("{"); this.push(new JSONObject()); this.comma = false; @@ -244,34 +269,35 @@ public class JSONWriter { } - /** * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. + * + * @param c + * The scope to close. + * @throws JSONException + * If nesting is wrong. */ - private void pop(char c) throws JSONException { + private void pop(final char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + final char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; + this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; } /** * Push an array or object scope. - * @param jo The scope to open. - * @throws JSONException If nesting is too deep. + * + * @param jo + * The scope to open. + * @throws JSONException + * If nesting is too deep. */ - private void push(JSONObject jo) throws JSONException { + private void push(final JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } @@ -280,47 +306,56 @@ public class JSONWriter { this.top += 1; } - /** - * Append either the value true or the value - * false. - * @param b A boolean. + * Append either the value true or the value false + * . + * + * @param b + * A boolean. * @return this * @throws JSONException */ - public JSONWriter value(boolean b) throws JSONException { + public JSONWriter value(final boolean b) throws JSONException { return this.append(b ? "true" : "false"); } /** * Append a double value. - * @param d A double. + * + * @param d + * A double. * @return this - * @throws JSONException If the number is not finite. + * @throws JSONException + * If the number is not finite. */ - public JSONWriter value(double d) throws JSONException { + public JSONWriter value(final double d) throws JSONException { return this.value(new Double(d)); } /** * Append a long value. - * @param l A long. + * + * @param l + * A long. * @return this * @throws JSONException */ - public JSONWriter value(long l) throws JSONException { + public JSONWriter value(final long l) throws JSONException { return this.append(Long.toString(l)); } - /** * Append an object value. - * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. + * + * @param object + * The object to append. It can be null, or a Boolean, Number, + * String, JSONObject, or JSONArray, or an object that implements + * JSONString. * @return this - * @throws JSONException If the value is out of sequence. + * @throws JSONException + * If the value is out of sequence. */ - public JSONWriter value(Object object) throws JSONException { + public JSONWriter value(final Object object) throws JSONException { return this.append(JSONObject.valueToString(object)); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/Kim.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/Kim.java index f1ba94d5d..825421f7b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/Kim.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/Kim.java @@ -32,11 +32,11 @@ package com.intellectualcrafters.json; * than 3 bytes. Every byte contributes 7 bits to the character. ASCII is * unmodified. * - * Kim UTF-8 - * one byte U+007F U+007F - * two bytes U+3FFF U+07FF - * three bytes U+10FFF U+FFFF - * four bytes U+10FFFF + * Kim UTF-8 + * one byte U+007F U+007F + * two bytes U+3FFF U+07FF + * three bytes U+10FFF U+FFFF + * four bytes U+10FFFF * * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one * byte smaller when encoded in Kim compared to UTF-8. @@ -65,23 +65,23 @@ public class Kim { /** * The byte array containing the kim's content. */ - private byte[] bytes = null; + private byte[] bytes = null; /** * The kim's hashcode, conforming to Java's hashcode conventions. */ - private int hashcode = 0; + private int hashcode = 0; /** * The number of bytes in the kim. The number of bytes can be as much as * three times the number of characters. */ - public int length = 0; + public int length = 0; /** * The memoization of toString(). */ - private String string = null; + private String string = null; /** * Make a kim from a portion of a byte array. @@ -93,10 +93,11 @@ public class Kim { * @param thru * The index of the last byte plus one. */ - public Kim(byte[] bytes, int from, int thru) { + public Kim(final byte[] bytes, final int from, final int thru) { -// As the bytes are copied into the new kim, a hashcode is computed using a -// modified Fletcher code. + // As the bytes are copied into the new kim, a hashcode is computed + // using a + // modified Fletcher code. int sum = 1; int value; @@ -105,7 +106,7 @@ public class Kim { if (this.length > 0) { this.bytes = new byte[this.length]; for (int at = 0; at < this.length; at += 1) { - value = (int) bytes[at + from] & 0xFF; + value = bytes[at + from] & 0xFF; sum += value; this.hashcode += sum; this.bytes[at] = (byte) value; @@ -122,7 +123,7 @@ public class Kim { * @param length * The number of bytes. */ - public Kim(byte[] bytes, int length) { + public Kim(final byte[] bytes, final int length) { this(bytes, 0, length); } @@ -137,7 +138,7 @@ public class Kim { * @param thru * The point at which to stop taking bytes. */ - public Kim(Kim kim, int from, int thru) { + public Kim(final Kim kim, final int from, final int thru) { this(kim.bytes, from, thru); } @@ -149,26 +150,28 @@ public class Kim { * @throws JSONException * if surrogate pair mismatch. */ - public Kim(String string) throws JSONException { - int stringLength = string.length(); + public Kim(final String string) throws JSONException { + final int stringLength = string.length(); this.hashcode = 0; this.length = 0; -// First pass: Determine the length of the kim, allowing for the UTF-16 -// to UTF-32 conversion, and then the UTF-32 to Kim conversion. + // First pass: Determine the length of the kim, allowing for the UTF-16 + // to UTF-32 conversion, and then the UTF-32 to Kim conversion. if (stringLength > 0) { for (int i = 0; i < stringLength; i += 1) { - int c = string.charAt(i); + final int c = string.charAt(i); if (c <= 0x7F) { this.length += 1; - } else if (c <= 0x3FFF) { + } + else if (c <= 0x3FFF) { this.length += 2; - } else { - if (c >= 0xD800 && c <= 0xDFFF) { + } + else { + if ((c >= 0xD800) && (c <= 0xDFFF)) { i += 1; - int d = string.charAt(i); - if (c > 0xDBFF || d < 0xDC00 || d > 0xDFFF) { + final int d = string.charAt(i); + if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) { throw new JSONException("Bad UTF16"); } } @@ -176,49 +179,51 @@ public class Kim { } } -// Second pass: Allocate a byte array and fill that array with the conversion -// while computing the hashcode. + // Second pass: Allocate a byte array and fill that array with the + // conversion + // while computing the hashcode. - this.bytes = new byte[length]; + this.bytes = new byte[this.length]; int at = 0; int b; int sum = 1; for (int i = 0; i < stringLength; i += 1) { int character = string.charAt(i); if (character <= 0x7F) { - bytes[at] = (byte) character; + this.bytes[at] = (byte) character; sum += character; this.hashcode += sum; at += 1; - } else if (character <= 0x3FFF) { + } + else if (character <= 0x3FFF) { b = 0x80 | (character >>> 7); - bytes[at] = (byte) b; + this.bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; b = character & 0x7F; - bytes[at] = (byte) b; + this.bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; - } else { - if (character >= 0xD800 && character <= 0xDBFF) { + } + else { + if ((character >= 0xD800) && (character <= 0xDBFF)) { i += 1; - character = (((character & 0x3FF) << 10) | (string - .charAt(i) & 0x3FF)) + 65536; + character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; } b = 0x80 | (character >>> 14); - bytes[at] = (byte) b; + this.bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; b = 0x80 | ((character >>> 7) & 0xFF); - bytes[at] = (byte) b; + this.bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; b = character & 0x7F; - bytes[at] = (byte) b; + this.bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; @@ -239,23 +244,23 @@ public class Kim { * @throws JSONException * if at does not point to a valid character. */ - public int characterAt(int at) throws JSONException { - int c = get(at); + public int characterAt(final int at) throws JSONException { + final int c = get(at); if ((c & 0x80) == 0) { return c; } int character; - int c1 = get(at + 1); + final int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } - } else { - int c2 = get(at + 2); + } + else { + final int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; - if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF - && (character < 0xD800 || character > 0xDFFF)) { + if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) { return character; } } @@ -272,8 +277,8 @@ public class Kim { * @throws JSONException * if the character is not representable in a kim. */ - public static int characterSize(int character) throws JSONException { - if (character < 0 || character > 0x10FFFF) { + public static int characterSize(final int character) throws JSONException { + if ((character < 0) || (character > 0x10FFFF)) { throw new JSONException("Bad character " + character); } return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; @@ -288,7 +293,7 @@ public class Kim { * The position within the byte array to take the byes. * @return The position immediately after the copy. */ - public int copy(byte[] bytes, int at) { + public int copy(final byte[] bytes, final int at) { System.arraycopy(this.bytes, 0, bytes, at, this.length); return at + this.length; } @@ -302,11 +307,12 @@ public class Kim { * @returns true if this and obj are both kim objects containing identical * byte sequences. */ - public boolean equals(Object obj) { + @Override + public boolean equals(final Object obj) { if (!(obj instanceof Kim)) { return false; } - Kim that = (Kim) obj; + final Kim that = (Kim) obj; if (this == that) { return true; } @@ -318,22 +324,24 @@ public class Kim { /** * Get a byte from a kim. + * * @param at * The position of the byte. The first byte is at 0. * @return The byte. * @throws JSONException * if there is no byte at that position. */ - public int get(int at) throws JSONException { - if (at < 0 || at > this.length) { + public int get(final int at) throws JSONException { + if ((at < 0) || (at > this.length)) { throw new JSONException("Bad character at " + at); } - return ((int) this.bytes[at]) & 0xFF; + return (this.bytes[at]) & 0xFF; } /** * Returns a hash code value for the kim. */ + @Override public int hashCode() { return this.hashcode; } @@ -347,17 +355,19 @@ public class Kim { * @throws JSONException * if the kim is not valid. */ + @Override public String toString() throws JSONException { if (this.string == null) { int c; int length = 0; - char chars[] = new char[this.length]; + final char chars[] = new char[this.length]; for (int at = 0; at < this.length; at += characterSize(c)) { c = this.characterAt(at); if (c < 0x10000) { chars[length] = (char) c; length += 1; - } else { + } + else { chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10)); length += 1; chars[length] = (char) (0xDC00 | (c & 0x03FF)); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/Property.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/Property.java index 10cff2c8c..8b323eec2 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/Property.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/Property.java @@ -1,28 +1,28 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ import java.util.Enumeration; import java.util.Iterator; @@ -30,22 +30,26 @@ import java.util.Properties; /** * Converts a Property file data into JSONObject and back. + * * @author JSON.org * @version 2014-05-03 */ public class Property { /** - * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. - * @param properties java.util.Properties + * Converts a property file object into a JSONObject. The property file + * object is a table of name value pairs. + * + * @param properties + * java.util.Properties * @return JSONObject * @throws JSONException */ - public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { - JSONObject jo = new JSONObject(); - if (properties != null && !properties.isEmpty()) { - Enumeration enumProperties = properties.propertyNames(); - while(enumProperties.hasMoreElements()) { - String name = (String)enumProperties.nextElement(); + public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException { + final JSONObject jo = new JSONObject(); + if ((properties != null) && !properties.isEmpty()) { + final Enumeration enumProperties = properties.propertyNames(); + while (enumProperties.hasMoreElements()) { + final String name = (String) enumProperties.nextElement(); jo.put(name, properties.getProperty(name)); } } @@ -54,16 +58,18 @@ public class Property { /** * Converts the JSONObject into a property file object. - * @param jo JSONObject + * + * @param jo + * JSONObject * @return java.util.Properties * @throws JSONException */ - public static Properties toProperties(JSONObject jo) throws JSONException { - Properties properties = new Properties(); + public static Properties toProperties(final JSONObject jo) throws JSONException { + final Properties properties = new Properties(); if (jo != null) { - Iterator keys = jo.keys(); + final Iterator keys = jo.keys(); while (keys.hasNext()) { - String name = keys.next(); + final String name = keys.next(); properties.put(name, jo.getString(name)); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/XML.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/XML.java index af1ac0591..f74ea5de5 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/XML.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/XML.java @@ -1,34 +1,35 @@ package com.intellectualcrafters.json; /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. + * * @author JSON.org * @version 2014-05-03 */ @@ -63,37 +64,40 @@ public class XML { /** * Replace special characters with XML escapes: + * *

          * & (ampersand) is replaced by &amp;
          * < (less than) is replaced by &lt;
          * > (greater than) is replaced by &gt;
          * " (double quote) is replaced by &quot;
          * 
    - * @param string The string to be escaped. + * + * @param string + * The string to be escaped. * @return The escaped string. */ - public static String escape(String string) { - StringBuilder sb = new StringBuilder(string.length()); + public static String escape(final String string) { + final StringBuilder sb = new StringBuilder(string.length()); for (int i = 0, length = string.length(); i < length; i++) { - char c = string.charAt(i); + final char c = string.charAt(i); switch (c) { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - sb.append(c); + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + sb.append(c); } } return sb.toString(); @@ -102,52 +106,57 @@ public class XML { /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. - * @param string A string. + * + * @param string + * A string. * @throws JSONException */ - public static void noSpace(String string) throws JSONException { - int i, length = string.length(); + public static void noSpace(final String string) throws JSONException { + int i; + final int length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + - "' contains a space character."); + throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. - * @param x The XMLTokener containing the source string. - * @param context The JSONObject that will include the new material. - * @param name The tag name. + * + * @param x + * The XMLTokener containing the source string. + * @param context + * The JSONObject that will include the new material. + * @param name + * The tag name. * @return true if the close tag is processed. * @throws JSONException */ - private static boolean parse(XMLTokener x, JSONObject context, - String name) throws JSONException { - char c; - int i; + private static boolean parse(final XMLTokener x, final JSONObject context, final String name) throws JSONException { + char c; + int i; JSONObject jsonobject = null; - String string; - String tagName; - Object token; + String string; + String tagName; + Object token; -// Test for and skip past these forms: -// -// -// -// -// Report errors for these forms: -// <> -// <= -// << + // Test for and skip past these forms: + // + // + // + // + // Report errors for these forms: + // <> + // <= + // << token = x.nextToken(); -// ' after ' 0); + } + while (i > 0); return false; - } else if (token == QUEST) { + } + else if (token == QUEST) { -// "); return false; - } else if (token == SLASH) { + } + else if (token == SLASH) { -// Close tag + // Empty tag <.../> - } else if (token == SLASH) { + } + else if (token == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); - } else { + } + else { context.accumulate(tagName, ""); } return false; -// Content, between <...> and + // Content, between <...> and - } else if (token == GT) { + } + else if (token == GT) { for (;;) { token = x.nextContent(); if (token == null) { @@ -258,48 +278,51 @@ public class XML { throw x.syntaxError("Unclosed tag " + tagName); } return false; - } else if (token instanceof String) { - string = (String)token; + } + else if (token instanceof String) { + string = (String) token; if (string.length() > 0) { - jsonobject.accumulate("content", - XML.stringToValue(string)); + jsonobject.accumulate("content", XML.stringToValue(string)); } -// Nested element + // Nested element - } else if (token == LT) { + } + else if (token == LT) { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); - } else if (jsonobject.length() == 1 && - jsonobject.opt("content") != null) { - context.accumulate(tagName, - jsonobject.opt("content")); - } else { + } + else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) { + context.accumulate(tagName, jsonobject.opt("content")); + } + else { context.accumulate(tagName, jsonobject); } return false; } } } - } else { + } + else { throw x.syntaxError("Misshaped tag"); } } } } - /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. This is much less ambitious than * JSONObject.stringToValue, especially because it does not attempt to * convert plus forms, octal forms, hex forms, or E forms lacking decimal * points. - * @param string A String. + * + * @param string + * A String. * @return A simple JSON value. */ - public static Object stringToValue(String string) { + public static Object stringToValue(final String string) { if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } @@ -310,30 +333,32 @@ public class XML { return JSONObject.NULL; } -// If it might be a number, try converting it, first as a Long, and then as a -// Double. If that doesn't work, return the string. + // If it might be a number, try converting it, first as a Long, and then + // as a + // Double. If that doesn't work, return the string. try { - char initial = string.charAt(0); - if (initial == '-' || (initial >= '0' && initial <= '9')) { - Long value = new Long(string); + final char initial = string.charAt(0); + if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) { + final Long value = new Long(string); if (value.toString().equals(string)) { return value; } } - } catch (Exception ignore) { + } + catch (final Exception ignore) { try { - Double value = new Double(string); + final Double value = new Double(string); if (value.toString().equals(string)) { return value; } - } catch (Exception ignoreAlso) { + } + catch (final Exception ignoreAlso) { } } return string; } - /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation @@ -344,52 +369,56 @@ public class XML { * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <[ [ ]]> are ignored. - * @param string The source string. + * + * @param string + * The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); + public static JSONObject toJSONObject(final String string) throws JSONException { + final JSONObject jo = new JSONObject(); + final XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; } - /** * Convert a JSONObject into a well-formed, element-normal XML string. - * @param object A JSONObject. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object) throws JSONException { - return toString(object, null); - } - - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * @param object A JSONObject. - * @param tagName The optional name of the enclosing tag. + * + * @param object + * A JSONObject. * @return A string. * @throws JSONException */ - public static String toString(Object object, String tagName) - throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; + public static String toString(final Object object) throws JSONException { + return toString(object, null); + } + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * + * @param object + * A JSONObject. + * @param tagName + * The optional name of the enclosing tag. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object, final String tagName) throws JSONException { + final StringBuilder sb = new StringBuilder(); + int i; + JSONArray ja; + JSONObject jo; + String key; + Iterator keys; + int length; + String string; + Object value; if (object instanceof JSONObject) { -// Emit + // Emit if (tagName != null) { sb.append('<'); @@ -397,9 +426,9 @@ public class XML { sb.append('>'); } -// Loop thru the keys. + // Loop thru the keys. - jo = (JSONObject)object; + jo = (JSONObject) object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next(); @@ -407,13 +436,13 @@ public class XML { if (value == null) { value = ""; } - string = value instanceof String ? (String)value : null; + string = value instanceof String ? (String) value : null; -// Emit content in body + // Emit content in body if ("content".equals(key)) { if (value instanceof JSONArray) { - ja = (JSONArray)value; + ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { if (i > 0) { @@ -421,14 +450,16 @@ public class XML { } sb.append(escape(ja.get(i).toString())); } - } else { + } + else { sb.append(escape(value.toString())); } -// Emit an array of similar keys + // Emit an array of similar keys - } else if (value instanceof JSONArray) { - ja = (JSONArray)value; + } + else if (value instanceof JSONArray) { + ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { value = ja.get(i); @@ -440,24 +471,27 @@ public class XML { sb.append("'); - } else { + } + else { sb.append(toString(value, key)); } } - } else if ("".equals(value)) { + } + else if ("".equals(value)) { sb.append('<'); sb.append(key); sb.append("/>"); -// Emit a new tag + // Emit a new tag - } else { + } + else { sb.append(toString(value, key)); } } if (tagName != null) { -// Emit the close tag + // Emit the close tag sb.append(" element. + // XML does not have good support for arrays. If an array appears in + // a place + // where XML is lacking, synthesize an element. - } else { + } + else { if (object.getClass().isArray()) { object = new JSONArray(object); } if (object instanceof JSONArray) { - ja = (JSONArray)object; + ja = (JSONArray) object; length = ja.length(); for (i = 0; i < length; i += 1) { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); - } else { + } + else { string = (object == null) ? "null" : escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : - (string.length() == 0) ? "<" + tagName + "/>" : - "<" + tagName + ">" + string + ""; + return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; } } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/json/XMLTokener.java b/PlotSquared/src/main/java/com/intellectualcrafters/json/XMLTokener.java index 0c6b99699..b1319b473 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/json/XMLTokener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/json/XMLTokener.java @@ -1,68 +1,74 @@ package com.intellectualcrafters.json; + /* -Copyright (c) 2002 JSON.org + Copyright (c) 2002 JSON.org -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. -The Software shall be used for Good, not Evil. + The Software shall be used for Good, not Evil. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ /** * The XMLTokener extends the JSONTokener to provide additional methods * for the parsing of XML texts. + * * @author JSON.org * @version 2014-05-03 */ public class XMLTokener extends JSONTokener { + /** + * The table of entity values. It initially contains Character values for + * amp, apos, gt, lt, quot. + */ + public static final java.util.HashMap entity; - /** The table of entity values. It initially contains Character values for - * amp, apos, gt, lt, quot. - */ - public static final java.util.HashMap entity; - - static { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } + static { + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } /** * Construct an XMLTokener from a string. - * @param s A source string. + * + * @param s + * A source string. */ - public XMLTokener(String s) { + public XMLTokener(final String s) { super(s); } /** * Get the text in the CDATA block. + * * @return The string up to the ]]>. - * @throws JSONException If the ]]> is not found. + * @throws JSONException + * If the ]]> is not found. */ public String nextCDATA() throws JSONException { - char c; - int i; - StringBuilder sb = new StringBuilder(); + char c; + int i; + final StringBuilder sb = new StringBuilder(); for (;;) { c = next(); if (end()) { @@ -70,15 +76,13 @@ public class XMLTokener extends JSONTokener { } sb.append(c); i = sb.length() - 3; - if (i >= 0 && sb.charAt(i) == ']' && - sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { + if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) { sb.setLength(i); return sb.toString(); } } } - /** * Get the next XML outer token, trimming whitespace. There are two kinds * of tokens: the '<' character which begins a markup tag, and the content @@ -89,11 +93,12 @@ public class XMLTokener extends JSONTokener { * @throws JSONException */ public Object nextContent() throws JSONException { - char c; + char c; StringBuilder sb; do { c = next(); - } while (Character.isWhitespace(c)); + } + while (Character.isWhitespace(c)); if (c == 0) { return null; } @@ -102,118 +107,127 @@ public class XMLTokener extends JSONTokener { } sb = new StringBuilder(); for (;;) { - if (c == '<' || c == 0) { + if ((c == '<') || (c == 0)) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); - } else { + } + else { sb.append(c); } c = next(); } } - /** * Return the next entity. These entities are translated to Characters: - * & ' > < ". - * @param ampersand An ampersand character. - * @return A Character or an entity String if the entity is not recognized. - * @throws JSONException If missing ';' in XML entity. + * & ' > < ". + * + * @param ampersand + * An ampersand character. + * @return A Character or an entity String if the entity is not recognized. + * @throws JSONException + * If missing ';' in XML entity. */ - public Object nextEntity(char ampersand) throws JSONException { - StringBuilder sb = new StringBuilder(); + public Object nextEntity(final char ampersand) throws JSONException { + final StringBuilder sb = new StringBuilder(); for (;;) { - char c = next(); - if (Character.isLetterOrDigit(c) || c == '#') { + final char c = next(); + if (Character.isLetterOrDigit(c) || (c == '#')) { sb.append(Character.toLowerCase(c)); - } else if (c == ';') { + } + else if (c == ';') { break; - } else { + } + else { throw syntaxError("Missing ';' in XML entity: &" + sb); } } - String string = sb.toString(); - Object object = entity.get(string); + final String string = sb.toString(); + final Object object = entity.get(string); return object != null ? object : ampersand + string + ";"; } - /** * Returns the next XML meta token. This is used for skipping over * and structures. + * * @return Syntax characters (< > / = ! ?) are returned as - * Character, and strings and names are returned as Boolean. We don't care - * what the values actually are. - * @throws JSONException If a string is not properly closed or if the XML - * is badly structured. + * Character, and strings and names are returned as Boolean. We + * don't care + * what the values actually are. + * @throws JSONException + * If a string is not properly closed or if the XML + * is badly structured. */ public Object nextMeta() throws JSONException { char c; char q; do { c = next(); - } while (Character.isWhitespace(c)); + } + while (Character.isWhitespace(c)); switch (c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for (;;) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return Boolean.TRUE; + } } - if (c == q) { - return Boolean.TRUE; + default: + for (;;) { + c = next(); + if (Character.isWhitespace(c)) { + return Boolean.TRUE; + } + switch (c) { + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } } - } - default: - for (;;) { - c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - } - } } } - /** * Get the next XML Token. These tokens are found inside of angle * brackets. It may be one of these characters: / > = ! ? or it * may be a string wrapped in single quotes or double quotes, or it may be a * name. + * * @return a String or a Character. - * @throws JSONException If the XML is not well formed. + * @throws JSONException + * If the XML is not well formed. */ public Object nextToken() throws JSONException { char c; @@ -221,90 +235,94 @@ public class XMLTokener extends JSONTokener { StringBuilder sb; do { c = next(); - } while (Character.isWhitespace(c)); + } + while (Character.isWhitespace(c)); switch (c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; -// Quoted string + // Quoted string - case '"': - case '\'': - q = c; - sb = new StringBuilder(); - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); + case '"': + case '\'': + q = c; + sb = new StringBuilder(); + for (;;) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return sb.toString(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } + else { + sb.append(c); + } } - if (c == q) { - return sb.toString(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { + default: + + // Name + + sb = new StringBuilder(); + for (;;) { sb.append(c); + c = next(); + if (Character.isWhitespace(c)) { + return sb.toString(); + } + switch (c) { + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } } - } - default: - -// Name - - sb = new StringBuilder(); - for (;;) { - sb.append(c); - c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); - } - switch (c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } } } - /** * Skip characters until past the requested string. - * If it is not found, we are left at the end of the source with a result of false. - * @param to A string to skip past. + * If it is not found, we are left at the end of the source with a result of + * false. + * + * @param to + * A string to skip past. * @throws JSONException */ - public boolean skipPast(String to) throws JSONException { + public boolean skipPast(final String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; - int length = to.length(); - char[] circle = new char[length]; + final int length = to.length(); + final char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/AbstractFlag.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/AbstractFlag.java index 7e3c6004f..1584e085e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/AbstractFlag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/AbstractFlag.java @@ -7,55 +7,60 @@ import org.apache.commons.lang.StringUtils; */ public class AbstractFlag { - private final String key; + private final String key; - /** - * AbstractFlag is a parameter used in creating a new Flag - * - * @param key - * The key must be alphabetical characters and <= 16 characters - * in length - */ - public AbstractFlag(String key) { - if (!StringUtils.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) { - throw new IllegalArgumentException("Flag must be alphabetic characters"); - } - if (key.length() > 16) { - throw new IllegalArgumentException("Key must be <= 16 characters"); - } - this.key = key.toLowerCase(); - } - - public String parseValue(String value) { - return value; - } - - public String getValueDesc() { - return "Flag value must be alphanumeric"; - } - + /** + * AbstractFlag is a parameter used in creating a new Flag + * + * @param key + * The key must be alphabetical characters and <= 16 characters + * in length + */ + public AbstractFlag(final String key) { + if (!StringUtils.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) { + throw new IllegalArgumentException("Flag must be alphabetic characters"); + } + if (key.length() > 16) { + throw new IllegalArgumentException("Key must be <= 16 characters"); + } + this.key = key.toLowerCase(); + } - /** - * AbstractFlag key - * - * @return String - */ - public String getKey() { - return this.key; - } + public String parseValue(final String value) { + return value; + } - @Override - public String toString() { - return this.key; - } - - @Override - public boolean equals(Object other){ - if (other == null) return false; - if (other == this) return true; - if (!(other instanceof AbstractFlag)) return false; - AbstractFlag otherObj = (AbstractFlag)other; - return (otherObj.key.equals(this.key)); - } + public String getValueDesc() { + return "Flag value must be alphanumeric"; + } + + /** + * AbstractFlag key + * + * @return String + */ + public String getKey() { + return this.key; + } + + @Override + public String toString() { + return this.key; + } + + @Override + public boolean equals(final Object other) { + if (other == null) { + return false; + } + if (other == this) { + return true; + } + if (!(other instanceof AbstractFlag)) { + return false; + } + final AbstractFlag otherObj = (AbstractFlag) other; + return (otherObj.key.equals(this.key)); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/BlockWrapper.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/BlockWrapper.java index c3bfec157..f4da88e2c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/BlockWrapper.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/BlockWrapper.java @@ -1,13 +1,14 @@ package com.intellectualcrafters.plot; + public class BlockWrapper { - public int x; - public int y; - public int z; - public int id; + public int x; + public int y; + public int z; + public int id; public byte data; - - public BlockWrapper(int x, int y, int z, short id, byte data) { + + public BlockWrapper(final int x, final int y, final int z, final short id, final byte data) { this.x = x; this.y = y; this.z = z; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/C.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/C.java index c5cbc7ae3..468131ebe 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/C.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/C.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = C.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ @@ -40,7 +40,7 @@ public enum C { NOT_CONSOLE("&cFor safety reasons, this command can only be executed by console."), IS_CONSOLE("&cThis command can only be executed by a player."), /* - Clipboard + * Clipboard */ CLIPBOARD_SET("&cThe current plot is now copied to your clipboard, use &6/plot paste&c to paste it"), PASTED("&cThe plot selection was successfully pasted. It has been cleared from your clipboard."), @@ -150,8 +150,8 @@ public enum C { */ INVALID_PLAYER("&cPlayer not found: &6%player%."), /* - * - */ + * + */ COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."), /* * purge @@ -219,7 +219,7 @@ public enum C { */ PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"), PLOT_INFO("&6ID&7: &a%id%&7\n&6Alias&7: &a%alias%\n&6Owner&7: &a%owner%\n&6Helpers&7: &a%helpers%\n&6Trusted&7: &a%trusted%\n&Denied&7: &a%denied%\n&6Denied&7: &a%denied%\n&6Flags&7: &a%flags%\n&6Biome&7: &a%biome%\n&6Rating&7: &a%rating%&7/&a10\n&6Can build&7: &a%build%"), - + PLOT_INFO_HELPERS("&6Helpers&7: %helpers%"), PLOT_INFO_TRUSTED("&6Trusted&7: %trusted%"), PLOT_INFO_DENIED("&6Denied&7: %denied%"), @@ -230,7 +230,7 @@ public enum C { PLOT_INFO_ID("&6ID&7: %id%"), PLOT_INFO_ALIAS("&6Alias&7: %alias%"), PLOT_INFO_SIZE("&6Size&7: %size%"), - + PLOT_USER_LIST(" &6%user%&c,"), INFO_SYNTAX_CONSOLE("/plot info X;Y"), /* @@ -327,10 +327,7 @@ public enum C { HELP_CATEGORY("&6Current Category&c: &l%category%"), HELP_INFO("&6You need to specify a help category"), HELP_INFO_ITEM("&6/plots help %category% &c- &6%category_desc%"), - HELP_PAGE( - "&c>> &6%usage% &c[&6%alias%&c]\n" + - "&c>> &6%desc%\n" - ), + HELP_PAGE("&c>> &6%usage% &c[&6%alias%&c]\n" + "&c>> &6%desc%\n"), HELP_ITEM_SEPARATOR("&c%lines"), HELP_HEADER("&c(Page &6%cur&c/&6%max&c) &6Help for Plots"), /* @@ -344,77 +341,78 @@ public enum C { /** * Default */ - private String d; - /** - * Translated - */ - private String s; + private String d; + /** + * Translated + */ + private String s; - /** - * Constructor for custom strings. - */ - @SuppressWarnings("unused") - C() { - /* - * use setCustomString(); - */ - } + /** + * Constructor for custom strings. + */ + @SuppressWarnings("unused") + C() { + /* + * use setCustomString(); + */ + } - /** - * Constructor - * - * @param d - * default - */ - C(String d) { - this.d = d; - if (PlotMain.translations == null) { - this.s = d; - } - else { - this.s = PlotMain.translations.getString(this.toString()); - } - if (this.s == null) { - this.s = ""; - } - } + /** + * Constructor + * + * @param d + * default + */ + C(final String d) { + this.d = d; + if (PlotMain.translations == null) { + this.s = d; + } + else { + this.s = PlotMain.translations.getString(this.toString()); + } + if (this.s == null) { + this.s = ""; + } + } public static class Potato { } - /** - * Get the default string - * - * @return default - */ - @SuppressWarnings("unused") - public String d() { - return this.d; - } - /** - * Get translated if exists - * - * @return translated if exists else default - */ - public String s() { - if(PlotMain.translations != null){ - String t = PlotMain.translations.getString(this.toString()); - if (t!=null) { + /** + * Get the default string + * + * @return default + */ + @SuppressWarnings("unused") + public String d() { + return this.d; + } + + /** + * Get translated if exists + * + * @return translated if exists else default + */ + public String s() { + if (PlotMain.translations != null) { + final String t = PlotMain.translations.getString(this.toString()); + if (t != null) { this.s = t; } } - if (this.s.length() < 1) { - return ""; - } - return this.s.replace("\\n", "\n"); - } + if (this.s.length() < 1) { + return ""; + } + return this.s.replace("\\n", "\n"); + } - /** - * @return translated and color decoded - */ - public String translated() { - return ChatColor.translateAlternateColorCodes('&', this.s()); - } + /** + * @return translated and color decoded + */ + public String translated() { + return ChatColor.translateAlternateColorCodes('&', this.s()); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Configuration.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Configuration.java index 53b9c4482..fd79e967f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Configuration.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Configuration.java @@ -3,265 +3,266 @@ package com.intellectualcrafters.plot; import java.util.ArrayList; import java.util.List; -import org.bukkit.Bukkit; import org.bukkit.block.Biome; public class Configuration { - public static final SettingValue STRING = new SettingValue("STRING") { - @Override - public boolean validateValue(String string) { - return true; - } + public static final SettingValue STRING = new SettingValue("STRING") { + @Override + public boolean validateValue(final String string) { + return true; + } - @Override - public Object parseString(String string) { - return string; - } - }; + @Override + public Object parseString(final String string) { + return string; + } + }; - public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") { - @Override - public boolean validateValue(String string) { - return true; - } + public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") { + @Override + public boolean validateValue(final String string) { + return true; + } - @Override - public Object parseString(String string) { - return string.split(","); - } - }; + @Override + public Object parseString(final String string) { + return string.split(","); + } + }; - public static final SettingValue INTEGER = new SettingValue("INTEGER") { - @Override - public boolean validateValue(String string) { - try { - Integer.parseInt(string); - return true; - } - catch (Exception e) { - return false; - } - } + public static final SettingValue INTEGER = new SettingValue("INTEGER") { + @Override + public boolean validateValue(final String string) { + try { + Integer.parseInt(string); + return true; + } + catch (final Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Integer.parseInt(string); - } - }; + @Override + public Object parseString(final String string) { + return Integer.parseInt(string); + } + }; - public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { - @Override - public boolean validateValue(String string) { - try { - Boolean.parseBoolean(string); - return true; - } - catch (Exception e) { - return false; - } - } + public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { + @Override + public boolean validateValue(final String string) { + try { + Boolean.parseBoolean(string); + return true; + } + catch (final Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Boolean.parseBoolean(string); - } - }; + @Override + public Object parseString(final String string) { + return Boolean.parseBoolean(string); + } + }; - public static final SettingValue DOUBLE = new SettingValue("DOUBLE") { - @Override - public boolean validateValue(String string) { - try { - Double.parseDouble(string); - return true; - } - catch (Exception e) { - return false; - } - } + public static final SettingValue DOUBLE = new SettingValue("DOUBLE") { + @Override + public boolean validateValue(final String string) { + try { + Double.parseDouble(string); + return true; + } + catch (final Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Double.parseDouble(string); - } - }; + @Override + public Object parseString(final String string) { + return Double.parseDouble(string); + } + }; - public static final SettingValue BIOME = new SettingValue("BIOME") { - @Override - public boolean validateValue(String string) { - try { - Biome.valueOf(string.toUpperCase()); - return true; - } - catch (Exception e) { - return false; - } - } + public static final SettingValue BIOME = new SettingValue("BIOME") { + @Override + public boolean validateValue(final String string) { + try { + Biome.valueOf(string.toUpperCase()); + return true; + } + catch (final Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - for (Biome biome : Biome.values()) { - if (biome.name().equals(string.toUpperCase())) { - return biome; - } - } - return Biome.FOREST; - } + @Override + public Object parseString(final String string) { + for (final Biome biome : Biome.values()) { + if (biome.name().equals(string.toUpperCase())) { + return biome; + } + } + return Biome.FOREST; + } - @Override - public Object parseObject(Object object) { - return ((Biome) object).toString(); - } - }; + @Override + public Object parseObject(final Object object) { + return ((Biome) object).toString(); + } + }; - public static final SettingValue BLOCK = new SettingValue("BLOCK") { - @Override - public boolean validateValue(String string) { - try { - if (string.contains(":")) { - String[] split = string.split(":"); - Short.parseShort(split[0]); - Short.parseShort(split[1]); - } - else { - Short.parseShort(string); - } - return true; - } - catch (Exception e) { - return false; - } - } + public static final SettingValue BLOCK = new SettingValue("BLOCK") { + @Override + public boolean validateValue(final String string) { + try { + if (string.contains(":")) { + final String[] split = string.split(":"); + Short.parseShort(split[0]); + Short.parseShort(split[1]); + } + else { + Short.parseShort(string); + } + return true; + } + catch (final Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - if (string.contains(":")) { - String[] split = string.split(":"); - return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); - } - else { - return new PlotBlock(Short.parseShort(string), (byte) 0); - } - } + @Override + public Object parseString(final String string) { + if (string.contains(":")) { + final String[] split = string.split(":"); + return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); + } + else { + return new PlotBlock(Short.parseShort(string), (byte) 0); + } + } - @Override - public Object parseObject(Object object) { - return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data; - } - }; - - public static int gcd(int a, int b) { - if (b==0) return a; - return gcd(b,a%b); - } - private static int gcd(int[] a) - { - int result = a[0]; - for(int i = 1; i < a.length; i++) - result = gcd(result, a[i]); - return result; - } + @Override + public Object parseObject(final Object object) { + return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data; + } + }; - public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") { - @Override - public boolean validateValue(String string) { - try { - for (String block : string.split(",")) { - if (block.contains("%")) { - String[] split = block.split("%"); - Integer.parseInt(split[0]); - block = split[1]; - } - if (block.contains(":")) { - String[] split = block.split(":"); - Short.parseShort(split[0]); - Short.parseShort(split[1]); - } - else { - Short.parseShort(block); - } - } - return true; - } - catch (Exception e) { - return false; - } - } + public static int gcd(final int a, final int b) { + if (b == 0) { + return a; + } + return gcd(b, a % b); + } - @Override - public Object parseString(String string) { - String[] blocks = string.split(","); - ArrayList parsedvalues = new ArrayList(); - - - PlotBlock[] values = new PlotBlock[blocks.length]; - int[] counts = new int[blocks.length]; - int min = 100; - for (int i = 0; i < blocks.length; i++) { - if (blocks[i].contains("%")) { - String[] split = blocks[i].split("%"); - blocks[i] = split[1]; - int value = Integer.parseInt(split[0]); - counts[i] = value; - if (value parsedvalues = new ArrayList(); + + final PlotBlock[] values = new PlotBlock[blocks.length]; + final int[] counts = new int[blocks.length]; + int min = 100; + for (int i = 0; i < blocks.length; i++) { + if (blocks[i].contains("%")) { + final String[] split = blocks[i].split("%"); + blocks[i] = split[1]; + final int value = Integer.parseInt(split[0]); + counts[i] = value; + if (value < min) { min = value; } - } - else { - counts[i] = 1; - if (1 list = new ArrayList(); - for (PlotBlock block : (PlotBlock[]) object) { - list.add((block.id + ":" + (block.data))); - } - return list; - } - }; + return parsedvalues.toArray(new PlotBlock[0]); + } - /** - * Create your own SettingValue object to make the management of plotworld - * configuration easier - */ - public static abstract class SettingValue { - private String type; + @Override + public Object parseObject(final Object object) { + final List list = new ArrayList(); + for (final PlotBlock block : (PlotBlock[]) object) { + list.add((block.id + ":" + (block.data))); + } + return list; + } + }; - public SettingValue(String type) { - this.type = type; - } + /** + * Create your own SettingValue object to make the management of plotworld + * configuration easier + */ + public static abstract class SettingValue { + private final String type; - public String getType() { - return this.type; - } + public SettingValue(final String type) { + this.type = type; + } - public Object parseObject(Object object) { - return object; - } + public String getType() { + return this.type; + } - public abstract Object parseString(String string); + public Object parseObject(final Object object) { + return object; + } - public abstract boolean validateValue(String string); - } + public abstract Object parseString(final String string); + + public abstract boolean validateValue(final String string); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConfigurationNode.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConfigurationNode.java index 802da7517..92c9ee1e3 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConfigurationNode.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConfigurationNode.java @@ -1,70 +1,70 @@ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.Configuration.SettingValue; -import org.apache.commons.lang.StringUtils; - import java.util.Arrays; +import org.apache.commons.lang.StringUtils; + +import com.intellectualcrafters.plot.Configuration.SettingValue; + public class ConfigurationNode { - private String constant; - private Object default_value; - private String description; - private Object value; - private SettingValue type; + private final String constant; + private final Object default_value; + private final String description; + private Object value; + private final SettingValue type; - public ConfigurationNode(String constant, Object default_value, String description, SettingValue type, - boolean required) { - this.constant = constant; - this.default_value = default_value; - this.description = description; - this.value = default_value; - this.type = type; - } + public ConfigurationNode(final String constant, final Object default_value, final String description, final SettingValue type, final boolean required) { + this.constant = constant; + this.default_value = default_value; + this.description = description; + this.value = default_value; + this.type = type; + } - public SettingValue getType() { - return this.type; - } + public SettingValue getType() { + return this.type; + } - public boolean isValid(String string) { - try { - Object result = this.type.parseString(string); - if (result == null) { - return false; - } - return true; - } - catch (Exception e) { - return false; - } - } + public boolean isValid(final String string) { + try { + final Object result = this.type.parseString(string); + if (result == null) { + return false; + } + return true; + } + catch (final Exception e) { + return false; + } + } - public boolean setValue(String string) { - if (!this.type.validateValue(string)) { - return false; - } - this.value = this.type.parseString(string); - return true; - } + public boolean setValue(final String string) { + if (!this.type.validateValue(string)) { + return false; + } + this.value = this.type.parseString(string); + return true; + } - public Object getValue() { - if (this.value instanceof String[]) { - return Arrays.asList((String[]) this.value); - } - return this.value; - } + public Object getValue() { + if (this.value instanceof String[]) { + return Arrays.asList((String[]) this.value); + } + return this.value; + } - public String getConstant() { - return this.constant; - } + public String getConstant() { + return this.constant; + } - public Object getDefaultValue() { - if (this.default_value instanceof String[]) { - return StringUtils.join((String[]) this.default_value, ","); - } - return this.default_value; - } + public Object getDefaultValue() { + if (this.default_value instanceof String[]) { + return StringUtils.join((String[]) this.default_value, ","); + } + return this.default_value; + } - public String getDescription() { - return this.description; - } + public String getDescription() { + return this.description; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConsoleColors.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConsoleColors.java index b256b58bb..147f1a248 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConsoleColors.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/ConsoleColors.java @@ -7,95 +7,95 @@ import org.bukkit.ChatColor; */ public class ConsoleColors { - static enum ConsoleColor { - RESET("\u001B[0m"), - BLACK("\u001B[30m"), - RED("\u001B[31m"), - GREEN("\u001B[32m"), - YELLOW("\u001B[33m"), - BLUE("\u001B[34m"), - PURPLE("\u001B[35m"), - CYAN("\u001B[36m"), - WHITE("\u001B[37m"), - BOLD("\033[1m"), - UNDERLINE("\033[0m"), - ITALIC("\033[3m"); + static enum ConsoleColor { + RESET("\u001B[0m"), + BLACK("\u001B[30m"), + RED("\u001B[31m"), + GREEN("\u001B[32m"), + YELLOW("\u001B[33m"), + BLUE("\u001B[34m"), + PURPLE("\u001B[35m"), + CYAN("\u001B[36m"), + WHITE("\u001B[37m"), + BOLD("\033[1m"), + UNDERLINE("\033[0m"), + ITALIC("\033[3m"); - private String win; - private String lin; + private final String win; + private final String lin; - ConsoleColor(String lin) { - this.lin = lin; - this.win = this.win; - } + ConsoleColor(final String lin) { + this.lin = lin; + this.win = this.win; + } - public String getWin() { - return this.win; - } + public String getWin() { + return this.win; + } - public String getLin() { - return this.lin; - } - } + public String getLin() { + return this.lin; + } + } - /* - * public static final String ANSI_RESET = "\u001B[0m"; public static final - * String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED = - * "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; - * public static final String ANSI_YELLOW = "\u001B[33m"; public static - * final String ANSI_BLUE = "\u001B[34m"; public static final String - * ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN = - * "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m"; - * public static final String ANSI_BOLD = "\033[1m"; public static final - * String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC - * = "\033[3m]"; - */ + /* + * public static final String ANSI_RESET = "\u001B[0m"; public static final + * String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED = + * "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; + * public static final String ANSI_YELLOW = "\u001B[33m"; public static + * final String ANSI_BLUE = "\u001B[34m"; public static final String + * ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN = + * "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m"; + * public static final String ANSI_BOLD = "\033[1m"; public static final + * String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC + * = "\033[3m]"; + */ - public static String fromString(String input) { - input = - input.replaceAll("&0", fromChatColor(ChatColor.BLACK)).replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)).replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)).replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)).replaceAll("&4", fromChatColor(ChatColor.DARK_RED)).replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)).replaceAll("&6", fromChatColor(ChatColor.GOLD)).replaceAll("&7", fromChatColor(ChatColor.GRAY)).replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)).replaceAll("&9", fromChatColor(ChatColor.BLUE)).replaceAll("&a", fromChatColor(ChatColor.GREEN)).replaceAll("&b", fromChatColor(ChatColor.AQUA)).replaceAll("&c", fromChatColor(ChatColor.RED)).replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)).replaceAll("&e", fromChatColor(ChatColor.YELLOW)).replaceAll("&f", fromChatColor(ChatColor.WHITE)).replaceAll("&k", fromChatColor(ChatColor.MAGIC)).replaceAll("&l", fromChatColor(ChatColor.BOLD)).replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH)).replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET)); - return input + "\u001B[0m"; - } + public static String fromString(String input) { + input = input.replaceAll("&0", fromChatColor(ChatColor.BLACK)).replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)).replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)).replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)).replaceAll("&4", fromChatColor(ChatColor.DARK_RED)).replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)).replaceAll("&6", fromChatColor(ChatColor.GOLD)).replaceAll("&7", fromChatColor(ChatColor.GRAY)).replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)).replaceAll("&9", fromChatColor(ChatColor.BLUE)).replaceAll("&a", fromChatColor(ChatColor.GREEN)).replaceAll("&b", fromChatColor(ChatColor.AQUA)).replaceAll("&c", fromChatColor(ChatColor.RED)).replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)).replaceAll("&e", fromChatColor(ChatColor.YELLOW)).replaceAll("&f", fromChatColor(ChatColor.WHITE)).replaceAll("&k", fromChatColor(ChatColor.MAGIC)).replaceAll("&l", fromChatColor(ChatColor.BOLD)).replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH)) + .replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET)); + return input + "\u001B[0m"; + } - public static String fromChatColor(ChatColor color) { - return chatColor(color).getLin(); - } + public static String fromChatColor(final ChatColor color) { + return chatColor(color).getLin(); + } - public static ConsoleColor chatColor(ChatColor color) { - switch (color) { - case RESET: - return ConsoleColor.RESET; - case GRAY: - case DARK_GRAY: - return ConsoleColor.WHITE; - case BLACK: - return ConsoleColor.BLACK; - case DARK_RED: - case RED: - return ConsoleColor.RED; - case GOLD: - case YELLOW: - return ConsoleColor.YELLOW; - case DARK_GREEN: - case GREEN: - return ConsoleColor.GREEN; - case AQUA: - case DARK_AQUA: - return ConsoleColor.CYAN; - case LIGHT_PURPLE: - case DARK_PURPLE: - return ConsoleColor.PURPLE; - case BLUE: - case DARK_BLUE: - return ConsoleColor.BLUE; - case UNDERLINE: - return ConsoleColor.UNDERLINE; - case ITALIC: - return ConsoleColor.ITALIC; - case BOLD: - return ConsoleColor.BOLD; - default: - return ConsoleColor.RESET; - } - } + public static ConsoleColor chatColor(final ChatColor color) { + switch (color) { + case RESET: + return ConsoleColor.RESET; + case GRAY: + case DARK_GRAY: + return ConsoleColor.WHITE; + case BLACK: + return ConsoleColor.BLACK; + case DARK_RED: + case RED: + return ConsoleColor.RED; + case GOLD: + case YELLOW: + return ConsoleColor.YELLOW; + case DARK_GREEN: + case GREEN: + return ConsoleColor.GREEN; + case AQUA: + case DARK_AQUA: + return ConsoleColor.CYAN; + case LIGHT_PURPLE: + case DARK_PURPLE: + return ConsoleColor.PURPLE; + case BLUE: + case DARK_BLUE: + return ConsoleColor.BLUE; + case UNDERLINE: + return ConsoleColor.UNDERLINE; + case ITALIC: + return ConsoleColor.ITALIC; + case BOLD: + return ConsoleColor.BOLD; + default: + return ConsoleColor.RESET; + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Flag.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Flag.java index bac20c5fa..8e9645424 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Flag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Flag.java @@ -3,94 +3,93 @@ package com.intellectualcrafters.plot; import org.apache.commons.lang.StringUtils; public class Flag { - private AbstractFlag key; - private String value; + private final AbstractFlag key; + private final String value; - /** - * Flag object used to store basic information for a Plot. Flags are a - * key/value pair. For a flag to be usable by a player, you need to register - * it with PlotSquared. - * - * @param key - * AbstractFlag - * @param value - * Value must be alphanumerical (can have spaces) and be <= 48 - * characters - * @throws IllegalArgumentException - * if you provide inadequate inputs - */ - public Flag(AbstractFlag key, String value) { - char[] allowedCharacters = new char[] { - '[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§' - }; + /** + * Flag object used to store basic information for a Plot. Flags are a + * key/value pair. For a flag to be usable by a player, you need to register + * it with PlotSquared. + * + * @param key + * AbstractFlag + * @param value + * Value must be alphanumerical (can have spaces) and be <= 48 + * characters + * @throws IllegalArgumentException + * if you provide inadequate inputs + */ + public Flag(final AbstractFlag key, final String value) { + final char[] allowedCharacters = new char[] { '[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§' }; String tempValue = value; - for(char c : allowedCharacters) + for (final char c : allowedCharacters) { tempValue = tempValue.replace(c, 'c'); - if (!StringUtils.isAlphanumericSpace(tempValue)) { - throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)"); - } - if (value.length() > 48) { - throw new IllegalArgumentException("Value must be <= 48 characters"); - } - this.key = key; - this.value = key.parseValue(value); - if (this.value==null) { - throw new IllegalArgumentException(key.getValueDesc()); - } - } + } + if (!StringUtils.isAlphanumericSpace(tempValue)) { + throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)"); + } + if (value.length() > 48) { + throw new IllegalArgumentException("Value must be <= 48 characters"); + } + this.key = key; + this.value = key.parseValue(value); + if (this.value == null) { + throw new IllegalArgumentException(key.getValueDesc()); + } + } - /** - * Get the AbstractFlag used in creating the flag - * - * @return AbstractFlag - */ - public AbstractFlag getAbstractFlag() { - return this.key; - } + /** + * Get the AbstractFlag used in creating the flag + * + * @return AbstractFlag + */ + public AbstractFlag getAbstractFlag() { + return this.key; + } - /** - * Get the key for the AbstractFlag - * - * @return String - */ - public String getKey() { - return this.key.getKey(); - } + /** + * Get the key for the AbstractFlag + * + * @return String + */ + public String getKey() { + return this.key.getKey(); + } - /** - * Get the value - * - * @return String - */ - public String getValue() { - return this.value; - } + /** + * Get the value + * + * @return String + */ + public String getValue() { + return this.value; + } - @Override - public String toString() { - if (this.value.equals("")) { - return this.key.getKey(); - } - return this.key + ":" + this.value; - } + @Override + public String toString() { + if (this.value.equals("")) { + return this.key.getKey(); + } + return this.key + ":" + this.value; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Flag other = (Flag) obj; - return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value)); - } + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Flag other = (Flag) obj; + return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value)); + } - @Override - public int hashCode() { - return this.key.getKey().hashCode(); - } + @Override + public int hashCode() { + return this.key.getKey().hashCode(); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/FlagManager.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/FlagManager.java index d6b9da38e..083cafd60 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/FlagManager.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/FlagManager.java @@ -1,146 +1,151 @@ package com.intellectualcrafters.plot; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; import java.util.Set; +import org.bukkit.entity.Player; + public class FlagManager { - // TODO add some flags - // - Plot clear interval - // - Mob cap - // - customized plot composition - // - greeting / leaving message - // OR in the flag command, allow users to set worldguard flags. + // TODO add some flags + // - Plot clear interval + // - Mob cap + // - customized plot composition + // - greeting / leaving message + // OR in the flag command, allow users to set worldguard flags. - private static ArrayList flags = new ArrayList(); + private static ArrayList flags = new ArrayList(); - /** - * Register an AbstractFlag with PlotSquared - * - * @param flag - * @return - */ - public static boolean addFlag(AbstractFlag flag) { - if (getFlag(flag.getKey()) != null) { - return false; - } - return flags.add(flag); - } + /** + * Register an AbstractFlag with PlotSquared + * + * @param flag + * @return + */ + public static boolean addFlag(final AbstractFlag flag) { + if (getFlag(flag.getKey()) != null) { + return false; + } + return flags.add(flag); + } - public static Flag[] removeFlag(Flag[] flags, String r) { - Flag[] f = new Flag[flags.length - 1]; + public static Flag[] removeFlag(final Flag[] flags, final String r) { + final Flag[] f = new Flag[flags.length - 1]; int index = 0; - for(Flag flag : flags) { - if(!flag.getKey().equals(r)) + for (final Flag flag : flags) { + if (!flag.getKey().equals(r)) { f[index++] = flag; + } } return f; } - public static Flag[] removeFlag(Set flags, String r) { - Flag[] flagArray = new Flag[flags.size() - 1]; + public static Flag[] removeFlag(final Set flags, final String r) { + final Flag[] flagArray = new Flag[flags.size() - 1]; int index = 0; - for(Flag flag : flags) { - if(!flag.getKey().equals(r)) + for (final Flag flag : flags) { + if (!flag.getKey().equals(r)) { flagArray[index++] = flag; + } } return flagArray; } - /** - * Get a list of registered AbstractFlag objects - * - * @return List (AbstractFlag) - */ - public static List getFlags() { - return flags; - } + /** + * Get a list of registered AbstractFlag objects + * + * @return List (AbstractFlag) + */ + public static List getFlags() { + return flags; + } /** * Get a list of registerd AbstragFlag objects based on player permissions - * @param player with permissions + * + * @param player + * with permissions * @return List (AbstractFlag) */ - public static List getFlags(Player player) { - List returnFlags = new ArrayList<>(); - for(AbstractFlag flag : flags) { - if(player.hasPermission("plots.set." + flag.getKey().toLowerCase())) + public static List getFlags(final Player player) { + final List returnFlags = new ArrayList<>(); + for (final AbstractFlag flag : flags) { + if (player.hasPermission("plots.set." + flag.getKey().toLowerCase())) { returnFlags.add(flag); + } } return returnFlags; } - /** - * Get an AbstractFlag by a string Returns null if flag does not exist - * - * @param string - * @return AbstractFlag - */ - public static AbstractFlag getFlag(String string) { - for (AbstractFlag flag : flags) { - if (flag.getKey().equalsIgnoreCase(string)) { - return flag; - } - } - return null; - } + /** + * Get an AbstractFlag by a string Returns null if flag does not exist + * + * @param string + * @return AbstractFlag + */ + public static AbstractFlag getFlag(final String string) { + for (final AbstractFlag flag : flags) { + if (flag.getKey().equalsIgnoreCase(string)) { + return flag; + } + } + return null; + } - /** - * Get an AbstractFlag by a string - * - * @param string - * @param create - * If to create the flag if it does not exist - * @return AbstractFlag - */ - public static AbstractFlag getFlag(String string, boolean create) { - if ((getFlag(string) == null) && create) { - AbstractFlag flag = new AbstractFlag(string); - addFlag(flag); - return flag; - } - return getFlag(string); - } + /** + * Get an AbstractFlag by a string + * + * @param string + * @param create + * If to create the flag if it does not exist + * @return AbstractFlag + */ + public static AbstractFlag getFlag(final String string, final boolean create) { + if ((getFlag(string) == null) && create) { + final AbstractFlag flag = new AbstractFlag(string); + addFlag(flag); + return flag; + } + return getFlag(string); + } - /** - * Remove a registered AbstractFlag - * - * @param flag - * @return boolean Result of operation - */ - public static boolean removeFlag(AbstractFlag flag) { - return flags.remove(flag); - } + /** + * Remove a registered AbstractFlag + * + * @param flag + * @return boolean Result of operation + */ + public static boolean removeFlag(final AbstractFlag flag) { + return flags.remove(flag); + } - public static Flag[] parseFlags(List flagstrings) { - Flag[] flags = new Flag[flagstrings.size()]; - for (int i = 0; i < flagstrings.size(); i++) { - String[] split = flagstrings.get(i).split(";"); - if (split.length == 1) { - flags[i] = new Flag(getFlag(split[0], true), ""); - } - else { - flags[i] = new Flag(getFlag(split[0], true), split[1]); - } - } - return flags; - } + public static Flag[] parseFlags(final List flagstrings) { + final Flag[] flags = new Flag[flagstrings.size()]; + for (int i = 0; i < flagstrings.size(); i++) { + final String[] split = flagstrings.get(i).split(";"); + if (split.length == 1) { + flags[i] = new Flag(getFlag(split[0], true), ""); + } + else { + flags[i] = new Flag(getFlag(split[0], true), split[1]); + } + } + return flags; + } - /** - * Get the flags for a plot - * - * @param plot - * @return List (AbstractFlag) - */ - public static List getPlotFlags(Plot plot) { - Set plotFlags = plot.settings.getFlags(); - List flags = new ArrayList<>(); - for (Flag flag : plotFlags) { - flags.add(flag.getAbstractFlag()); - } - return flags; - } + /** + * Get the flags for a plot + * + * @param plot + * @return List (AbstractFlag) + */ + public static List getPlotFlags(final Plot plot) { + final Set plotFlags = plot.settings.getFlags(); + final List flags = new ArrayList<>(); + for (final Flag flag : plotFlags) { + flags.add(flag.getAbstractFlag()); + } + return flags; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/LSetCube.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/LSetCube.java index bb560fa5e..4f4bfb537 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/LSetCube.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/LSetCube.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = LSetCube.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ @@ -17,110 +17,108 @@ import org.bukkit.Location; */ public class LSetCube { - /** - * Base locations - */ - private Location l1, l2; + /** + * Base locations + */ + private Location l1, l2; - /** - * Constructor - * - * @param l1 - * @param l2 - */ - public LSetCube(Location l1, Location l2) { - this.l1 = l1; - this.l1 = l2; - } + /** + * Constructor + * + * @param l1 + * @param l2 + */ + public LSetCube(final Location l1, final Location l2) { + this.l1 = l1; + this.l1 = l2; + } - /** - * Secondary constructor - * - * @param l1 - * @param size - */ - public LSetCube(Location l1, int size) { - this.l1 = l1; - this.l2 = l1.clone().add(size, size, size); - } + /** + * Secondary constructor + * + * @param l1 + * @param size + */ + public LSetCube(final Location l1, final int size) { + this.l1 = l1; + this.l2 = l1.clone().add(size, size, size); + } - /** - * Returns the absolute min. of the cube - * - * @return abs. min - */ - public Location minLoc() { - int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX()); - int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY()); - int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ()); - return new Location(this.l1.getWorld(), x, y, z); - } + /** + * Returns the absolute min. of the cube + * + * @return abs. min + */ + public Location minLoc() { + final int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX()); + final int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY()); + final int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ()); + return new Location(this.l1.getWorld(), x, y, z); + } - /** - * Returns the absolute max. of the cube - * - * @return abs. max - */ - public Location maxLoc() { - int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX()); - int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY()); - int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ()); - return new Location(this.l1.getWorld(), x, y, z); - } + /** + * Returns the absolute max. of the cube + * + * @return abs. max + */ + public Location maxLoc() { + final int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX()); + final int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY()); + final int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ()); + return new Location(this.l1.getWorld(), x, y, z); + } - /** - * Creates a LCycler for the cube. - * - * @return new lcycler - */ - public LCycler getCycler() { - return new LCycler(this); - } + /** + * Creates a LCycler for the cube. + * + * @return new lcycler + */ + public LCycler getCycler() { + return new LCycler(this); + } - /** - * @author Citymonstret - */ - protected class LCycler { - /** - * - */ - private Location min; - /** - * - */ - private Location max; - /** - * - */ - private Location current; + /** + * @author Citymonstret + */ + protected class LCycler { + /** + * + */ + private final Location min; + /** + * + */ + private final Location max; + /** + * + */ + private Location current; - /** - * @param cube - */ - public LCycler(LSetCube cube) { - this.min = cube.minLoc(); - this.max = cube.maxLoc(); - this.current = this.min; - } + /** + * @param cube + */ + public LCycler(final LSetCube cube) { + this.min = cube.minLoc(); + this.max = cube.maxLoc(); + this.current = this.min; + } - /** - * @return - */ - public boolean hasNext() { - return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) - && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) - && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ()); - } + /** + * @return + */ + public boolean hasNext() { + return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ()); + } - /** - * @return - */ - public Location getNext() { - if (!hasNext()) { - return null; - } - this.current = this.current.add(1, 1, 1); - return this.current; - } - } + /** + * @return + */ + public Location getNext() { + if (!hasNext()) { + return null; + } + this.current = this.current.add(1, 1, 1); + return this.current; + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Lag.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Lag.java index c84e10b28..d0494cefa 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Lag.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Lag.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Lag.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ @@ -15,79 +15,79 @@ package com.intellectualcrafters.plot; */ public class Lag implements Runnable { - /** - * Tick count - */ - public static int TC = 0; - /** - * Ticks - */ - public static long[] T = new long[600]; - /** - * something :_: - */ - @SuppressWarnings("unused") - public static long LT = 0L; + /** + * Tick count + */ + public static int TC = 0; + /** + * Ticks + */ + public static long[] T = new long[600]; + /** + * something :_: + */ + @SuppressWarnings("unused") + public static long LT = 0L; - /** - * Get the server TPS - * - * @return server tick per second - */ - public static double getTPS() { - return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100)); - } + /** + * Get the server TPS + * + * @return server tick per second + */ + public static double getTPS() { + return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100)); + } - /** - * Return the tick per second (measured in $ticks) - * - * @param ticks - * Ticks - * @return ticks per second - */ - public static double getTPS(int ticks) { - if (TC < ticks) { - return 20.0D; - } - int t = (TC - 1 - ticks) % T.length; - long e = System.currentTimeMillis() - T[t]; - return ticks / (e / 1000.0D); - } + /** + * Return the tick per second (measured in $ticks) + * + * @param ticks + * Ticks + * @return ticks per second + */ + public static double getTPS(final int ticks) { + if (TC < ticks) { + return 20.0D; + } + final int t = (TC - 1 - ticks) % T.length; + final long e = System.currentTimeMillis() - T[t]; + return ticks / (e / 1000.0D); + } - /** - * Get number of ticks since - * - * @param tI - * Ticks < - * @return number of ticks since $tI - */ - @SuppressWarnings("unused") - public static long getElapsed(int tI) { - long t = T[tI % T.length]; - return System.currentTimeMillis() - t; - } + /** + * Get number of ticks since + * + * @param tI + * Ticks < + * @return number of ticks since $tI + */ + @SuppressWarnings("unused") + public static long getElapsed(final int tI) { + final long t = T[tI % T.length]; + return System.currentTimeMillis() - t; + } - @Override - public void run() { - T[TC % T.length] = System.currentTimeMillis(); - TC++; - } + @Override + public void run() { + T[TC % T.length] = System.currentTimeMillis(); + TC++; + } - /** - * Get lag percentage - * - * @return lag percentage - */ - public static double getPercentage() { - return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D); - } + /** + * Get lag percentage + * + * @return lag percentage + */ + public static double getPercentage() { + return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D); + } - /** - * Get TPS percentage (of 20) - * - * @return TPS percentage - */ - public static double getFullPercentage() { - return getTPS() * 5.0D; - } + /** + * Get TPS percentage (of 20) + * + * @return TPS percentage + */ + public static double getFullPercentage() { + return getTPS() * 5.0D; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Logger.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Logger.java index 67c7b0872..2e7c3c2fe 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Logger.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Logger.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Logger.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ @@ -23,54 +23,54 @@ import java.util.Date; */ public class Logger { - private static ArrayList entries; - private static File log; + private static ArrayList entries; + private static File log; - public static void setup(File file) { - log = file; - entries = new ArrayList<>(); - try { - BufferedReader reader = new BufferedReader(new FileReader(file)); - String line; - while ((line = reader.readLine()) != null) { - entries.add(line); - } - reader.close(); - } - catch (IOException e) { - PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup"); - } - } + public static void setup(final File file) { + log = file; + entries = new ArrayList<>(); + try { + final BufferedReader reader = new BufferedReader(new FileReader(file)); + String line; + while ((line = reader.readLine()) != null) { + entries.add(line); + } + reader.close(); + } + catch (final IOException e) { + PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup"); + } + } - public enum LogLevel { - GENERAL("General"), - WARNING("Warning"), - DANGER("Danger"); - private String name; + public enum LogLevel { + GENERAL("General"), + WARNING("Warning"), + DANGER("Danger"); + private final String name; - LogLevel(String name) { - this.name = name; - } + LogLevel(final String name) { + this.name = name; + } - @Override - public String toString() { - return this.name; - } - } + @Override + public String toString() { + return this.name; + } + } - public static void write() throws IOException { - FileWriter writer = new FileWriter(log); - for (String string : entries) { - writer.write(string + System.lineSeparator()); - } - writer.close(); - } + public static void write() throws IOException { + final FileWriter writer = new FileWriter(log); + for (final String string : entries) { + writer.write(string + System.lineSeparator()); + } + writer.close(); + } - public static void add(LogLevel level, String string) { - append("[" + level.toString() + "] " + string); - } + public static void add(final LogLevel level, final String string) { + append("[" + level.toString() + "] " + string); + } - private static void append(String string) { - entries.add("[" + new Date().toString() + "]" + string); - } + private static void append(final String string) { + entries.add("[" + new Date().toString() + "]" + string); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Metrics.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Metrics.java index b04f91076..da8da5505 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Metrics.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Metrics.java @@ -2,17 +2,17 @@ package com.intellectualcrafters.plot; /* * Copyright 2011-2013 Tyler Blair. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -23,12 +23,34 @@ package com.intellectualcrafters.plot; * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are * those of the authors and contributors and should not be interpreted as * representing official policies, either expressed or implied, of anybody else. */ +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + import org.bukkit.Bukkit; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -37,704 +59,696 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.scheduler.BukkitTask; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.*; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - public class Metrics { - /** - * The current revision number - */ - private final static int REVISION = 7; - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - /** - * The plugin configuration file - */ - private final File configurationFile; - /** - * Unique server id - */ - private final String guid; - /** - * Debug mode - */ - private final boolean debug; - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - /** - * The scheduled task - */ - private volatile BukkitTask task = null; + /** + * The current revision number + */ + private final static int REVISION = 7; + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://report.mcstats.org"; + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/plugin/%s"; + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 15; + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + /** + * All of the custom graphs to submit to metrics + */ + private final Set graphs = Collections.synchronizedSet(new HashSet()); + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + /** + * The plugin configuration file + */ + private final File configurationFile; + /** + * Unique server id + */ + private final String guid; + /** + * Debug mode + */ + private final boolean debug; + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + /** + * 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"); - } - this.plugin = plugin; - // load the config - this.configurationFile = getConfigFile(); - this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile); - // add some defaults - this.configuration.addDefault("opt-out", false); - this.configuration.addDefault("guid", UUID.randomUUID().toString()); - this.configuration.addDefault("debug", false); - // Do we need to create the file? - if (this.configuration.get("guid", null) == null) { - this.configuration.options().header("http://mcstats.org").copyDefaults(true); - this.configuration.save(this.configurationFile); - } - // Load the guid then - this.guid = this.configuration.getString("guid"); - this.debug = this.configuration.getBoolean("debug", false); - } + public Metrics(final Plugin plugin) throws IOException { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + this.plugin = plugin; + // load the config + this.configurationFile = getConfigFile(); + this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile); + // add some defaults + this.configuration.addDefault("opt-out", false); + this.configuration.addDefault("guid", UUID.randomUUID().toString()); + this.configuration.addDefault("debug", false); + // Do we need to create the file? + if (this.configuration.get("guid", null) == null) { + this.configuration.options().header("http://mcstats.org").copyDefaults(true); + this.configuration.save(this.configurationFile); + } + // Load the guid then + this.guid = this.configuration.getString("guid"); + this.debug = this.configuration.getBoolean("debug", false); + } - /** - * 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. - * - * @param name - * The name of the graph - * @return Graph object created. Will never return NULL under normal - * circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - // Construct the graph object - final Graph graph = new Graph(name); - // Now we can add our graph - this.graphs.add(graph); - // and return back - return graph; - } + /** + * 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. + * + * @param name + * The name of the graph + * @return Graph object created. Will never return NULL under normal + * circumstances unless bad parameters are given + */ + public Graph createGraph(final String name) { + if (name == null) { + throw new IllegalArgumentException("Graph name cannot be null"); + } + // Construct the graph object + final Graph graph = new Graph(name); + // Now we can add our graph + this.graphs.add(graph); + // and return back + return graph; + } - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin - * that should be sent to the backend - * - * @param graph - * The name of the graph - */ - public void addGraph(final Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - this.graphs.add(graph); - } + /** + * Add a Graph object to BukkitMetrics that represents data for the plugin + * that should be sent to the backend + * + * @param graph + * The name of the graph + */ + public void addGraph(final Graph graph) { + if (graph == null) { + throw new IllegalArgumentException("Graph cannot be null"); + } + this.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 ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - synchronized (this.optOutLock) { - // Did we opt out? - if (isOptOut()) { - return false; - } - // Is metrics already running? - if (this.task != null) { - return true; - } - // Begin hitting the server with glorious data - this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { - private boolean firstPost = true; + /** + * 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 ticks. + * + * @return True if statistics measuring is running, otherwise false. + */ + public boolean start() { + synchronized (this.optOutLock) { + // Did we opt out? + if (isOptOut()) { + return false; + } + // Is metrics already running? + if (this.task != null) { + return true; + } + // Begin hitting the server with glorious data + this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { + private boolean firstPost = true; - @Override - public void run() { - try { - // This has to be synchronized or it can collide - // with - // the disable method. - synchronized (Metrics.this.optOutLock) { - // Disable Task, if it is running and the - // server - // owner decided to opt-out - if (isOptOut() && (Metrics.this.task != null)) { - Metrics.this.task.cancel(); - Metrics.this.task = null; - // Tell all plotters to stop gathering - // information. - for (Graph graph : Metrics.this.graphs) { - graph.onOptOut(); - } - } - } - // We use the inverse of firstPost because if it - // is the - // first time we are posting, - // it is not a interval ping, so it evaluates to - // FALSE - // Each time thereafter it will evaluate to - // TRUE, i.e - // PING! - postPlugin(!this.firstPost); - // After the first post we set firstPost to - // false - // Each post thereafter will be a ping - this.firstPost = false; - } - catch (IOException e) { - if (Metrics.this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - return true; - } - } + @Override + public void run() { + try { + // This has to be synchronized or it can collide + // with + // the disable method. + synchronized (Metrics.this.optOutLock) { + // Disable Task, if it is running and the + // server + // owner decided to opt-out + if (isOptOut() && (Metrics.this.task != null)) { + Metrics.this.task.cancel(); + Metrics.this.task = null; + // Tell all plotters to stop gathering + // information. + for (final Graph graph : Metrics.this.graphs) { + graph.onOptOut(); + } + } + } + // We use the inverse of firstPost because if it + // is the + // first time we are posting, + // it is not a interval ping, so it evaluates to + // FALSE + // Each time thereafter it will evaluate to + // TRUE, i.e + // PING! + postPlugin(!this.firstPost); + // After the first post we set firstPost to + // false + // Each post thereafter will be a ping + this.firstPost = false; + } + catch (final IOException e) { + if (Metrics.this.debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); + } + } + } + }, 0, PING_INTERVAL * 1200); + return true; + } + } - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() { - synchronized (this.optOutLock) { - try { - // Reload the metrics file - this.configuration.load(getConfigFile()); - } - catch (IOException ex) { - if (this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - catch (InvalidConfigurationException ex) { - if (this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return this.configuration.getBoolean("opt-out", false); - } - } + /** + * Has the server owner denied plugin metrics? + * + * @return true if metrics should be opted out of it + */ + public boolean isOptOut() { + synchronized (this.optOutLock) { + try { + // Reload the metrics file + this.configuration.load(getConfigFile()); + } + catch (final IOException ex) { + if (this.debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } + catch (final InvalidConfigurationException ex) { + if (this.debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } + return this.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. - * - * @throws java.io.IOException - */ - public void enable() throws IOException { - // This has to be synchronized or it can collide with the check in the - // task. - synchronized (this.optOutLock) { - // Check if the server owner has already set opt-out, if not, set - // it. - if (isOptOut()) { - this.configuration.set("opt-out", false); - this.configuration.save(this.configurationFile); - } - // Enable Task, if it is not running - if (this.task == null) { - start(); - } - } - } + /** + * Enables metrics for the server by setting "opt-out" to false in the + * config file and starting the metrics task. + * + * @throws java.io.IOException + */ + public void enable() throws IOException { + // This has to be synchronized or it can collide with the check in the + // task. + synchronized (this.optOutLock) { + // Check if the server owner has already set opt-out, if not, set + // it. + if (isOptOut()) { + this.configuration.set("opt-out", false); + this.configuration.save(this.configurationFile); + } + // Enable Task, if it is not running + if (this.task == null) { + start(); + } + } + } - /** - * Disables metrics for the server by setting "opt-out" to true in the - * config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException { - // This has to be synchronized or it can collide with the check in the - // task. - synchronized (this.optOutLock) { - // Check if the server owner has already set opt-out, if not, set - // it. - if (!isOptOut()) { - this.configuration.set("opt-out", true); - this.configuration.save(this.configurationFile); - } - // Disable Task, if it is running - if (this.task != null) { - this.task.cancel(); - this.task = null; - } - } - } + /** + * Disables metrics for the server by setting "opt-out" to true in the + * config file and canceling the metrics task. + * + * @throws java.io.IOException + */ + public void disable() throws IOException { + // This has to be synchronized or it can collide with the check in the + // task. + synchronized (this.optOutLock) { + // Check if the server owner has already set opt-out, if not, set + // it. + if (!isOptOut()) { + this.configuration.set("opt-out", true); + this.configuration.save(this.configurationFile); + } + // Disable Task, if it is running + if (this.task != null) { + this.task.cancel(); + this.task = null; + } + } + } - /** - * Gets the File object of the config file that should be used to store data - * such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set - // via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = this.plugin.getDataFolder().getParentFile(); - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } + /** + * Gets the File object of the config file that should be used to store data + * such as the GUID and opt-out status + * + * @return the File object for the config file + */ + public File getConfigFile() { + // I believe the easiest way to get the base folder (e.g craftbukkit set + // via -P) for plugins to use + // is to abuse the plugin object we already have + // plugin.getDataFolder() => base/plugins/PluginA/ + // pluginsFolder => base/plugins/ + // The base is not necessarily relative to the startup directory. + final File pluginsFolder = this.plugin.getDataFolder().getParentFile(); + // 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 - */ - private void postPlugin(final boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = this.plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if - // online - // mode - // is - // enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - 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(); - else - playersOnline = ((Player[])Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null, new Object[0])).length; - } - catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex){} + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException { + // Server software specific section + final PluginDescriptionFile description = this.plugin.getDescription(); + final String pluginName = description.getName(); + final boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE + // if + // online + // mode + // is + // enabled + final String pluginVersion = description.getVersion(); + final String serverVersion = Bukkit.getVersion(); + 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(); + } + else { + playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null, new Object[0])).length; + } + } + 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 - StringBuilder json = new StringBuilder(1024); - json.append('{'); - // The plugin's description file containg all of the plugin data such as - // name, version, author, etc - appendJSONPair(json, "guid", this.guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } - if (this.graphs.size() > 0) { - synchronized (this.graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - boolean firstGraph = true; - final Iterator iter = this.graphs.iterator(); - while (iter.hasNext()) { - Graph graph = iter.next(); - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - graphJson.append('}'); - if (!firstGraph) { - json.append(','); - } - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - firstGraph = false; - } - json.append('}'); - } - } - // close json - json.append('}'); - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - // Connect to the website - URLConnection connection; - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } - else { - connection = url.openConnection(); - } - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.setDoOutput(true); - if (this.debug) { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length - + " compressed=" + compressed.length); - } - // Write the data - 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")) { - if (response == null) { - response = "null"; - } - else - if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - 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")) { - synchronized (this.graphs) { - final Iterator iter = this.graphs.iterator(); - while (iter.hasNext()) { - final Graph graph = iter.next(); - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } + // END server software specific section -- all code below does not use + // any code outside of this class / Java + // Construct the post data + final StringBuilder json = new StringBuilder(1024); + json.append('{'); + // The plugin's description file containg all of the plugin data such as + // name, version, author, etc + appendJSONPair(json, "guid", this.guid); + appendJSONPair(json, "plugin_version", pluginVersion); + appendJSONPair(json, "server_version", serverVersion); + appendJSONPair(json, "players_online", Integer.toString(playersOnline)); + // New data as of R6 + final String osname = System.getProperty("os.name"); + String osarch = System.getProperty("os.arch"); + final String osversion = System.getProperty("os.version"); + final String java_version = System.getProperty("java.version"); + final int coreCount = Runtime.getRuntime().availableProcessors(); + // normalize os arch .. amd64 -> x86_64 + if (osarch.equals("amd64")) { + osarch = "x86_64"; + } + appendJSONPair(json, "osname", osname); + appendJSONPair(json, "osarch", osarch); + appendJSONPair(json, "osversion", osversion); + appendJSONPair(json, "cores", Integer.toString(coreCount)); + appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); + appendJSONPair(json, "java_version", java_version); + // If we're pinging, append it + if (isPing) { + appendJSONPair(json, "ping", "1"); + } + if (this.graphs.size() > 0) { + synchronized (this.graphs) { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); + boolean firstGraph = true; + final Iterator iter = this.graphs.iterator(); + while (iter.hasNext()) { + final Graph graph = iter.next(); + final StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + for (final Plotter plotter : graph.getPlotters()) { + appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); + } + graphJson.append('}'); + if (!firstGraph) { + json.append(','); + } + json.append(escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + firstGraph = false; + } + json.append('}'); + } + } + // close json + json.append('}'); + // Create the url + final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); + // Connect to the website + URLConnection connection; + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (isMineshafterPresent()) { + connection = url.openConnection(Proxy.NO_PROXY); + } + else { + connection = url.openConnection(); + } + final byte[] uncompressed = json.toString().getBytes(); + final byte[] compressed = gzip(json.toString()); + // Headers + connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); + connection.addRequestProperty("Content-Type", "application/json"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.setDoOutput(true); + if (this.debug) { + System.out.println("[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")) { + if (response == null) { + response = "null"; + } + else if (response.startsWith("7")) { + response = response.substring(response.startsWith("7,") ? 2 : 1); + } + 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")) { + synchronized (this.graphs) { + final Iterator iter = this.graphs.iterator(); + while (iter.hasNext()) { + final Graph graph = iter.next(); + for (final Plotter plotter : graph.getPlotters()) { + plotter.reset(); + } + } + } + } + } + } - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } - catch (IOException e) { - e.printStackTrace(); - } - finally { - if (gzos != null) { - try { - gzos.close(); - } - catch (IOException ignore) { - } - } - } - return baos.toByteArray(); - } + /** + * 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 - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } - catch (Exception e) { - return false; - } - } + /** + * Check if mineshafter is present. If it is, we need to bypass it to send + * POST requests + * + * @return true if mineshafter is installed on the server + */ + private boolean isMineshafterPresent() { + try { + Class.forName("mineshafter.MineServer"); + return true; + } + catch (final Exception e) { + return false; + } + } - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { - boolean isValueNumeric = false; - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } - catch (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)); - } - } + /** + * Appends a json encoded key/value pair to the given string builder. + * + * @param json + * @param key + * @param value + * @throws 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(String text) { - StringBuilder builder = new StringBuilder(); - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - 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 < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } - else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - return builder.toString(); - } + /** + * 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"); - } + /** + * 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"); + } - /** - * 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 - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); + /** + * 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 + */ + private final String name; + /** + * The set of plotters that are contained within this graph + */ + private final Set plotters = new LinkedHashSet(); - private Graph(final String name) { - this.name = name; - } + private Graph(final String name) { + this.name = name; + } - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return this.name; - } + /** + * Gets the graph's name + * + * @return the Graph's name + */ + public String getName() { + return this.name; + } - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter - * the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) { - this.plotters.add(plotter); - } + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter + * the plotter to add to the graph + */ + public void addPlotter(final Plotter plotter) { + this.plotters.add(plotter); + } - /** - * Remove a plotter from the graph - * - * @param plotter - * the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) { - this.plotters.remove(plotter); - } + /** + * Remove a plotter from the graph + * + * @param plotter + * the plotter to remove from the graph + */ + public void removePlotter(final Plotter plotter) { + this.plotters.remove(plotter); + } - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(this.plotters); - } + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return an unmodifiable {@link java.util.Set} of the plotter objects + */ + public Set getPlotters() { + return Collections.unmodifiableSet(this.plotters); + } - @Override - public int hashCode() { - return this.name.hashCode(); - } + @Override + public int hashCode() { + return this.name.hashCode(); + } - @Override - public boolean equals(final Object object) { - if (!(object instanceof Graph)) { - return false; - } - final Graph graph = (Graph) object; - return graph.name.equals(this.name); - } + @Override + public boolean equals(final Object object) { + if (!(object instanceof Graph)) { + return false; + } + final Graph graph = (Graph) object; + return graph.name.equals(this.name); + } - /** - * Called when the server owner decides to opt-out of BukkitMetrics - * while the server is running. - */ - protected void onOptOut() { - } - } + /** + * Called when the server owner decides to opt-out of BukkitMetrics + * while the server is running. + */ + 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; + /** + * 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 the default plot name + */ + public Plotter() { + this("Default"); + } - /** - * Construct a plotter with a specific plot name - * - * @param name - * the name of the plotter to use, which will show up on the - * website - */ - public Plotter(final String name) { - this.name = name; - } + /** + * Construct a plotter with a specific plot name + * + * @param name + * the name of the plotter to use, which will show up on the + * website + */ + 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 from any thread so care should be taken when - * accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); + /** + * 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 from any thread so care should be taken when + * accessing resources that need to be synchronized. + * + * @return the current value for the point to be plotted. + */ + public abstract int getValue(); - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return this.name; - } + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() { + return this.name; + } - /** - * Called after the website graphs have been updated - */ - public void reset() { - } + /** + * Called after the website graphs have been updated + */ + public void reset() { + } - @Override - public int hashCode() { - return getColumnName().hashCode(); - } + @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(this.name) && (plotter.getValue() == getValue()); - } - } + @Override + public boolean equals(final Object object) { + if (!(object instanceof Plotter)) { + return false; + } + final Plotter plotter = (Plotter) object; + return plotter.name.equals(this.name) && (plotter.getValue() == getValue()); + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PWE.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PWE.java index 3645fe1e5..2a0039340 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PWE.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PWE.java @@ -20,104 +20,102 @@ import com.sk89q.worldedit.regions.CuboidRegion; public class PWE { @SuppressWarnings("deprecation") - public static void setMask(Player p, Location l) { - try { - LocalSession s; - if (PlotMain.worldEdit == null) { - s = WorldEdit.getInstance().getSession(p.getName()); - } - else { - s = PlotMain.worldEdit.getSession(p); - } - - PlotId id = PlayerFunctions.getPlot(l); - if (id != null) { - Plot plot = PlotMain.getPlots(l.getWorld()).get(id); - if (plot != null) { - boolean r; - r = - (plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId()) - || plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()); - if (!r) { - if (p.hasPermission("plots.worldedit.bypass")) { - removeMask(p, s); - return; - } - } - else { - - World w = p.getWorld(); - - Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id); - Location tloc = PlotHelper.getPlotTopLoc(w, plot.id); - - Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1); - Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ()); - - LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld(); - - CuboidRegion region = new CuboidRegion(lw, bvec, tvec); - RegionMask mask = new RegionMask(region); - s.setMask(mask); - return; - } - } - } - if (noMask(s)) { - BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); - Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); - s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); - } - } - catch (Exception e) { - // throw new - // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, - // "WorldEdit == Null?"); - } - } - - public static boolean noMask(LocalSession s) { - return s.getMask() == null; - } - - public static void setNoMask(Player p) { - try { - LocalSession s; + public static void setMask(final Player p, final Location l) { + try { + LocalSession s; if (PlotMain.worldEdit == null) { s = WorldEdit.getInstance().getSession(p.getName()); } else { s = PlotMain.worldEdit.getSession(p); } - BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); - Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); - s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); - } - catch (Exception e) { - - } - } - - public static void removeMask(Player p, LocalSession s) { - Mask mask = null; - s.setMask(mask); - } - public static void removeMask(Player p) { - try { - LocalSession s; - if (PlotMain.worldEdit == null) { - s = WorldEdit.getInstance().getSession(p.getName()); - } - else { - s = PlotMain.worldEdit.getSession(p); - } - removeMask(p, s); - } - catch (Exception e) { - // throw new - // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, - // "WorldEdit == Null?"); - } - } + final PlotId id = PlayerFunctions.getPlot(l); + if (id != null) { + final Plot plot = PlotMain.getPlots(l.getWorld()).get(id); + if (plot != null) { + boolean r; + r = ((plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId())) || plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()); + if (!r) { + if (p.hasPermission("plots.worldedit.bypass")) { + removeMask(p, s); + return; + } + } + else { + + final World w = p.getWorld(); + + final Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id); + final Location tloc = PlotHelper.getPlotTopLoc(w, plot.id); + + final Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1); + final Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ()); + + final LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld(); + + final CuboidRegion region = new CuboidRegion(lw, bvec, tvec); + final RegionMask mask = new RegionMask(region); + s.setMask(mask); + return; + } + } + } + if (noMask(s)) { + final BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); + final Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); + s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); + } + } + catch (final Exception e) { + // throw new + // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, + // "WorldEdit == Null?"); + } + } + + public static boolean noMask(final LocalSession s) { + return s.getMask() == null; + } + + public static void setNoMask(final Player p) { + try { + LocalSession s; + if (PlotMain.worldEdit == null) { + s = WorldEdit.getInstance().getSession(p.getName()); + } + else { + s = PlotMain.worldEdit.getSession(p); + } + final BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); + final Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); + s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); + } + catch (final Exception e) { + + } + } + + public static void removeMask(final Player p, final LocalSession s) { + final Mask mask = null; + s.setMask(mask); + } + + public static void removeMask(final Player p) { + try { + LocalSession s; + if (PlotMain.worldEdit == null) { + s = WorldEdit.getInstance().getSession(p.getName()); + } + else { + s = PlotMain.worldEdit.getSession(p); + } + removeMask(p, s); + } + catch (final Exception e) { + // throw new + // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, + // "WorldEdit == Null?"); + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlayerFunctions.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlayerFunctions.java index 5bfe23be8..2dbded55f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlayerFunctions.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlayerFunctions.java @@ -2,19 +2,27 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerFunctions.java >> Generated by: Citymonstret at 2014-08-09 * 01:43 */ package com.intellectualcrafters.plot; -import org.bukkit.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.entity.Player; -import java.util.*; - /** * Functions involving players, plots and locations. * @@ -23,29 +31,29 @@ import java.util.*; @SuppressWarnings("javadoc") public class PlayerFunctions { - /** - * @param player - * player - * @return - */ - public static boolean isInPlot(Player player) { - return getCurrentPlot(player) != null; - } + /** + * @param player + * player + * @return + */ + public static boolean isInPlot(final Player player) { + return getCurrentPlot(player) != null; + } - /** - * @param plot - * plot - * @return - */ - public static boolean hasExpired(Plot plot) { - OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner); - long lp = player.getLastPlayed(); - long cu = System.currentTimeMillis(); - return (lp - cu) > 30l; - } + /** + * @param plot + * plot + * @return + */ + public static boolean hasExpired(final Plot plot) { + final OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner); + final long lp = player.getLastPlayed(); + final long cu = System.currentTimeMillis(); + return (lp - cu) > 30l; + } - public static ArrayList getPlotSelectionIds(World world, PlotId pos1, PlotId pos2) { - ArrayList myplots = new ArrayList(); + public static ArrayList getPlotSelectionIds(final World world, final PlotId pos1, final PlotId pos2) { + final ArrayList myplots = new ArrayList(); for (int x = pos1.x; x <= pos2.x; x++) { for (int y = pos1.y; y <= pos2.y; y++) { myplots.add(new PlotId(x, y)); @@ -53,21 +61,21 @@ public class PlayerFunctions { } return myplots; } - - public static ArrayList getMaxPlotSelectionIds(World world, PlotId pos1, PlotId pos2) { - - Plot plot1 = PlotMain.getPlots(world).get(pos1); - Plot plot2 = PlotMain.getPlots(world).get(pos2); - - if (plot1 != null) { + + public static ArrayList getMaxPlotSelectionIds(final World world, PlotId pos1, PlotId pos2) { + + final Plot plot1 = PlotMain.getPlots(world).get(pos1); + final Plot plot2 = PlotMain.getPlots(world).get(pos2); + + if (plot1 != null) { pos1 = getBottomPlot(world, plot1).id; } - - if (plot2 != null) { + + if (plot2 != null) { pos2 = getTopPlot(world, plot2).id; } - - ArrayList myplots = new ArrayList(); + + final ArrayList myplots = new ArrayList(); for (int x = pos1.x; x <= pos2.x; x++) { for (int y = pos1.y; y <= pos2.y; y++) { myplots.add(new PlotId(x, y)); @@ -76,205 +84,211 @@ public class PlayerFunctions { return myplots; } - public static Plot getBottomPlot(World world, Plot plot) { - if (plot.settings.getMerged(0)) { - Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1)); - if (p==null) { - return plot; - } - return getBottomPlot(world, p); - } - if (plot.settings.getMerged(3)) { - Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y)); - if (p==null) { + public static Plot getBottomPlot(final World world, final Plot plot) { + if (plot.settings.getMerged(0)) { + final Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1)); + if (p == null) { return plot; } - return getBottomPlot(world, p); - } - return plot; - } + return getBottomPlot(world, p); + } + if (plot.settings.getMerged(3)) { + final Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y)); + if (p == null) { + return plot; + } + return getBottomPlot(world, p); + } + return plot; + } - public static Plot getTopPlot(World world, Plot plot) { - if (plot.settings.getMerged(2)) { - return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1))); - } - if (plot.settings.getMerged(1)) { - return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x + 1, plot.id.y))); - } - return plot; - } + public static Plot getTopPlot(final World world, final Plot plot) { + if (plot.settings.getMerged(2)) { + return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1))); + } + if (plot.settings.getMerged(1)) { + return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x + 1, plot.id.y))); + } + return plot; + } - /** - * Returns the plot at a location (mega plots are not considered, all plots are treated as small plots) - * @param loc - * @return - */ - public static PlotId getPlotAbs(Location loc) { - String world = loc.getWorld().getName(); - PlotManager manager = PlotMain.getPlotManager(world); - if (manager == null) { - return null; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - return manager.getPlotIdAbs(plotworld, loc); - } + /** + * Returns the plot at a location (mega plots are not considered, all plots + * are treated as small plots) + * + * @param loc + * @return + */ + public static PlotId getPlotAbs(final Location loc) { + final String world = loc.getWorld().getName(); + final PlotManager manager = PlotMain.getPlotManager(world); + if (manager == null) { + return null; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + return manager.getPlotIdAbs(plotworld, loc); + } - /** - * Returns the plot id at a location (mega plots are considered) - * @param loc - * @return - */ - public static PlotId getPlot(Location loc) { - String world = loc.getWorld().getName(); - PlotManager manager = PlotMain.getPlotManager(world); - if (manager == null) { - return null; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - return manager.getPlotId(plotworld, loc); - } + /** + * Returns the plot id at a location (mega plots are considered) + * + * @param loc + * @return + */ + public static PlotId getPlot(final Location loc) { + final String world = loc.getWorld().getName(); + final PlotManager manager = PlotMain.getPlotManager(world); + if (manager == null) { + return null; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + return manager.getPlotId(plotworld, loc); + } + /** + * Returns the plot a player is currently in. + * + * @param player + * @return + */ + public static Plot getCurrentPlot(final Player player) { + if (!PlotMain.isPlotWorld(player.getWorld())) { + return null; + } + final PlotId id = getPlot(player.getLocation()); + final World world = player.getWorld(); + if (id == null) { + return null; + } + final HashMap plots = PlotMain.getPlots(world); + if (plots != null) { + if (plots.containsKey(id)) { + return plots.get(id); + } + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), world.getName()); + } - /** - * Returns the plot a player is currently in. - * @param player - * @return - */ - public static Plot getCurrentPlot(Player player) { - if (!PlotMain.isPlotWorld(player.getWorld())) { - return null; - } - PlotId id = getPlot(player.getLocation()); - World world = player.getWorld(); - if (id == null) { - return null; - } - HashMap plots = PlotMain.getPlots(world); - if (plots != null) { - if (plots.containsKey(id)) { - return plots.get(id); - } - } - return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), world.getName()); + /** + * Updates a given plot with another instance + * + * @deprecated + * + * @param plot + */ + @Deprecated + public static void set(final Plot plot) { + PlotMain.updatePlot(plot); + } - } + /** + * Get the plots for a player + * + * @param plr + * @return + */ + public static Set getPlayerPlots(final World world, final Player plr) { + final Set p = PlotMain.getPlots(world, plr); + if (p == null) { + return new HashSet(); + } + return p; + } - /** - * Updates a given plot with another instance - * @deprecated + /** + * Get the number of plots for a player + * + * @param plr + * @return + */ + public static int getPlayerPlotCount(final World world, final Player plr) { + final UUID uuid = plr.getUniqueId(); + int count = 0; + for (final Plot plot : PlotMain.getPlots(world).values()) { + if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) { + count++; + } + } + return count; + } - * @param plot - */ - @Deprecated - public static void set(Plot plot) { - PlotMain.updatePlot(plot); - } + /** + * Get the maximum number of plots a player is allowed + * + * @param p + * @return + */ + @SuppressWarnings("SuspiciousNameCombination") + public static int getAllowedPlots(final Player p) { + return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); + } - /** - * Get the plots for a player - * @param plr - * @return - */ - public static Set getPlayerPlots(World world, Player plr) { - Set p = PlotMain.getPlots(world, plr); - if (p == null) { - return new HashSet(); - } - return p; - } + /** + * @return PlotMain.getPlots(); + * @deprecated + */ + @Deprecated + public static Set getPlots() { + return PlotMain.getPlots(); + } - /** - * Get the number of plots for a player - * @param plr - * @return - */ - public static int getPlayerPlotCount(World world, Player plr) { - UUID uuid = plr.getUniqueId(); - int count = 0; - for (Plot plot: PlotMain.getPlots(world).values()) { - if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) { - count++; - } - } - return count; - } + /** + * \\previous\\ + * + * @param plr + * @param msg + * Was used to wrap the chat client length (Packets out--) + */ + public static void sendMessageWrapped(final Player plr, final String msg) { + plr.sendMessage(msg); + } - /** - * Get the maximum number of plots a player is allowed - * @param p - * @return - */ - @SuppressWarnings("SuspiciousNameCombination") - public static int getAllowedPlots(Player p) { - return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); - } + /** + * Send a message to the player + * + * @param plr + * Player to recieve message + * @param msg + * Message to send + */ + public static void sendMessage(final Player plr, final String msg) { + if ((msg.length() == 0) || msg.equalsIgnoreCase("")) { + return; + } - /** - * @return PlotMain.getPlots(); - * @deprecated - */ - @Deprecated - public static Set getPlots() { - return PlotMain.getPlots(); - } + if (plr == null) { + PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg); + return; + } - /** - * \\previous\\ - * - * @param plr - * @param msg - * Was used to wrap the chat client length (Packets out--) - */ - public static void sendMessageWrapped(Player plr, String msg) { - plr.sendMessage(msg); - } + sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); + } - /** - * Send a message to the player - * - * @param plr - * Player to recieve message - * @param msg - * Message to send - */ - public static void sendMessage(Player plr, String msg) { - if ((msg.length() == 0) || msg.equalsIgnoreCase("")) { - return; - } - - if (plr==null) { - PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg); - return; - } - - sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); - } + /** + * Send a message to the player + * + * @param plr + * Player to recieve message + * @param c + * Caption to send + */ + public static void sendMessage(final Player plr, final C c, final String... args) { - /** - * Send a message to the player - * - * @param plr - * Player to recieve message - * @param c - * Caption to send - */ - public static void sendMessage(Player plr, C c, String... args) { - - if (plr==null) { - PlotMain.sendConsoleSenderMessage(c); - return; - } - - if (c.s().length() < 1) { - return; - } - String msg = c.s(); - if ((args != null) && (args.length > 0)) { - for (String str : args) { - msg = msg.replaceFirst("%s", str); - } - } - sendMessage(plr, msg); - } + if (plr == null) { + PlotMain.sendConsoleSenderMessage(c); + return; + } + + if (c.s().length() < 1) { + return; + } + String msg = c.s(); + if ((args != null) && (args.length > 0)) { + for (final String str : args) { + msg = msg.replaceFirst("%s", str); + } + } + sendMessage(plr, msg); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Plot.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Plot.java index f4a5af227..ffae6bb9f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Plot.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Plot.java @@ -2,20 +2,21 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Plot.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.database.DBFunc; +import java.util.ArrayList; +import java.util.UUID; + import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.UUID; +import com.intellectualcrafters.plot.database.DBFunc; /** * The plot class @@ -25,262 +26,255 @@ import java.util.UUID; @SuppressWarnings("javadoc") public class Plot implements Cloneable { - /** - * plot ID - */ - public PlotId id; - /** - * plot world - */ - public String world; - /** - * plot owner - */ - public UUID owner; - /** - * Deny Entry - */ - public boolean deny_entry; - /** - * List of helpers (with plot permissions) - */ - public ArrayList helpers; - /** - * List of trusted users (with plot permissions) - */ - public ArrayList trusted; - /** - * List of denied players - */ - public ArrayList denied; - /** - * External settings class - */ - public PlotSettings settings; - /** - * Delete on next save cycle? - */ - public boolean delete; - /** - * Has the plot changed since the last save cycle? - */ - public boolean hasChanged = false; - public boolean countsTowardsMax = true ; + /** + * plot ID + */ + public PlotId id; + /** + * plot world + */ + public String world; + /** + * plot owner + */ + public UUID owner; + /** + * Deny Entry + */ + public boolean deny_entry; + /** + * List of helpers (with plot permissions) + */ + public ArrayList helpers; + /** + * List of trusted users (with plot permissions) + */ + public ArrayList trusted; + /** + * List of denied players + */ + public ArrayList denied; + /** + * External settings class + */ + public PlotSettings settings; + /** + * Delete on next save cycle? + */ + public boolean delete; + /** + * Has the plot changed since the last save cycle? + */ + public boolean hasChanged = false; + public boolean countsTowardsMax = true; - /** - * Primary constructor - * - * @param id - * @param owner - * @param plotBiome - * @param helpers - * @param denied - */ - public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList helpers, ArrayList denied, String world) { - this.id = id; - this.settings = new PlotSettings(this); - this.settings.setBiome(plotBiome); - this.owner = owner; - this.deny_entry = this.owner == null; - this.helpers = helpers; - this.denied = denied; - this.trusted = new ArrayList(); - this.settings.setAlias(""); - this.settings.setPosition(PlotHomePosition.DEFAULT); - this.delete = false; - this.settings.setFlags(new Flag[0]); - this.world = world; - } + /** + * Primary constructor + * + * @param id + * @param owner + * @param plotBiome + * @param helpers + * @param denied + */ + public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList helpers, final ArrayList denied, final String world) { + this.id = id; + this.settings = new PlotSettings(this); + this.settings.setBiome(plotBiome); + this.owner = owner; + this.deny_entry = this.owner == null; + this.helpers = helpers; + this.denied = denied; + this.trusted = new ArrayList(); + this.settings.setAlias(""); + this.settings.setPosition(PlotHomePosition.DEFAULT); + this.delete = false; + this.settings.setFlags(new Flag[0]); + this.world = world; + } - /** - * Constructor for saved plots - * - * @param id - * @param owner - * @param plotBiome - * @param helpers - * @param denied - * @param changeTime - * @param time - * @param merged - */ - public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList helpers, ArrayList trusted, - ArrayList denied, String alias, - PlotHomePosition position, Flag[] flags, String world, boolean[] merged) { - this.id = id; - this.settings = new PlotSettings(this); - this.settings.setBiome(plotBiome); - this.owner = owner; - this.deny_entry = this.owner != null; - this.trusted = trusted; - this.helpers = helpers; - this.denied = denied; - this.settings.setAlias(alias); - this.settings.setPosition(position); - this.settings.setMerged(merged); - this.delete = false; - if (flags != null) { - this.settings.setFlags(flags); - } - else { - this.settings.setFlags(new Flag[0]); - } - this.world = world; - } + /** + * Constructor for saved plots + * + * @param id + * @param owner + * @param plotBiome + * @param helpers + * @param denied + * @param changeTime + * @param time + * @param merged + */ + public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList helpers, final ArrayList trusted, final ArrayList denied, final String alias, final PlotHomePosition position, final Flag[] flags, final String world, final boolean[] merged) { + this.id = id; + this.settings = new PlotSettings(this); + this.settings.setBiome(plotBiome); + this.owner = owner; + this.deny_entry = this.owner != null; + this.trusted = trusted; + this.helpers = helpers; + this.denied = denied; + this.settings.setAlias(alias); + this.settings.setPosition(position); + this.settings.setMerged(merged); + this.delete = false; + if (flags != null) { + this.settings.setFlags(flags); + } + else { + this.settings.setFlags(new Flag[0]); + } + this.world = world; + } - /** - * Check if the plot has a set owner - * - * @return false if there is no owner - */ - public boolean hasOwner() { - return this.owner != null; - } + /** + * Check if the plot has a set owner + * + * @return false if there is no owner + */ + public boolean hasOwner() { + return this.owner != null; + } - /** - * Set the owner - * - * @param player - */ - public void setOwner(Player player) { - this.owner = player.getUniqueId(); - } + /** + * Set the owner + * + * @param player + */ + public void setOwner(final Player player) { + this.owner = player.getUniqueId(); + } - /** - * Check if the player is either the owner or on the helpers list - * - * @param player - * @return true if the player is added as a helper or is the owner - */ - public boolean hasRights(Player player) { - return PlotMain.hasPermission(player, "plots.admin") - || ((this.helpers != null) && this.helpers.contains(DBFunc.everyone)) - || ((this.helpers != null) && this.helpers.contains(player.getUniqueId())) - || ((this.owner != null) && this.owner.equals(player.getUniqueId())) - || ((this.owner != null) && (this.trusted != null) && (Bukkit.getPlayer(this.owner) != null) && (this.trusted.contains(player.getUniqueId()) || this.trusted.contains(DBFunc.everyone))); - } + /** + * Check if the player is either the owner or on the helpers list + * + * @param player + * @return true if the player is added as a helper or is the owner + */ + public boolean hasRights(final Player player) { + return PlotMain.hasPermission(player, "plots.admin") || ((this.helpers != null) && this.helpers.contains(DBFunc.everyone)) || ((this.helpers != null) && this.helpers.contains(player.getUniqueId())) || ((this.owner != null) && this.owner.equals(player.getUniqueId())) || ((this.owner != null) && (this.trusted != null) && (Bukkit.getPlayer(this.owner) != null) && (this.trusted.contains(player.getUniqueId()) || this.trusted.contains(DBFunc.everyone))); + } - /** - * Should the player be allowed to enter? - * - * @param player - * @return false if the player is allowed to enter - */ - public boolean deny_entry(Player player) { - return (this.denied != null) - && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId()))); - } + /** + * Should the player be allowed to enter? + * + * @param player + * @return false if the player is allowed to enter + */ + public boolean deny_entry(final Player player) { + return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId()))); + } - /** - * Get the UUID of the owner - */ - public UUID getOwner() { - return this.owner; - } + /** + * Get the UUID of the owner + */ + public UUID getOwner() { + return this.owner; + } - /** - * Get the plot ID - */ - public PlotId getId() { - return this.id; - } + /** + * Get the plot ID + */ + public PlotId getId() { + return this.id; + } - /** - * Get the plot World - */ - public World getWorld() { - return Bukkit.getWorld(this.world); - } + /** + * Get the plot World + */ + public World getWorld() { + return Bukkit.getWorld(this.world); + } - /** - * Get a clone of the plot - * - * @return - */ - @Override - public Object clone() throws CloneNotSupportedException { - try { - return super.clone(); - } - catch (CloneNotSupportedException e) { - return null; - } - } + /** + * Get a clone of the plot + * + * @return + */ + @Override + public Object clone() throws CloneNotSupportedException { + try { + return super.clone(); + } + catch (final CloneNotSupportedException e) { + return null; + } + } - /** - * Deny someone (use DBFunc.addDenied() as well) - * - * @param uuid - */ - public void addDenied(UUID uuid) { - this.denied.add(uuid); - } + /** + * Deny someone (use DBFunc.addDenied() as well) + * + * @param uuid + */ + public void addDenied(final UUID uuid) { + this.denied.add(uuid); + } - /** - * Add someone as a helper (use DBFunc as well) - * - * @param uuid - */ - public void addHelper(UUID uuid) { - this.helpers.add(uuid); - } + /** + * Add someone as a helper (use DBFunc as well) + * + * @param uuid + */ + public void addHelper(final UUID uuid) { + this.helpers.add(uuid); + } - /** - * Add someone as a trusted user (use DBFunc as well) - * - * @param uuid - */ - public void addTrusted(UUID uuid) { - this.trusted.add(uuid); - } + /** + * Add someone as a trusted user (use DBFunc as well) + * + * @param uuid + */ + public void addTrusted(final UUID uuid) { + this.trusted.add(uuid); + } - /** - * Get plot display name - * - * @return alias if set, else id - */ - public String getDisplayName() { - if (this.settings.getAlias().length() > 1) { - return this.settings.getAlias(); - } - return this.getId().x + ";" + this.getId().y; - } + /** + * Get plot display name + * + * @return alias if set, else id + */ + public String getDisplayName() { + if (this.settings.getAlias().length() > 1) { + return this.settings.getAlias(); + } + return this.getId().x + ";" + this.getId().y; + } - /** - * Remove a denied player (use DBFunc as well) - * - * @param uuid - */ - public void removeDenied(UUID uuid) { - this.denied.remove(uuid); - } + /** + * Remove a denied player (use DBFunc as well) + * + * @param uuid + */ + public void removeDenied(final UUID uuid) { + this.denied.remove(uuid); + } - /** - * Remove a helper (use DBFunc as well) - * - * @param uuid - */ - public void removeHelper(UUID uuid) { - this.helpers.remove(uuid); - } + /** + * Remove a helper (use DBFunc as well) + * + * @param uuid + */ + public void removeHelper(final UUID uuid) { + this.helpers.remove(uuid); + } - /** - * Remove a trusted user (use DBFunc as well) - * - * @param uuid - */ - public void removeTrusted(UUID uuid) { - this.trusted.remove(uuid); - } + /** + * Remove a trusted user (use DBFunc as well) + * + * @param uuid + */ + public void removeTrusted(final UUID uuid) { + this.trusted.remove(uuid); + } - /** - * Clear a plot - * - * @param plr - * initiator - */ - public void clear(Player plr) { - PlotHelper.clear(plr, this); - } + /** + * Clear a plot + * + * @param plr + * initiator + */ + public void clear(final Player plr) { + PlotHelper.clear(plr, this); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotBlock.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotBlock.java index c8f3c4c2c..a633fff94 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotBlock.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotBlock.java @@ -1,11 +1,11 @@ package com.intellectualcrafters.plot; public class PlotBlock { - public short id; - public byte data; + public short id; + public byte data; - public PlotBlock(short id, byte data) { - this.id = id; - this.data = data; - } + public PlotBlock(final short id, final byte data) { + this.id = id; + this.data = data; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotComment.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotComment.java index 6812738b1..12c574bb7 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotComment.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotComment.java @@ -2,10 +2,10 @@ package com.intellectualcrafters.plot; public class PlotComment { public final String comment; - public final int tier; + public final int tier; public final String senderName; - - public PlotComment(String comment, String senderName, int tier) { + + public PlotComment(final String comment, final String senderName, final int tier) { this.comment = comment; this.tier = tier; this.senderName = senderName; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotGenerator.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotGenerator.java index d485975f9..d8d3e8042 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotGenerator.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotGenerator.java @@ -4,11 +4,11 @@ import org.bukkit.generator.ChunkGenerator; public abstract class PlotGenerator extends ChunkGenerator { - public PlotGenerator(String world) { - PlotMain.loadWorld(world, this); - } + public PlotGenerator(final String world) { + PlotMain.loadWorld(world, this); + } - public abstract PlotWorld getNewPlotWorld(String world); + public abstract PlotWorld getNewPlotWorld(final String world); - public abstract PlotManager getPlotManager(); + public abstract PlotManager getPlotManager(); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHelper.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHelper.java index 6597585e3..e1adcbbad 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHelper.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHelper.java @@ -2,15 +2,25 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlotHelper.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.database.DBFunc; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; + import net.milkbowl.vault.economy.Economy; -import org.bukkit.*; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -18,10 +28,7 @@ import org.bukkit.block.Sign; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.UUID; +import com.intellectualcrafters.plot.database.DBFunc; /** * plot functions @@ -29,641 +36,645 @@ import java.util.UUID; * @author Citymonstret */ public class PlotHelper { - public static boolean canSetFast = false; - static long state = 1; + public static boolean canSetFast = false; + static long state = 1; - /** - * direction 0 = north, 1 = south, etc: - * - * @param id - * @param direction - * @return - */ - public static PlotId getPlotIdRelative(PlotId id, int direction) { - switch (direction) { - case 0: - return new PlotId(id.x, id.y - 1); - case 1: - return new PlotId(id.x + 1, id.y); - case 2: - return new PlotId(id.x, id.y + 1); - case 3: - return new PlotId(id.x - 1, id.y); - } - return id; - } + /** + * direction 0 = north, 1 = south, etc: + * + * @param id + * @param direction + * @return + */ + public static PlotId getPlotIdRelative(final PlotId id, final int direction) { + switch (direction) { + case 0: + return new PlotId(id.x, id.y - 1); + case 1: + return new PlotId(id.x + 1, id.y); + case 2: + return new PlotId(id.x, id.y + 1); + case 3: + return new PlotId(id.x - 1, id.y); + } + return id; + } - /** - * Merges all plots in the arraylist (with cost) - * @param plr - * @param world - * @param plotIds - * @return - */ - public static boolean mergePlots(Player plr, World world, ArrayList plotIds) { - PlotWorld plotworld = PlotMain.getWorldSettings(world); - if (PlotMain.useEconomy && plotworld.USE_ECONOMY) { - double cost = plotIds.size() * plotworld.MERGE_PRICE; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - PlayerFunctions.sendMessage(plr, C.CANNOT_AFFORD_MERGE, "" + cost); - return false; - } - economy.withdrawPlayer(plr, cost); - PlayerFunctions.sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } - return mergePlots(world, plotIds); - } + /** + * Merges all plots in the arraylist (with cost) + * + * @param plr + * @param world + * @param plotIds + * @return + */ + public static boolean mergePlots(final Player plr, final World world, final ArrayList plotIds) { + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + if (PlotMain.useEconomy && plotworld.USE_ECONOMY) { + final double cost = plotIds.size() * plotworld.MERGE_PRICE; + if (cost > 0d) { + final Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + PlayerFunctions.sendMessage(plr, C.CANNOT_AFFORD_MERGE, "" + cost); + return false; + } + economy.withdrawPlayer(plr, cost); + PlayerFunctions.sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } + return mergePlots(world, plotIds); + } - /** - * Completely merges a set of plots
    - * (There are no checks to make sure you supply the correct - * arguments)
    - * - Misuse of this method can result in unusable plots
    - * - the set of plots must belong to one owner and be rectangular
    - * - the plot array must be sorted in ascending order
    - * - Road will be removed where required
    - * - changes will be saved to DB
    - * - * @param world - * @param plotIds - * @return boolean (success) - */ - public static boolean mergePlots(World world, ArrayList plotIds) { - if (plotIds.size() < 2) { - return false; - } - PlotId pos1 = plotIds.get(0); - PlotId pos2 = plotIds.get(plotIds.size() - 1); + /** + * Completely merges a set of plots
    + * (There are no checks to make sure you supply the correct + * arguments)
    + * - Misuse of this method can result in unusable plots
    + * - the set of plots must belong to one owner and be rectangular
    + * - the plot array must be sorted in ascending order
    + * - Road will be removed where required
    + * - changes will be saved to DB
    + * + * @param world + * @param plotIds + * @return boolean (success) + */ + public static boolean mergePlots(final World world, final ArrayList plotIds) { + if (plotIds.size() < 2) { + return false; + } + final PlotId pos1 = plotIds.get(0); + final PlotId pos2 = plotIds.get(plotIds.size() - 1); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - manager.startPlotMerge(world, plotworld, plotIds); - - boolean result = false; - - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - - boolean changed = false; - - boolean lx = x < pos2.x; - boolean ly = y < pos2.y; + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotId id = new PlotId(x, y); - Plot plot = PlotMain.getPlots(world).get(id); - Plot plot2 = null; - - if (lx) { - if (ly) { - if (!plot.settings.getMerged(1) || !plot.settings.getMerged(2)) { - changed = true; - manager.removeRoadSouthEast(plotworld, plot); - } - } - if (!plot.settings.getMerged(1)) { - changed = true; - plot2 = PlotMain.getPlots(world).get(new PlotId(x + 1, y)); - mergePlot(world, plot, plot2); - plot.settings.setMerged(1, true); - plot2.settings.setMerged(3, true); - } - } - if (ly) { - if (!plot.settings.getMerged(2)) { - changed = true; - plot2 = PlotMain.getPlots(world).get(new PlotId(x, y + 1)); - mergePlot(world, plot, plot2); - plot.settings.setMerged(2, true); - plot2.settings.setMerged(0, true); - } - } - if (changed) { - result = true; - DBFunc.setMerged(world.getName(), plot, plot.settings.getMerged()); - if (plot2!=null) { - DBFunc.setMerged(world.getName(), plot2, plot2.settings.getMerged()); - } - } - } - } + manager.startPlotMerge(world, plotworld, plotIds); - manager.finishPlotMerge(world, plotworld, plotIds); - return result; - } + boolean result = false; - /** - * Merges 2 plots Removes the road inbetween
    - * - Assumes the first plot parameter is lower
    - * - Assumes neither are a Mega-plot
    - * - Assumes plots are directly next to each other
    - * - Saves to DB - * - * @param world - * @param lesserPlot - * @param greaterPlot - */ - public static void mergePlot(World world, Plot lesserPlot, Plot greaterPlot) { - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { - if (lesserPlot.id.x == greaterPlot.id.x) { - if (!lesserPlot.settings.getMerged(2)) { - lesserPlot.settings.setMerged(2, true); - greaterPlot.settings.setMerged(0, true); - manager.removeRoadSouth(plotworld, lesserPlot); - } - } - else { - if (!lesserPlot.settings.getMerged(1)) { - lesserPlot.settings.setMerged(1, true); - greaterPlot.settings.setMerged(3, true); - manager.removeRoadEast(plotworld, lesserPlot); - } - } - } + boolean changed = false; - /* - * Random number gen section - */ - public static final long nextLong() { - long a = state; - state = xorShift64(a); - return a; - } + final boolean lx = x < pos2.x; + final boolean ly = y < pos2.y; - public static final long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } + final PlotId id = new PlotId(x, y); + final Plot plot = PlotMain.getPlots(world).get(id); + Plot plot2 = null; - public static final int random(int n) { - if (n == 1) { - return 0; - } - long r = ((nextLong() >>> 32) * n) >> 32; - return (int) r; - } - /* + if (lx) { + if (ly) { + if (!plot.settings.getMerged(1) || !plot.settings.getMerged(2)) { + changed = true; + manager.removeRoadSouthEast(plotworld, plot); + } + } + if (!plot.settings.getMerged(1)) { + changed = true; + plot2 = PlotMain.getPlots(world).get(new PlotId(x + 1, y)); + mergePlot(world, plot, plot2); + plot.settings.setMerged(1, true); + plot2.settings.setMerged(3, true); + } + } + if (ly) { + if (!plot.settings.getMerged(2)) { + changed = true; + plot2 = PlotMain.getPlots(world).get(new PlotId(x, y + 1)); + mergePlot(world, plot, plot2); + plot.settings.setMerged(2, true); + plot2.settings.setMerged(0, true); + } + } + if (changed) { + result = true; + DBFunc.setMerged(world.getName(), plot, plot.settings.getMerged()); + if (plot2 != null) { + DBFunc.setMerged(world.getName(), plot2, plot2.settings.getMerged()); + } + } + } + } + + manager.finishPlotMerge(world, plotworld, plotIds); + return result; + } + + /** + * Merges 2 plots Removes the road inbetween
    + * - Assumes the first plot parameter is lower
    + * - Assumes neither are a Mega-plot
    + * - Assumes plots are directly next to each other
    + * - Saves to DB + * + * @param world + * @param lesserPlot + * @param greaterPlot + */ + public static void mergePlot(final World world, final Plot lesserPlot, final Plot greaterPlot) { + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + + if (lesserPlot.id.x == greaterPlot.id.x) { + if (!lesserPlot.settings.getMerged(2)) { + lesserPlot.settings.setMerged(2, true); + greaterPlot.settings.setMerged(0, true); + manager.removeRoadSouth(plotworld, lesserPlot); + } + } + else { + if (!lesserPlot.settings.getMerged(1)) { + lesserPlot.settings.setMerged(1, true); + greaterPlot.settings.setMerged(3, true); + manager.removeRoadEast(plotworld, lesserPlot); + } + } + } + + /* + * Random number gen section + */ + public static final long nextLong() { + final long a = state; + state = xorShift64(a); + return a; + } + + public static final long xorShift64(long a) { + a ^= (a << 21); + a ^= (a >>> 35); + a ^= (a << 4); + return a; + } + + public static final int random(final int n) { + if (n == 1) { + return 0; + } + final long r = ((nextLong() >>> 32) * n) >> 32; + return (int) r; + } + + /* * End of random number gen section */ - public static void removeSign(World world, Plot p) { - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - Location loc = manager.getSignLoc(world, plotworld, p); - Block bs = loc.getBlock(); - bs.setType(Material.AIR); - } - - public static void setSign(Player player, Plot p) { - setSign(player.getWorld(), player.getName(), p); - } + public static void removeSign(final World world, final Plot p) { + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + final Location loc = manager.getSignLoc(world, plotworld, p); + final Block bs = loc.getBlock(); + bs.setType(Material.AIR); + } - @SuppressWarnings("deprecation") - public static void setSign(World world, String name, Plot p) { - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - Location loc = manager.getSignLoc(world, plotworld, p); - Block bs = loc.getBlock(); - bs.setType(Material.AIR); - bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); - String id = p.id.x + ";" + p.id.y; - Sign sign = (Sign) bs.getState(); - sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id)); - sign.setLine(1, C.OWNER_SIGN_LINE_2.translated().replaceAll("%id%", id).replaceAll("%plr%", name)); - sign.setLine(2, C.OWNER_SIGN_LINE_3.translated().replaceAll("%id%", id).replaceAll("%plr%", name)); - sign.setLine(3, C.OWNER_SIGN_LINE_4.translated().replaceAll("%id%", id).replaceAll("%plr%", name)); - sign.update(true); - } + public static void setSign(final Player player, final Plot p) { + setSign(player.getWorld(), player.getName(), p); + } - - public static String getPlayerName(UUID uuid) { - if (uuid == null) { - return "unknown"; - } - OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); - if (plr == null) { - return "unknown"; - } - return plr.getName(); - } + @SuppressWarnings("deprecation") + public static void setSign(final World world, final String name, final Plot p) { + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + final Location loc = manager.getSignLoc(world, plotworld, p); + final Block bs = loc.getBlock(); + bs.setType(Material.AIR); + bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); + final String id = p.id.x + ";" + p.id.y; + final Sign sign = (Sign) bs.getState(); + sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id)); + sign.setLine(1, C.OWNER_SIGN_LINE_2.translated().replaceAll("%id%", id).replaceAll("%plr%", name)); + sign.setLine(2, C.OWNER_SIGN_LINE_3.translated().replaceAll("%id%", id).replaceAll("%plr%", name)); + sign.setLine(3, C.OWNER_SIGN_LINE_4.translated().replaceAll("%id%", id).replaceAll("%plr%", name)); + sign.update(true); + } - public static String getStringSized(int max, String string) { - if (string.length() > max) { - return string.substring(0, max); - } - return string; - } + public static String getPlayerName(final UUID uuid) { + if (uuid == null) { + return "unknown"; + } + final OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); + if (plr == null) { + return "unknown"; + } + return plr.getName(); + } - /** - * Set a block quickly, attempts to use NMS if possible - * @param block - * @param plotblock - */ - public static boolean setBlock(Block block, PlotBlock plotblock) { + public static String getStringSized(final int max, final String string) { + if (string.length() > max) { + return string.substring(0, max); + } + return string; + } - if (canSetFast) { - if (block.getTypeId() != plotblock.id || plotblock.data != block.getData()) { - try { - SetBlockFast.set(block.getWorld(), block.getX(), block.getY(), block.getZ(), plotblock.id, plotblock.data); - return true; - } - catch (Throwable e) { - canSetFast = false; - } - } - return false; - } - if (block.getData() == plotblock.data) { - if (block.getTypeId() != plotblock.id) { - block.setTypeId(plotblock.id); - } - } - else { - if (block.getTypeId() == plotblock.id) { - block.setData(plotblock.data); - } - else { - block.setTypeIdAndData(plotblock.id, plotblock.data, false); - } - } - return false; - } + /** + * Set a block quickly, attempts to use NMS if possible + * + * @param block + * @param plotblock + */ + public static boolean setBlock(final Block block, final PlotBlock plotblock) { - /** - * Adjusts a plot wall - * @param player - * @param plot - * @param block - */ - public static void adjustWall(Player player, Plot plot, PlotBlock block) { - World world = player.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); + if (canSetFast) { + if ((block.getTypeId() != plotblock.id) || (plotblock.data != block.getData())) { + try { + SetBlockFast.set(block.getWorld(), block.getX(), block.getY(), block.getZ(), plotblock.id, plotblock.data); + return true; + } + catch (final Throwable e) { + canSetFast = false; + } + } + return false; + } + if (block.getData() == plotblock.data) { + if (block.getTypeId() != plotblock.id) { + block.setTypeId(plotblock.id); + } + } + else { + if (block.getTypeId() == plotblock.id) { + block.setData(plotblock.data); + } + else { + block.setTypeIdAndData(plotblock.id, plotblock.data, false); + } + } + return false; + } - manager.setWall(world, plotworld, plot.id, block); - } + /** + * Adjusts a plot wall + * + * @param player + * @param plot + * @param block + */ + public static void adjustWall(final Player player, final Plot plot, final PlotBlock block) { + final World world = player.getWorld(); + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); - public static void autoMerge(World world, Plot plot, Player player) { - if (plot == null) { - return; - } - if (plot.owner == null) { - return; - } - if (!plot.owner.equals(player.getUniqueId())) { - return; - } + manager.setWall(world, plotworld, plot.id, block); + } - ArrayList plots; - boolean merge = true; - int count = 0; - while (merge) { - if (count>16) { - break; - } - count++; - PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; - PlotId top = PlayerFunctions.getTopPlot(world, plot).id; - merge = false; - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); - if (ownsPlots(world, plots, player, 0)) { - boolean result = mergePlots(world, plots); - if (result) { - merge = true; - continue; - } - } - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); - if (ownsPlots(world, plots, player, 1)) { - boolean result = mergePlots(world, plots); - if (result) { + public static void autoMerge(final World world, final Plot plot, final Player player) { + if (plot == null) { + return; + } + if (plot.owner == null) { + return; + } + if (!plot.owner.equals(player.getUniqueId())) { + return; + } + + ArrayList plots; + boolean merge = true; + int count = 0; + while (merge) { + if (count > 16) { + break; + } + count++; + final PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; + final PlotId top = PlayerFunctions.getTopPlot(world, plot).id; + merge = false; + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); + if (ownsPlots(world, plots, player, 0)) { + final boolean result = mergePlots(world, plots); + if (result) { merge = true; continue; } - } - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); - if (ownsPlots(world, plots, player, 2)) { - boolean result = mergePlots(world, plots); - if (result) { + } + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); + if (ownsPlots(world, plots, player, 1)) { + final boolean result = mergePlots(world, plots); + if (result) { merge = true; continue; } - } - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); - if (ownsPlots(world, plots, player, 3)) { - boolean result = mergePlots(world, plots); - if (result) { + } + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); + if (ownsPlots(world, plots, player, 2)) { + final boolean result = mergePlots(world, plots); + if (result) { merge = true; continue; } - } - merge = false; - } - if (canSetFast) { - SetBlockFast.update(player); - } - } + } + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); + if (ownsPlots(world, plots, player, 3)) { + final boolean result = mergePlots(world, plots); + if (result) { + merge = true; + continue; + } + } + merge = false; + } + if (canSetFast) { + SetBlockFast.update(player); + } + } - private static boolean ownsPlots(World world, ArrayList plots, Player player, int dir) { - PlotId id_min = plots.get(0); - PlotId id_max = plots.get(plots.size() - 1); - for (PlotId myid : plots) { - Plot myplot = PlotMain.getPlots(world).get(myid); - if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(player.getUniqueId()))) { - return false; - } - PlotId top = PlayerFunctions.getTopPlot(world, myplot).id; - if (((top.x > id_max.x) && (dir != 1)) || ((top.y > id_max.y) && (dir != 2))) { - return false; - } - PlotId bot = PlayerFunctions.getBottomPlot(world, myplot).id; - if (((bot.x < id_min.x) && (dir != 3)) || ((bot.y < id_min.y) && (dir != 0))) { - return false; - } - } - return true; - } + private static boolean ownsPlots(final World world, final ArrayList plots, final Player player, final int dir) { + final PlotId id_min = plots.get(0); + final PlotId id_max = plots.get(plots.size() - 1); + for (final PlotId myid : plots) { + final Plot myplot = PlotMain.getPlots(world).get(myid); + if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(player.getUniqueId()))) { + return false; + } + final PlotId top = PlayerFunctions.getTopPlot(world, myplot).id; + if (((top.x > id_max.x) && (dir != 1)) || ((top.y > id_max.y) && (dir != 2))) { + return false; + } + final PlotId bot = PlayerFunctions.getBottomPlot(world, myplot).id; + if (((bot.x < id_min.x) && (dir != 3)) || ((bot.y < id_min.y) && (dir != 0))) { + return false; + } + } + return true; + } - public static boolean createPlot(Player player, Plot plot) { - World w = plot.getWorld(); - Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), new ArrayList(), new ArrayList(), w.getName()); - PlotMain.updatePlot(p); - DBFunc.createPlot(p); - DBFunc.createPlotSettings(DBFunc.getId(w.getName(), plot.id), plot); - PlotWorld plotworld = PlotMain.getWorldSettings(w); - if (plotworld.AUTO_MERGE) { - autoMerge(w, p, player); - } + public static boolean createPlot(final Player player, final Plot plot) { + final World w = plot.getWorld(); + final Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), new ArrayList(), new ArrayList(), w.getName()); + PlotMain.updatePlot(p); + DBFunc.createPlot(p); + DBFunc.createPlotSettings(DBFunc.getId(w.getName(), plot.id), plot); + final PlotWorld plotworld = PlotMain.getWorldSettings(w); + if (plotworld.AUTO_MERGE) { + autoMerge(w, p, player); + } - return true; - } + return true; + } - public static int getLoadedChunks(World world) { - return world.getLoadedChunks().length; - } + public static int getLoadedChunks(final World world) { + return world.getLoadedChunks().length; + } - public static int getEntities(World world) { - return world.getEntities().size(); - } + public static int getEntities(final World world) { + return world.getEntities().size(); + } - public static int getTileEntities(World world) { - PlotMain.getWorldSettings(world); - int x = 0; - for (Chunk chunk : world.getLoadedChunks()) { - x += chunk.getTileEntities().length; - } - return x; - } + public static int getTileEntities(final World world) { + PlotMain.getWorldSettings(world); + int x = 0; + for (final Chunk chunk : world.getLoadedChunks()) { + x += chunk.getTileEntities().length; + } + return x; + } - public static double getWorldFolderSize(World world) { - // long size = FileUtil.sizeOfDirectory(world.getWorldFolder()); - File folder = world.getWorldFolder(); - long size = folder.length(); - return (((size) / 1024) / 1024); - } + public static double getWorldFolderSize(final World world) { + // long size = FileUtil.sizeOfDirectory(world.getWorldFolder()); + final File folder = world.getWorldFolder(); + final long size = folder.length(); + return (((size) / 1024) / 1024); + } - // public static void adjustLinkedPlots(String id) { - // World world = Bukkit.getWorld(Settings.PLOT_WORLD); - // int x = getIdX(id); - // int z = getIdZ(id); - // - // plot p11 = getPlot(id); - // if (p11 != null) { - // plot p01, p10, p12, p21, p00, p02, p20, p22; - // p01 = getPlot(x - 1, z); - // p10 = getPlot(x, z - 1); - // p12 = getPlot(x, z + 1); - // p21 = getPlot(x + 1, z); - // p00 = getPlot(x - 1, z - 1); - // p02 = getPlot(x - 1, z + 1); - // p20 = getPlot(x + 1, z - 1); - // p22 = getPlot(x + 1, z + 1); - // if (p01 != null && p01.owner.equals(p11.owner)) { - // fillroad(p01, p11, world); - // } - // - // if (p10 != null && p10.owner.equals(p11.owner)) { - // fillroad(p10, p11, world); - // } - // - // if (p12 != null && p12.owner.equals(p11.owner)) { - // fillroad(p12, p11, world); - // } - // - // if (p21 != null && p21.owner.equals(p11.owner)) { - // fillroad(p21, p11, world); - // } - // - // if (p00 != null && p10 != null && p01 != null - // && p00.owner.equals(p11.owner) - // && p11.owner.equals(p10.owner) - // && p10.owner.equals(p01.owner)) { - // fillmiddleroad(p00, p11, world); - // } - // - // if (p10 != null && p20 != null && p21 != null - // && p10.owner.equals(p11.owner) - // && p11.owner.equals(p20.owner) - // && p20.owner.equals(p21.owner)) { - // fillmiddleroad(p20, p11, world); - // } - // - // if (p01 != null && p02 != null && p12 != null - // && p01.owner.equals(p11.owner) - // && p11.owner.equals(p02.owner) - // && p02.owner.equals(p12.owner)) { - // fillmiddleroad(p02, p11, world); - // } - // - // if (p12 != null && p21 != null && p22 != null - // && p12.owner.equals(p11.owner) - // && p11.owner.equals(p21.owner) - // && p21.owner.equals(p22.owner)) { - // fillmiddleroad(p22, p11, world); - // } - // } - // } - // - // public static void fillroad(plot plot1, plot plot2, World w) { - // Location bottomPlot1, topPlot1, bottomPlot2, topPlot2; - // bottomPlot1 = getPlotBottomLoc(w, plot1.id); - // topPlot1 = getPlotTopLoc(w, plot1.id); - // bottomPlot2 = getPlotBottomLoc(w, plot2.id); - // topPlot2 = getPlotTopLoc(w, plot2.id); - // - // int minX, maxX, minZ, maxZ; - // - // boolean isWallX; - // - // int h = Settings.ROAD_HEIGHT; - // int wallId = Settings.WALL_BLOCK; - // int fillId = Settings.TOP_BLOCK; - // - // if(bottomPlot1.getBlockX() == bottomPlot2.getBlockX()) { - // minX = bottomPlot1.getBlockX(); - // maxX = topPlot1.getBlockX(); - // - // minZ = Math.min(bottomPlot1.getBlockZ(), bottomPlot2.getBlockZ()) + - // Settings.PLOT_WIDTH; - // maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) - - // Settings.PLOT_WIDTH; - // } else { - // minZ = bottomPlot1.getBlockZ(); - // maxZ = topPlot1.getBlockZ(); - // - // minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) + - // Settings.PLOT_WIDTH; - // maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) - - // Settings.PLOT_WIDTH; - // } - // - // isWallX = (maxX - minX) > (maxZ - minZ); - // - // if(isWallX) { - // minX--; - // maxX++; - // } else { - // minZ--; - // maxZ++; - // } - // - // for(int x = minX; x <= maxX; x++) { - // for(int z = minZ; x <= maxZ; z++) { - // for(int y = h; y < h + 3; y++) { - // if(y >= (h + 2)) { - // w.getBlockAt(x,y,z).setType(Material.AIR); - // } else if(y == (h + 1)) { - // if(isWallX && (x == minX || x == maxX)) { - // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); - // } else if(!isWallX && (z == minZ || z == maxZ)) { - // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); - // } else { - // w.getBlockAt(x,y,z).setType(Material.AIR); - // } - // } else { - // w.getBlockAt(x,y,z).setTypeIdAndData(fillId, (byte) 0, true); - // } - // } - // } - // } - // } - // - // public static void fillmiddleroad(plot p1, plot p2, World w) { - // Location b1 = getPlotBottomLoc(w, p1.id); - // Location t1 = getPlotTopLoc(w, p1.id); - // Location b2 = getPlotBottomLoc(w, p2.id); - // Location t2 = getPlotTopLoc(w, p2.id); - // - // int minX, maxX, minZ, maxZ; - // - // int h = Settings.ROAD_HEIGHT; - // int fillID = Settings.TOP_BLOCK; - // - // minX = Math.min(t1.getBlockX(), t2.getBlockX()); - // maxX = Math.max(b1.getBlockX(), b2.getBlockX()); - // - // minZ = Math.min(t1.getBlockZ(), t2.getBlockZ()); - // maxZ = Math.max(b1.getBlockZ(), b2.getBlockZ()); - // - // for(int x = minX; x <= maxX; x++) { - // for(int z = minZ; z <= maxZ; z++) { - // for(int y = h; y < h + 3; y++) { - // if(y >= (h + 1)) { - // w.getBlockAt(x,y,z).setType(Material.AIR); - // } else { - // w.getBlockAt(x,y,z).setTypeId(fillID); - // } - // } - // } - // } - // } + // public static void adjustLinkedPlots(String id) { + // World world = Bukkit.getWorld(Settings.PLOT_WORLD); + // int x = getIdX(id); + // int z = getIdZ(id); + // + // plot p11 = getPlot(id); + // if (p11 != null) { + // plot p01, p10, p12, p21, p00, p02, p20, p22; + // p01 = getPlot(x - 1, z); + // p10 = getPlot(x, z - 1); + // p12 = getPlot(x, z + 1); + // p21 = getPlot(x + 1, z); + // p00 = getPlot(x - 1, z - 1); + // p02 = getPlot(x - 1, z + 1); + // p20 = getPlot(x + 1, z - 1); + // p22 = getPlot(x + 1, z + 1); + // if (p01 != null && p01.owner.equals(p11.owner)) { + // fillroad(p01, p11, world); + // } + // + // if (p10 != null && p10.owner.equals(p11.owner)) { + // fillroad(p10, p11, world); + // } + // + // if (p12 != null && p12.owner.equals(p11.owner)) { + // fillroad(p12, p11, world); + // } + // + // if (p21 != null && p21.owner.equals(p11.owner)) { + // fillroad(p21, p11, world); + // } + // + // if (p00 != null && p10 != null && p01 != null + // && p00.owner.equals(p11.owner) + // && p11.owner.equals(p10.owner) + // && p10.owner.equals(p01.owner)) { + // fillmiddleroad(p00, p11, world); + // } + // + // if (p10 != null && p20 != null && p21 != null + // && p10.owner.equals(p11.owner) + // && p11.owner.equals(p20.owner) + // && p20.owner.equals(p21.owner)) { + // fillmiddleroad(p20, p11, world); + // } + // + // if (p01 != null && p02 != null && p12 != null + // && p01.owner.equals(p11.owner) + // && p11.owner.equals(p02.owner) + // && p02.owner.equals(p12.owner)) { + // fillmiddleroad(p02, p11, world); + // } + // + // if (p12 != null && p21 != null && p22 != null + // && p12.owner.equals(p11.owner) + // && p11.owner.equals(p21.owner) + // && p21.owner.equals(p22.owner)) { + // fillmiddleroad(p22, p11, world); + // } + // } + // } + // + // public static void fillroad(plot plot1, plot plot2, World w) { + // Location bottomPlot1, topPlot1, bottomPlot2, topPlot2; + // bottomPlot1 = getPlotBottomLoc(w, plot1.id); + // topPlot1 = getPlotTopLoc(w, plot1.id); + // bottomPlot2 = getPlotBottomLoc(w, plot2.id); + // topPlot2 = getPlotTopLoc(w, plot2.id); + // + // int minX, maxX, minZ, maxZ; + // + // boolean isWallX; + // + // int h = Settings.ROAD_HEIGHT; + // int wallId = Settings.WALL_BLOCK; + // int fillId = Settings.TOP_BLOCK; + // + // if(bottomPlot1.getBlockX() == bottomPlot2.getBlockX()) { + // minX = bottomPlot1.getBlockX(); + // maxX = topPlot1.getBlockX(); + // + // minZ = Math.min(bottomPlot1.getBlockZ(), bottomPlot2.getBlockZ()) + + // Settings.PLOT_WIDTH; + // maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) - + // Settings.PLOT_WIDTH; + // } else { + // minZ = bottomPlot1.getBlockZ(); + // maxZ = topPlot1.getBlockZ(); + // + // minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) + + // Settings.PLOT_WIDTH; + // maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) - + // Settings.PLOT_WIDTH; + // } + // + // isWallX = (maxX - minX) > (maxZ - minZ); + // + // if(isWallX) { + // minX--; + // maxX++; + // } else { + // minZ--; + // maxZ++; + // } + // + // for(int x = minX; x <= maxX; x++) { + // for(int z = minZ; x <= maxZ; z++) { + // for(int y = h; y < h + 3; y++) { + // if(y >= (h + 2)) { + // w.getBlockAt(x,y,z).setType(Material.AIR); + // } else if(y == (h + 1)) { + // if(isWallX && (x == minX || x == maxX)) { + // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); + // } else if(!isWallX && (z == minZ || z == maxZ)) { + // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); + // } else { + // w.getBlockAt(x,y,z).setType(Material.AIR); + // } + // } else { + // w.getBlockAt(x,y,z).setTypeIdAndData(fillId, (byte) 0, true); + // } + // } + // } + // } + // } + // + // public static void fillmiddleroad(plot p1, plot p2, World w) { + // Location b1 = getPlotBottomLoc(w, p1.id); + // Location t1 = getPlotTopLoc(w, p1.id); + // Location b2 = getPlotBottomLoc(w, p2.id); + // Location t2 = getPlotTopLoc(w, p2.id); + // + // int minX, maxX, minZ, maxZ; + // + // int h = Settings.ROAD_HEIGHT; + // int fillID = Settings.TOP_BLOCK; + // + // minX = Math.min(t1.getBlockX(), t2.getBlockX()); + // maxX = Math.max(b1.getBlockX(), b2.getBlockX()); + // + // minZ = Math.min(t1.getBlockZ(), t2.getBlockZ()); + // maxZ = Math.max(b1.getBlockZ(), b2.getBlockZ()); + // + // for(int x = minX; x <= maxX; x++) { + // for(int z = minZ; z <= maxZ; z++) { + // for(int y = h; y < h + 3; y++) { + // if(y >= (h + 1)) { + // w.getBlockAt(x,y,z).setType(Material.AIR); + // } else { + // w.getBlockAt(x,y,z).setTypeId(fillID); + // } + // } + // } + // } + // } - public static String createId(int x, int z) { - return x + ";" + z; - } + public static String createId(final int x, final int z) { + return x + ";" + z; + } - public static ArrayList runners_p = new ArrayList(); - public static HashMap runners = new HashMap(); + public static ArrayList runners_p = new ArrayList(); + public static HashMap runners = new HashMap(); - public static void adjustWallFilling(final Player requester, final Plot plot, PlotBlock block) { - if (runners.containsKey(plot)) { - PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); - return; - } - World world = requester.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - manager.setWallFilling(world, plotworld, plot.id, block); - PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); - if (canSetFast) { - SetBlockFast.update(requester); - } - } + public static void adjustWallFilling(final Player requester, final Plot plot, final PlotBlock block) { + if (runners.containsKey(plot)) { + PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); + return; + } + final World world = requester.getWorld(); + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + manager.setWallFilling(world, plotworld, plot.id, block); + PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); + if (canSetFast) { + SetBlockFast.update(requester); + } + } - public static void setFloor(final Player requester, final Plot plot, PlotBlock[] blocks) { - if (runners.containsKey(plot)) { - PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); - return; - } + public static void setFloor(final Player requester, final Plot plot, final PlotBlock[] blocks) { + if (runners.containsKey(plot)) { + PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); + return; + } - World world = requester.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); - manager.setFloor(world, plotworld, plot.id, blocks); - if (canSetFast) { - SetBlockFast.update(requester); - } - } + final World world = requester.getWorld(); + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); + manager.setFloor(world, plotworld, plot.id, blocks); + if (canSetFast) { + SetBlockFast.update(requester); + } + } - public static int square(int x) { - return x * x; - } + public static int square(final int x) { + return x * x; + } - public static short[] getBlock(String block) { - if (block.contains(":")) { - String[] split = block.split(":"); - return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; - } - return new short[] { Short.parseShort(block), 0 }; - } + public static short[] getBlock(final String block) { + if (block.contains(":")) { + final String[] split = block.split(":"); + return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; + } + return new short[] { Short.parseShort(block), 0 }; + } - public static void clearAllEntities(World world, Plot plot, boolean tile) { - final Location pos1 = getPlotBottomLoc(world, plot.id).add(1, 0, 1); - final Location pos2 = getPlotTopLoc(world, plot.id); - for (int i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { - for (int j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) { - Chunk chunk = world.getChunkAt(i, j); - for (Entity entity : chunk.getEntities()) { - PlotId id = PlayerFunctions.getPlot(entity.getLocation()); - if ((id != null) && id.equals(plot.id)) { - if (entity instanceof Player) { - PlotMain.teleportPlayer((Player) entity, entity.getLocation(), plot); - } - else { - entity.remove(); - } - } - } - if (tile) { - for (BlockState entity : chunk.getTileEntities()) { - entity.setRawData((byte) 0); - } - } - } - } - } - public static void clear(final World world, final Plot plot) { - PlotManager manager = PlotMain.getPlotManager(world); + public static void clearAllEntities(final World world, final Plot plot, final boolean tile) { + final Location pos1 = getPlotBottomLoc(world, plot.id).add(1, 0, 1); + final Location pos2 = getPlotTopLoc(world, plot.id); + for (int i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { + for (int j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) { + final Chunk chunk = world.getChunkAt(i, j); + for (final Entity entity : chunk.getEntities()) { + final PlotId id = PlayerFunctions.getPlot(entity.getLocation()); + if ((id != null) && id.equals(plot.id)) { + if (entity instanceof Player) { + PlotMain.teleportPlayer((Player) entity, entity.getLocation(), plot); + } + else { + entity.remove(); + } + } + } + if (tile) { + for (final BlockState entity : chunk.getTileEntities()) { + entity.setRawData((byte) 0); + } + } + } + } + } - Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add(1, 0, 1); + public static void clear(final World world, final Plot plot) { + final PlotManager manager = PlotMain.getPlotManager(world); + + final Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add(1, 0, 1); final int prime = 31; int h = 1; @@ -674,290 +685,299 @@ public class PlotHelper { PlotHelper.setBiome(world, plot, Biome.FOREST); manager.clearPlot(world, plot); - + if (canSetFast) { refreshPlotChunks(world, plot); // SetBlockFast.update(requester); } - } - - - /** - * Clear a plot - * - * @param requester - * @param plot - */ - public static void clear(final Player requester, final Plot plot) { - if (runners.containsKey(plot)) { - PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); - return; - } - - PlayerFunctions.sendMessage(requester, C.CLEARING_PLOT); + } - final long start = System.nanoTime(); - - final World world; - if (requester!=null) { - world = requester.getWorld(); - } - else { - world = Bukkit.getWorld(plot.world); - } + /** + * Clear a plot + * + * @param requester + * @param plot + */ + public static void clear(final Player requester, final Plot plot) { + if (runners.containsKey(plot)) { + PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); + return; + } - /* - * keep - */ - clearAllEntities(world, plot, false); - clear(world, plot); - removeSign(world, plot); - PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" - + ((System.nanoTime() - start) / 1000000.0))); + PlayerFunctions.sendMessage(requester, C.CLEARING_PLOT); - return; - } + final long start = System.nanoTime(); - public static void setCuboid(World world, Location pos1, Location pos2, PlotBlock[] blocks) { - if (!canSetFast) { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - int i = random(blocks.length); - PlotBlock newblock = blocks[i]; - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { - block.setTypeIdAndData(newblock.id, newblock.data, false); - } - } - } - } - } - else { - try { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - int i = random(blocks.length); - PlotBlock newblock = blocks[i]; - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { - SetBlockFast.set(world, x, y, z, newblock.id, newblock.data); - } - } - } - } - } - catch (Exception e) { - } - } - } + final World world; + if (requester != null) { + world = requester.getWorld(); + } + else { + world = Bukkit.getWorld(plot.world); + } - public static void setSimpleCuboid(World world, Location pos1, Location pos2, PlotBlock newblock) { - if (!canSetFast) { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id))) { - block.setTypeId(newblock.id, false); - } - } - } - } - } - else { - try { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id))) { - SetBlockFast.set(world, x, y, z, newblock.id, (byte) 0); - } - } - } - } - } - catch (Exception e) { + /* + * keep + */ + clearAllEntities(world, plot, false); + clear(world, plot); + removeSign(world, plot); + PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0))); - } - } - } + return; + } - public static void setBiome(World world, Plot plot, Biome b) { - int bottomX = getPlotBottomLoc(world, plot.id).getBlockX() - 1; - int topX = getPlotTopLoc(world, plot.id).getBlockX() + 1; - int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ() - 1; - int topZ = getPlotTopLoc(world, plot.id).getBlockZ() + 1; + public static void setCuboid(final World world, final Location pos1, final Location pos2, final PlotBlock[] blocks) { + if (!canSetFast) { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + final int i = random(blocks.length); + final PlotBlock newblock = blocks[i]; + final Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { + block.setTypeIdAndData(newblock.id, newblock.data, false); + } + } + } + } + } + else { + try { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + final int i = random(blocks.length); + final PlotBlock newblock = blocks[i]; + final Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { + SetBlockFast.set(world, x, y, z, newblock.id, newblock.data); + } + } + } + } + } + catch (final Exception e) { + } + } + } - for (int x = bottomX; x <= topX; x++) { - for (int z = bottomZ; z <= topZ; z++) { - world.getBlockAt(x, 0, z).setBiome(b); - } - } + public static void setSimpleCuboid(final World world, final Location pos1, final Location pos2, final PlotBlock newblock) { + if (!canSetFast) { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + final Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id))) { + block.setTypeId(newblock.id, false); + } + } + } + } + } + else { + try { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + final Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id))) { + SetBlockFast.set(world, x, y, z, newblock.id, (byte) 0); + } + } + } + } + } + catch (final Exception e) { - plot.settings.setBiome(b); - PlotMain.updatePlot(plot); - refreshPlotChunks(world, plot); - } - public static int getHeighestBlock(World world, int x, int z) { - boolean safe = false; - for (int i = 1; i(), new ArrayList(), world.getName()); - } + /** + * Obtains the width of a plot (x width) + * + * @param world + * @param id + * @return + */ + public static int getPlotWidth(final World world, final PlotId id) { + return getPlotTopLoc(world, id).getBlockX() - getPlotBottomLoc(world, id).getBlockX(); + } - /** - * Returns the plot at a given location - * @param loc - * @return - */ - public static Plot getCurrentPlot(Location loc) { - PlotId id = PlayerFunctions.getPlot(loc); - if (id == null) { - return null; - } - if (PlotMain.getPlots(loc.getWorld()).containsKey(id)) { - return PlotMain.getPlots(loc.getWorld()).get(id); - } - return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), loc.getWorld().getName()); - } + /** + * 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 world + * @param id + * @return + */ + public static Location getPlotTopLoc(final World world, PlotId id) { + final Plot plot = PlotMain.getPlots(world).get(id); + if (plot != null) { + id = PlayerFunctions.getTopPlot(world, plot).id; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + final PlotManager manager = PlotMain.getPlotManager(world); + return manager.getPlotTopLocAbs(plotworld, id); + } + + /** + * Gets the bottom loc of a plot (if mega, returns bottom loc of that mega + * plot) + * - If you would like each plot treated as a small plot use + * getPlotBottomLocAbs(...) + * + * @param world + * @param id + * @return + */ + public static Location getPlotBottomLoc(final World world, PlotId id) { + final Plot plot = PlotMain.getPlots(world).get(id); + if (plot != null) { + id = PlayerFunctions.getBottomPlot(world, plot).id; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + final PlotManager manager = PlotMain.getPlotManager(world); + return manager.getPlotBottomLocAbs(plotworld, id); + } + + /** + * Fetches the plot from the main class + * + * @param world + * @param id + * @return + */ + public static Plot getPlot(final World world, final PlotId id) { + if (id == null) { + return null; + } + if (PlotMain.getPlots(world).containsKey(id)) { + return PlotMain.getPlots(world).get(id); + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), world.getName()); + } + + /** + * Returns the plot at a given location + * + * @param loc + * @return + */ + public static Plot getCurrentPlot(final Location loc) { + final PlotId id = PlayerFunctions.getPlot(loc); + if (id == null) { + return null; + } + if (PlotMain.getPlots(loc.getWorld()).containsKey(id)) { + return PlotMain.getPlots(loc.getWorld()).get(id); + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), loc.getWorld().getName()); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHomePosition.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHomePosition.java index c4229f593..d87ad9b5a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHomePosition.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotHomePosition.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlotHomePosition.java >> Generated by: Citymonstret at 2014-08-09 * 01:44 */ @@ -13,25 +13,25 @@ package com.intellectualcrafters.plot; * Created by Citymonstret on 2014-08-05. */ public enum PlotHomePosition { - CENTER("Center", 'c'), - DEFAULT("Default", 'd'); + CENTER("Center", 'c'), + DEFAULT("Default", 'd'); - private String string; - private char ch; + private String string; + private char ch; - PlotHomePosition(String string, char ch) { - this.string = string; - this.ch = ch; - } + PlotHomePosition(final String string, final char ch) { + this.string = string; + this.ch = ch; + } - public boolean isMatching(String string) { - if ((string.length() < 2) && (string.charAt(0) == this.ch)) { - return true; - } - if (string.equalsIgnoreCase(this.string)) { - return true; - } - return false; - } + public boolean isMatching(final String string) { + if ((string.length() < 2) && (string.charAt(0) == this.ch)) { + return true; + } + if (string.equalsIgnoreCase(this.string)) { + return true; + } + return false; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotId.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotId.java index 1cacbe4cf..50004d3b6 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotId.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotId.java @@ -1,54 +1,54 @@ package com.intellectualcrafters.plot; public class PlotId { - /** - * x value - */ - public Integer x; - /** - * y value - */ - public Integer y; + /** + * x value + */ + public Integer x; + /** + * y value + */ + public Integer y; - /** - * PlotId class (PlotId x,y values do not correspond to Block locations) - * - * @param x - * The plot x coordinate - * @param y - * The plot y coordinate - */ - public PlotId(int x, int y) { - this.x = x; - this.y = y; - } + /** + * PlotId class (PlotId x,y values do not correspond to Block locations) + * + * @param x + * The plot x coordinate + * @param y + * The plot y coordinate + */ + public PlotId(final int x, final int y) { + this.x = x; + this.y = y; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PlotId other = (PlotId) obj; - return (((int) this.x == (int) other.x) && ((int) this.y == (int) other.y)); - } + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PlotId other = (PlotId) obj; + return ((this.x == other.x) && (this.y == other.y)); + } - @Override - public String toString() { - return this.x + ";" + this.y; - } + @Override + public String toString() { + return this.x + ";" + this.y; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + this.x; - result = (prime * result) + this.y; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + this.x; + result = (prime * result) + this.y; + return result; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotMain.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotMain.java index 9f0c18865..3d34510ad 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotMain.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotMain.java @@ -2,36 +2,12 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Main.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.Logger.LogLevel; -import com.intellectualcrafters.plot.commands.Auto; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.database.*; -import com.intellectualcrafters.plot.events.PlayerTeleportToPlotEvent; -import com.intellectualcrafters.plot.events.PlotDeleteEvent; -import com.intellectualcrafters.plot.generator.DefaultPlotManager; -import com.intellectualcrafters.plot.generator.DefaultPlotWorld; -import com.intellectualcrafters.plot.generator.WorldGenerator; -import com.intellectualcrafters.plot.listeners.*; -import com.intellectualcrafters.plot.uuid.PlotUUIDSaver; -import com.intellectualcrafters.plot.uuid.UUIDSaver; -import com.sk89q.worldedit.bukkit.WorldEditPlugin; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import me.confuser.barapi.BarAPI; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.*; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.java.JavaPlugin; - import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -39,150 +15,207 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.TimeUnit; +import me.confuser.barapi.BarAPI; +import net.milkbowl.vault.economy.Economy; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; + +import com.intellectualcrafters.plot.Logger.LogLevel; +import com.intellectualcrafters.plot.commands.Auto; +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.database.MySQL; +import com.intellectualcrafters.plot.database.PlotMeConverter; +import com.intellectualcrafters.plot.database.SQLManager; +import com.intellectualcrafters.plot.database.SQLite; +import com.intellectualcrafters.plot.events.PlayerTeleportToPlotEvent; +import com.intellectualcrafters.plot.events.PlotDeleteEvent; +import com.intellectualcrafters.plot.generator.DefaultPlotManager; +import com.intellectualcrafters.plot.generator.DefaultPlotWorld; +import com.intellectualcrafters.plot.generator.WorldGenerator; +import com.intellectualcrafters.plot.listeners.ForceFieldListener; +import com.intellectualcrafters.plot.listeners.PlayerEvents; +import com.intellectualcrafters.plot.listeners.PlotListener; +import com.intellectualcrafters.plot.listeners.PlotPlusListener; +import com.intellectualcrafters.plot.listeners.WorldEditListener; +import com.intellectualcrafters.plot.listeners.WorldGuardListener; +import com.intellectualcrafters.plot.uuid.PlotUUIDSaver; +import com.intellectualcrafters.plot.uuid.UUIDSaver; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; + /** * PlotMain class. + * * @author Citymonstret * @author Empire92 */ public class PlotMain extends JavaPlugin { - private static UUIDSaver uuidSaver; + private static UUIDSaver uuidSaver; - /** - * settings.properties - */ - public static File configFile; + /** + * settings.properties + */ + public static File configFile; /** * The main configuration file */ - public static YamlConfiguration config; + public static YamlConfiguration config; /** - * storage.properties - */ - public static File storageFile; + * storage.properties + */ + public static File storageFile; /** * Contains storage options */ - public static YamlConfiguration storage; - public static int storage_ver = 1; - /** - * translations.properties - */ - public static File translationsFile; + public static YamlConfiguration storage; + public static int storage_ver = 1; + /** + * translations.properties + */ + public static File translationsFile; /** * Contains all translations */ - public static YamlConfiguration translations; - public static int translations_ver = 1; - /** - * MySQL Object - */ - private static MySQL mySQL; - /** - * MySQL Connection - */ - public static Connection connection; - /** - * WorldEdit object - */ - public static WorldEditPlugin worldEdit = null; - /** - * BarAPI object - */ - public static BarAPI barAPI = null; + public static YamlConfiguration translations; + public static int translations_ver = 1; + /** + * MySQL Object + */ + private static MySQL mySQL; + /** + * MySQL Connection + */ + public static Connection connection; + /** + * WorldEdit object + */ + public static WorldEditPlugin worldEdit = null; + /** + * BarAPI object + */ + public static BarAPI barAPI = null; - public static WorldGuardPlugin worldGuard = null; - public static WorldGuardListener worldGuardListener = null; + public static WorldGuardPlugin worldGuard = null; + public static WorldGuardListener worldGuardListener = null; - public static Economy economy; - public static boolean useEconomy = false; + public static Economy economy; + public static boolean useEconomy = false; - /** - * !!WorldGeneration!! - */ - @Override - public ChunkGenerator getDefaultWorldGenerator(String worldname, String id) { - return new WorldGenerator(worldname); - } + /** + * !!WorldGeneration!! + */ + @Override + public ChunkGenerator getDefaultWorldGenerator(final String worldname, final String id) { + return new WorldGenerator(worldname); + } - public static void checkForExpiredPlots() { - final JavaPlugin plugin = PlotMain.getMain(); - Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { - checkExpired(plugin, true); - } - }, 0l, 12 * 60 * 60 * 20l); - } + public static void checkForExpiredPlots() { + final JavaPlugin plugin = PlotMain.getMain(); + Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { + @Override + public void run() { + checkExpired(plugin, true); + } + }, 0l, 12 * 60 * 60 * 20l); + } - /** - * Check a range of permissions e.g. 'plots.plot.<0-100>'
    - * Returns highest integer in range. - * - * @param player to check - * @param stub to check - * @param range tp check - * @return permitted range - */ - public static int hasPermissionRange(Player player, String stub, int range) { - if (player==null || player.isOp()) { + /** + * Check a range of permissions e.g. 'plots.plot.<0-100>'
    + * Returns highest integer in range. + * + * @param player + * to check + * @param stub + * to check + * @param range + * tp check + * @return permitted range + */ + public static int hasPermissionRange(final Player player, final String stub, final int range) { + if ((player == null) || player.isOp()) { return Integer.MAX_VALUE; } if (player.hasPermission(stub + ".*")) { return Integer.MAX_VALUE; } - for (int i = range; i > 0; i--) { - if (player.hasPermission(stub + "." + i)) { - return i; - } - } - return 0; - } + for (int i = range; i > 0; i--) { + if (player.hasPermission(stub + "." + i)) { + return i; + } + } + return 0; + } - /** - * Check a player for a permission
    - * - Op has all permissions
    - * - checks for '*' nodes - * - * @param player to check - * @param perms to check - * @return true of player has permissions - */ + /** + * Check a player for a permission
    + * - Op has all permissions
    + * - checks for '*' nodes + * + * @param player + * to check + * @param perms + * to check + * @return true of player has permissions + */ @SuppressWarnings("unused") - public static boolean hasPermissions(Player player, String[] perms) { - // Assumes null player is console. - if (player==null || player.isOp()) { - return true; - } - for (String perm : perms) { - boolean hasperm = false; - if (player.hasPermission(perm)) { - hasperm = true; - } - else { - String[] nodes = perm.split("\\."); - StringBuilder n = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - n.append(nodes[i]).append("."); - if (player.hasPermission(n + "*")) { - hasperm = true; - break; - } - } - } - if (!hasperm) { - return false; - } - } + public static boolean hasPermissions(final Player player, final String[] perms) { + // Assumes null player is console. + if ((player == null) || player.isOp()) { + return true; + } + for (final String perm : perms) { + boolean hasperm = false; + if (player.hasPermission(perm)) { + hasperm = true; + } + else { + final String[] nodes = perm.split("\\."); + final StringBuilder n = new StringBuilder(); + for (int i = 0; i < (nodes.length - 1); i++) { + n.append(nodes[i]).append("."); + if (player.hasPermission(n + "*")) { + hasperm = true; + break; + } + } + } + if (!hasperm) { + return false; + } + } - return true; - } + return true; + } - public static void setUUIDSaver(UUIDSaver saver) { + public static void setUUIDSaver(final UUIDSaver saver) { uuidSaver = saver; } @@ -190,789 +223,786 @@ public class PlotMain extends JavaPlugin { return uuidSaver; } - /** - * Check a player for a permission
    - * - Op has all permissions
    - * - checks for '*' nodes - * - * @param player to check - * @param perm to check - * @return true if player has the permission - */ - public static boolean hasPermission(Player player, String perm) { - if (player==null || player.isOp()) { - return true; - } - if (player.hasPermission(perm)) { - return true; - } - String[] nodes = perm.split("\\."); - StringBuilder n = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - n.append(nodes[i]).append("."); - if (player.hasPermission(n + "*")) { - return true; - } - } + /** + * Check a player for a permission
    + * - Op has all permissions
    + * - checks for '*' nodes + * + * @param player + * to check + * @param perm + * to check + * @return true if player has the permission + */ + public static boolean hasPermission(final Player player, final String perm) { + if ((player == null) || player.isOp()) { + return true; + } + if (player.hasPermission(perm)) { + return true; + } + final String[] nodes = perm.split("\\."); + final StringBuilder n = new StringBuilder(); + for (int i = 0; i < (nodes.length - 1); i++) { + n.append(nodes[i]).append("."); + if (player.hasPermission(n + "*")) { + return true; + } + } - return false; - } + return false; + } - /** - * List of all plots - * DO NOT USE EXCEPT FOR DATABASE PURPOSES - */ - private static LinkedHashMap> plots; - /** - * All loaded plot worlds - */ - private static HashMap worlds = new HashMap<>(); - private static HashMap managers = new HashMap<>(); + /** + * List of all plots + * DO NOT USE EXCEPT FOR DATABASE PURPOSES + */ + private static LinkedHashMap> plots; + /** + * All loaded plot worlds + */ + private static HashMap worlds = new HashMap<>(); + private static HashMap managers = new HashMap<>(); - /** - * Get all plots - * - * @return HashMap containing the plot ID and the plot object. - */ + /** + * Get all plots + * + * @return HashMap containing the plot ID and the plot object. + */ public static Set getPlots() { - ArrayList myplots = new ArrayList<>(); - for (HashMap world : plots.values()) { + final ArrayList myplots = new ArrayList<>(); + for (final HashMap world : plots.values()) { myplots.addAll(world.values()); } return new HashSet<>(myplots); } - public static LinkedHashSet getPlotsSorted() { - ArrayList myplots = new ArrayList<>(); - for (HashMap world : plots.values()) { - myplots.addAll(world.values()); - } - return new LinkedHashSet<>(myplots); - } + public static LinkedHashSet getPlotsSorted() { + final ArrayList myplots = new ArrayList<>(); + for (final HashMap world : plots.values()) { + myplots.addAll(world.values()); + } + return new LinkedHashSet<>(myplots); + } - /** - * @param player player - * @return Set Containing the players plots - */ - public static Set getPlots(Player player) { - UUID uuid = player.getUniqueId(); - ArrayList myplots = new ArrayList<>(); - for (HashMap world : plots.values()) { - for (Plot plot : world.values()) { - if (plot.hasOwner()) { - if (plot.getOwner().equals(uuid)) { - myplots.add(plot); - } - } - } - } - return new HashSet<>(myplots); - } + /** + * @param player + * player + * @return Set Containing the players plots + */ + public static Set getPlots(final Player player) { + final UUID uuid = player.getUniqueId(); + final ArrayList myplots = new ArrayList<>(); + for (final HashMap world : plots.values()) { + for (final Plot plot : world.values()) { + if (plot.hasOwner()) { + if (plot.getOwner().equals(uuid)) { + myplots.add(plot); + } + } + } + } + return new HashSet<>(myplots); + } - /** - * @param world plot world - * @param player plot owner - * @return players plots - */ - public static Set getPlots(World world, Player player) { - UUID uuid = player.getUniqueId(); - ArrayList myplots = new ArrayList(); - for (Plot plot : getPlots(world).values()) { - if (plot.hasOwner()) { - if (plot.getOwner().equals(uuid)) { - myplots.add(plot); - } - } - } - return new HashSet(myplots); - } - - public static HashMap getPlots(String world) { + /** + * @param world + * plot world + * @param player + * plot owner + * @return players plots + */ + public static Set getPlots(final World world, final Player player) { + final UUID uuid = player.getUniqueId(); + final ArrayList myplots = new ArrayList(); + for (final Plot plot : getPlots(world).values()) { + if (plot.hasOwner()) { + if (plot.getOwner().equals(uuid)) { + myplots.add(plot); + } + } + } + return new HashSet(myplots); + } + + public static HashMap getPlots(final String world) { if (plots.containsKey(world)) { return plots.get(world); } return new HashMap(); } - /** - * @param world plot world - * @return plots in world - */ - public static HashMap getPlots(World world) { - if (plots.containsKey(world.getName())) { - return plots.get(world.getName()); - } - return new HashMap(); - } + /** + * @param world + * plot world + * @return plots in world + */ + public static HashMap getPlots(final World world) { + if (plots.containsKey(world.getName())) { + return plots.get(world.getName()); + } + return new HashMap(); + } - /** - * get all plot worlds - */ - public static String[] getPlotWorlds() { - return (worlds.keySet().toArray(new String[0])); - } + /** + * get all plot worlds + */ + public static String[] getPlotWorlds() { + return (worlds.keySet().toArray(new String[0])); + } - /** - * @return plots worlds - */ - public static String[] getPlotWorldsString() { - return plots.keySet().toArray(new String[0]); - } + /** + * @return plots worlds + */ + public static String[] getPlotWorldsString() { + return plots.keySet().toArray(new String[0]); + } - /** - * @param world plotworld(?) + /** + * @param world + * plotworld(?) * @return true if the world is a plotworld */ - public static boolean isPlotWorld(World world) { + public static boolean isPlotWorld(final World world) { return (worlds.containsKey(world.getName())); } - + /** - * @param world plotworld(?) + * @param world + * plotworld(?) * @return true if the world is a plotworld */ - public static boolean isPlotWorld(String world) { + public static boolean isPlotWorld(final String world) { return (worlds.containsKey(world)); } - /** - * @param world World to get manager for - * @return manager for world - */ - public static PlotManager getPlotManager(World world) { - if (managers.containsKey(world.getName())) { - return managers.get(world.getName()); - } - return null; - } + /** + * @param world + * World to get manager for + * @return manager for world + */ + public static PlotManager getPlotManager(final World world) { + if (managers.containsKey(world.getName())) { + return managers.get(world.getName()); + } + return null; + } - /** - * @param world - * @return - */ - public static PlotManager getPlotManager(String world) { - if (managers.containsKey(world)) { - return managers.get(world); - } - return null; - } + /** + * @param world + * @return + */ + public static PlotManager getPlotManager(final String world) { + if (managers.containsKey(world)) { + return managers.get(world); + } + return null; + } - /** - * @param world - * @return - */ - public static PlotWorld getWorldSettings(World world) { - if (worlds.containsKey(world.getName())) { - return worlds.get(world.getName()); - } - return null; - } + /** + * @param world + * @return + */ + public static PlotWorld getWorldSettings(final World world) { + if (worlds.containsKey(world.getName())) { + return worlds.get(world.getName()); + } + return null; + } - /** - * @param world - * @return - */ - public static PlotWorld getWorldSettings(String world) { - if (worlds.containsKey(world)) { - return worlds.get(world); - } - return null; - } + /** + * @param world + * @return + */ + public static PlotWorld getWorldSettings(final String world) { + if (worlds.containsKey(world)) { + return worlds.get(world); + } + return null; + } - /** - * @param world - * @return set containing the plots for a world - */ - public static Plot[] getWorldPlots(World world) { - return (plots.get(world.getName()).values().toArray(new Plot[0])); - } + /** + * @param world + * @return set containing the plots for a world + */ + public static Plot[] getWorldPlots(final World world) { + return (plots.get(world.getName()).values().toArray(new Plot[0])); + } - public static boolean removePlot(String world, PlotId id, boolean callEvent) { - if (callEvent) { - PlotDeleteEvent event = new PlotDeleteEvent(world, id); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - return false; - } - } - plots.get(world).remove(id); - return true; - } + public static boolean removePlot(final String world, final PlotId id, final boolean callEvent) { + if (callEvent) { + final PlotDeleteEvent event = new PlotDeleteEvent(world, id); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + return false; + } + } + plots.get(world).remove(id); + return true; + } - /** - * Replace the plot object with an updated version - * - * @param plot - * plot object - */ - public static void updatePlot(Plot plot) { - String world = plot.world; - if (!plots.containsKey(world)) { - plots.put(world, new HashMap()); - } - plot.hasChanged = true; - plots.get(world).put(plot.id, plot); - } + /** + * Replace the plot object with an updated version + * + * @param plot + * plot object + */ + public static void updatePlot(final Plot plot) { + final String world = plot.world; + if (!plots.containsKey(world)) { + plots.put(world, new HashMap()); + } + plot.hasChanged = true; + plots.get(world).put(plot.id, plot); + } - /** - * TODO: Implement better system The whole point of this system is to - * recycle old plots
    - * So why not just allow users to claim old plots, and try to hide the fact - * that the are owned.
    - *
    - * Reduce amount of expired plots:
    - * - On /plot
    - * auto
    - * - allow claiming of old plot, clear it so the user doesn't know
    - * - On /plot info,
    - * - show that the plot is expired and allowed to be claimed Have the task - * run less often:
    - * - Run the task when there are very little, or no players online (great - * for small servers)
    - * - Run the task at startup (also only useful for small servers)
    - * Also, in terms of faster code:
    - * - Have an array of plots, sorted by expiry time.
    - * - Add new plots to the end.
    - * - The task then only needs to go through the first few plots - * - * @param plugin - * Plugin - * @param async - * Call async? - */ - private static void checkExpired(JavaPlugin plugin, boolean async) { - if (async) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { - @Override - public void run() { - for (String world : getPlotWorldsString()) { - if (plots.containsKey(world)) { - - ArrayList toDeletePlot = new ArrayList(); - - for (Plot plot : plots.get(world).values()) { - if (plot.owner == null) { - continue; - } - long lastPlayed = getLastPlayed(plot.owner); - if (lastPlayed == 0) { - continue; - } - long compared = System.currentTimeMillis() - lastPlayed; - if (TimeUnit.MILLISECONDS.toDays(compared) >= Settings.AUTO_CLEAR_DAYS) { - PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - } - else { - toDeletePlot.add(plot); - } - } - } - for (Plot plot: toDeletePlot) { - World worldobj = Bukkit.getWorld(world); - PlotHelper.clear(worldobj, plot); - PlotHelper.removeSign(worldobj, plot); + /** + * TODO: Implement better system The whole point of this system is to + * recycle old plots
    + * So why not just allow users to claim old plots, and try to hide the fact + * that the are owned.
    + *
    + * Reduce amount of expired plots:
    + * - On /plot
    + * auto
    + * - allow claiming of old plot, clear it so the user doesn't know
    + * - On /plot info,
    + * - show that the plot is expired and allowed to be claimed Have the task + * run less often:
    + * - Run the task when there are very little, or no players online (great + * for small servers)
    + * - Run the task at startup (also only useful for small servers)
    + * Also, in terms of faster code:
    + * - Have an array of plots, sorted by expiry time.
    + * - Add new plots to the end.
    + * - The task then only needs to go through the first few plots + * + * @param plugin + * Plugin + * @param async + * Call async? + */ + private static void checkExpired(final JavaPlugin plugin, final boolean async) { + if (async) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + for (final String world : getPlotWorldsString()) { + if (plots.containsKey(world)) { + + final ArrayList toDeletePlot = new ArrayList(); + + for (final Plot plot : plots.get(world).values()) { + if (plot.owner == null) { + continue; + } + final long lastPlayed = getLastPlayed(plot.owner); + if (lastPlayed == 0) { + continue; + } + final long compared = System.currentTimeMillis() - lastPlayed; + if (TimeUnit.MILLISECONDS.toDays(compared) >= Settings.AUTO_CLEAR_DAYS) { + final PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + } + else { + toDeletePlot.add(plot); + } + } + } + for (final Plot plot : toDeletePlot) { + final World worldobj = Bukkit.getWorld(world); + PlotHelper.clear(worldobj, plot); + PlotHelper.removeSign(worldobj, plot); DBFunc.delete(world, plot); removePlot(world, plot.id, true); - if (Math.abs(plot.id.x) 0) { - Broadcast(C.ENABLED); - } + if (C.ENABLED.s().length() > 0) { + Broadcast(C.ENABLED); + } // Use mysql? - if (Settings.DB.USE_MYSQL) { - DBFunc.dbManager = new SQLManager(); - try { - mySQL = - new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); - connection = mySQL.openConnection(); - { - DatabaseMetaData meta = connection.getMetaData(); - ResultSet res = meta.getTables(null, null, Settings.DB.PREFIX + "plot", null); - if (!res.next()) { - DBFunc.createTables("mysql", true); - } - else { - res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_trusted", null); - if (!res.next()) { - DBFunc.createTables("mysql", false); - } - else { - res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_ratings", null); - if (!res.next()) { - DBFunc.createTables("mysql", false); - } - } - } - } - } - catch (Exception e) { - Logger.add(LogLevel.DANGER, "MySQL connection failed."); - sendConsoleSenderMessage("&c[Plots] MySQL is not setup correctly. The plugin will disable itself."); - if (config==null || config.getBoolean("debug")) { - sendConsoleSenderMessage("&d==== Here is an ugly stacktrace if you are interested in those things ===="); - e.printStackTrace(); - sendConsoleSenderMessage("&d==== End of stacktrace ===="); - sendConsoleSenderMessage("&6Please go to the PlotSquared 'storage.yml' and configure MySQL correctly."); - } - Bukkit.getPluginManager().disablePlugin(this); - return; - } - plots = DBFunc.getPlots(); + if (Settings.DB.USE_MYSQL) { + DBFunc.dbManager = new SQLManager(); + try { + mySQL = new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); + connection = mySQL.openConnection(); + { + final DatabaseMetaData meta = connection.getMetaData(); + ResultSet res = meta.getTables(null, null, Settings.DB.PREFIX + "plot", null); + if (!res.next()) { + DBFunc.createTables("mysql", true); + } + else { + res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_trusted", null); + if (!res.next()) { + DBFunc.createTables("mysql", false); + } + else { + res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_ratings", null); + if (!res.next()) { + DBFunc.createTables("mysql", false); + } + } + } + } + } + catch (final Exception e) { + Logger.add(LogLevel.DANGER, "MySQL connection failed."); + sendConsoleSenderMessage("&c[Plots] MySQL is not setup correctly. The plugin will disable itself."); + if ((config == null) || config.getBoolean("debug")) { + sendConsoleSenderMessage("&d==== Here is an ugly stacktrace if you are interested in those things ===="); + e.printStackTrace(); + sendConsoleSenderMessage("&d==== End of stacktrace ===="); + sendConsoleSenderMessage("&6Please go to the PlotSquared 'storage.yml' and configure MySQL correctly."); + } + Bukkit.getPluginManager().disablePlugin(this); + return; + } + plots = DBFunc.getPlots(); - } + } // TODO: Implement mongo - else - if (Settings.DB.USE_MONGO) { -// DBFunc.dbManager = new MongoManager(); - sendConsoleSenderMessage(C.PREFIX.s() + "MongoDB is not yet implemented"); - } - else - if (Settings.DB.USE_SQLITE) { - DBFunc.dbManager = new SQLManager(); - try { - connection = new SQLite(this, Settings.DB.SQLITE_DB + ".db").openConnection(); - { - DatabaseMetaData meta = connection.getMetaData(); - ResultSet res = meta.getTables(null, null, Settings.DB.PREFIX + "plot", null); - if (!res.next()) { - DBFunc.createTables("sqlite", true); - } - else { - res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_trusted", null); - if (!res.next()) { - DBFunc.createTables("sqlite", false); - } - else { - res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_ratings", null); - if (!res.next()) { - DBFunc.createTables("sqlite", false); - } - } - } - } - } - catch (Exception e) { - Logger.add(LogLevel.DANGER, "SQLite connection failed"); - sendConsoleSenderMessage(C.PREFIX.s() - + "&cFailed to open SQLite connection. The plugin will disable itself."); - sendConsoleSenderMessage("&9==== Here is an ugly stacktrace, if you are interested in those things ==="); - e.printStackTrace(); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - plots = DBFunc.getPlots(); - } - else { - Logger.add(LogLevel.DANGER, "No storage type is set."); - sendConsoleSenderMessage(C.PREFIX + "&cNo storage type is set!"); - getServer().getPluginManager().disablePlugin(this); - return; - } - if (getServer().getPluginManager().getPlugin("PlotMe") != null) { - try { - new PlotMeConverter(this).runAsync(); - } - catch (Exception e) { - e.printStackTrace(); - } - } + else if (Settings.DB.USE_MONGO) { + // DBFunc.dbManager = new MongoManager(); + sendConsoleSenderMessage(C.PREFIX.s() + "MongoDB is not yet implemented"); + } + else if (Settings.DB.USE_SQLITE) { + DBFunc.dbManager = new SQLManager(); + try { + connection = new SQLite(this, Settings.DB.SQLITE_DB + ".db").openConnection(); + { + final DatabaseMetaData meta = connection.getMetaData(); + ResultSet res = meta.getTables(null, null, Settings.DB.PREFIX + "plot", null); + if (!res.next()) { + DBFunc.createTables("sqlite", true); + } + else { + res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_trusted", null); + if (!res.next()) { + DBFunc.createTables("sqlite", false); + } + else { + res = meta.getTables(null, null, Settings.DB.PREFIX + "plot_ratings", null); + if (!res.next()) { + DBFunc.createTables("sqlite", false); + } + } + } + } + } + catch (final Exception e) { + Logger.add(LogLevel.DANGER, "SQLite connection failed"); + sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to open SQLite connection. The plugin will disable itself."); + sendConsoleSenderMessage("&9==== Here is an ugly stacktrace, if you are interested in those things ==="); + e.printStackTrace(); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + plots = DBFunc.getPlots(); + } + else { + Logger.add(LogLevel.DANGER, "No storage type is set."); + sendConsoleSenderMessage(C.PREFIX + "&cNo storage type is set!"); + getServer().getPluginManager().disablePlugin(this); + return; + } + if (getServer().getPluginManager().getPlugin("PlotMe") != null) { + try { + new PlotMeConverter(this).runAsync(); + } + catch (final Exception e) { + e.printStackTrace(); + } + } - MainCommand command = new MainCommand(); - getCommand("plots").setExecutor(command); - getCommand("plots").setAliases(new ArrayList() { - { - add("p"); + final MainCommand command = new MainCommand(); + getCommand("plots").setExecutor(command); + getCommand("plots").setAliases(new ArrayList() { + { + add("p"); add("ps"); - add("plotme"); - add("plot"); - } - }); - //getCommand("plots").setTabCompleter(command); - getServer().getPluginManager().registerEvents(new PlayerEvents(), this); + add("plotme"); + add("plot"); + } + }); + // getCommand("plots").setTabCompleter(command); + getServer().getPluginManager().registerEvents(new PlayerEvents(), this); PlotPlusListener.startRunnable(this); getServer().getPluginManager().registerEvents(new PlotPlusListener(), this); getServer().getPluginManager().registerEvents(new ForceFieldListener(this), this); defaultFlags(); + if (getServer().getPluginManager().getPlugin("BarAPI") != null) { + barAPI = (BarAPI) getServer().getPluginManager().getPlugin("BarAPI"); + } + if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { + worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); - if (getServer().getPluginManager().getPlugin("BarAPI") != null) { - barAPI = (BarAPI) getServer().getPluginManager().getPlugin("BarAPI"); - } - if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { - worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); - - String version = worldEdit.getDescription().getVersion(); - if (version!=null && version.startsWith("5.")) { - PlotMain.sendConsoleSenderMessage("&cPlease update to WorldEdit 6 for improved stability and additional features:\nhttp://builds.enginehub.org/job/worldedit"); - } - else { - getServer().getPluginManager().registerEvents(new WorldEditListener(), this); - } - } - if (Settings.WORLDGUARD) { - if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { - worldGuard = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); - worldGuardListener = new WorldGuardListener(this); - getServer().getPluginManager().registerEvents(worldGuardListener, this); - } - } - if (Settings.AUTO_CLEAR) { - checkExpired(PlotMain.getMain(), true); - checkForExpiredPlots(); - } - if (getServer().getPluginManager().getPlugin("Vault") != null && getServer().getPluginManager().getPlugin("Vault").isEnabled()) { - RegisteredServiceProvider economyProvider = - getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - } - } - useEconomy = (economy != null); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L); + final String version = worldEdit.getDescription().getVersion(); + if ((version != null) && version.startsWith("5.")) { + PlotMain.sendConsoleSenderMessage("&cPlease update to WorldEdit 6 for improved stability and additional features:\nhttp://builds.enginehub.org/job/worldedit"); + } + else { + getServer().getPluginManager().registerEvents(new WorldEditListener(), this); + } + } + if (Settings.WORLDGUARD) { + if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { + worldGuard = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); + worldGuardListener = new WorldGuardListener(this); + getServer().getPluginManager().registerEvents(worldGuardListener, this); + } + } + if (Settings.AUTO_CLEAR) { + checkExpired(PlotMain.getMain(), true); + checkForExpiredPlots(); + } + if ((getServer().getPluginManager().getPlugin("Vault") != null) && getServer().getPluginManager().getPlugin("Vault").isEnabled()) { + final RegisteredServiceProvider economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + economy = economyProvider.getProvider(); + } + } + useEconomy = (economy != null); + getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L); - try { - new SetBlockFast(); - PlotHelper.canSetFast = true; - } - catch (Exception e) { - PlotHelper.canSetFast = false; - } + try { + new SetBlockFast(); + PlotHelper.canSetFast = true; + } + catch (final Exception e) { + PlotHelper.canSetFast = false; + } - //Setup version + downloads, will not be updated... maybe setup runnable? TODO Let jesse decide... + // Setup version + downloads, will not be updated... maybe setup + // runnable? TODO Let jesse decide... com.intellectualcrafters.plot.commands.plugin.setup(this); setUUIDSaver(new PlotUUIDSaver()); - getUUIDSaver().globalPopulate(); - //UUIDHandler.startFetch(this); - } + getUUIDSaver().globalPopulate(); + // UUIDHandler.startFetch(this); + } - /** - * Get MySQL Connection - * @return connection MySQL Connection. - */ - public static Connection getConnection() { - return connection; - } + /** + * Get MySQL Connection + * + * @return connection MySQL Connection. + */ + public static Connection getConnection() { + return connection; + } - /** .. */ + /** .. */ - // Old Stuff - /* - * private static boolean checkForUpdate() throws IOException { URL call = - * new URL(Settings.Update.VERSION_URL); InputStream stream = - * call.openStream(); BufferedReader reader = new BufferedReader(new - * InputStreamReader(stream)); String latest = reader.readLine(); - * reader.close(); return - * !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); } - * private static String getNextUpdateString() throws IOException { URL call - * = new URL(Settings.Update.VERSION_URL); InputStream stream = - * call.openStream(); BufferedReader reader = new BufferedReader(new - * InputStreamReader(stream)); return reader.readLine(); } private static - * void update() throws IOException { sendConsoleSenderMessage(C.PREFIX.s() - * + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() + - * "&c&l, Current Update: &6&l" + - * getPlotMain().getDescription().getVersion()); } - */ + // Old Stuff + /* + * private static boolean checkForUpdate() throws IOException { URL call = + * new URL(Settings.Update.VERSION_URL); InputStream stream = + * call.openStream(); BufferedReader reader = new BufferedReader(new + * InputStreamReader(stream)); String latest = reader.readLine(); + * reader.close(); return + * !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); } + * private static String getNextUpdateString() throws IOException { URL call + * = new URL(Settings.Update.VERSION_URL); InputStream stream = + * call.openStream(); BufferedReader reader = new BufferedReader(new + * InputStreamReader(stream)); return reader.readLine(); } private static + * void update() throws IOException { sendConsoleSenderMessage(C.PREFIX.s() + * + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() + + * "&c&l, Current Update: &6&l" + + * getPlotMain().getDescription().getVersion()); } + */ - /** - * Send a message to the console. - * - * @param string - * message - */ - public static void sendConsoleSenderMessage(String string) { - if (getMain().getServer().getConsoleSender() == null) { - System.out.println(ChatColor.stripColor(ConsoleColors.fromString(string))); - } - else { - getMain().getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string)); - } - } + /** + * Send a message to the console. + * + * @param string + * message + */ + public static void sendConsoleSenderMessage(final String string) { + if (getMain().getServer().getConsoleSender() == null) { + System.out.println(ChatColor.stripColor(ConsoleColors.fromString(string))); + } + else { + getMain().getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string)); + } + } - public static boolean teleportPlayer(Player player, Location from, Plot plot) { - PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, from, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - Location location = PlotHelper.getPlotHome(Bukkit.getWorld(plot.world), plot); - if ((location.getBlockX() >= 29999999) || (location.getBlockX() <= -29999999) - || (location.getBlockZ() >= 299999999) || (location.getBlockZ() <= -29999999)) { - event.setCancelled(true); - return false; - } - player.teleport(location); - PlayerFunctions.sendMessage(player, C.TELEPORTED_TO_PLOT); - } - return event.isCancelled(); - } + public static boolean teleportPlayer(final Player player, final Location from, final Plot plot) { + final PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, from, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + final Location location = PlotHelper.getPlotHome(Bukkit.getWorld(plot.world), plot); + if ((location.getBlockX() >= 29999999) || (location.getBlockX() <= -29999999) || (location.getBlockZ() >= 299999999) || (location.getBlockZ() <= -29999999)) { + event.setCancelled(true); + return false; + } + player.teleport(location); + PlayerFunctions.sendMessage(player, C.TELEPORTED_TO_PLOT); + } + return event.isCancelled(); + } - /** - * Send a message to the console - * - * @param c - * message - */ - @SuppressWarnings("unused") - public static void sendConsoleSenderMessage(C c) { - sendConsoleSenderMessage(c.s()); - } + /** + * Send a message to the console + * + * @param c + * message + */ + @SuppressWarnings("unused") + public static void sendConsoleSenderMessage(final C c) { + sendConsoleSenderMessage(c.s()); + } - /** - * Broadcast publicly - * - * @param c - * message - */ - public static void Broadcast(C c) { - Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())); - } + /** + * Broadcast publicly + * + * @param c + * message + */ + public static void Broadcast(final C c) { + Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())); + } - /** - * Returns the main class. - * - * @return (this class) - */ - public static PlotMain getMain() { - return JavaPlugin.getPlugin(PlotMain.class); - } + /** + * Returns the main class. + * + * @return (this class) + */ + public static PlotMain getMain() { + return JavaPlugin.getPlugin(PlotMain.class); + } - /** - * Broadcast a message to all admins - * - * @param c - * message - */ - public static void BroadcastWithPerms(C c) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(player, c); - } - } - System.out.println(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s()))); - } + /** + * Broadcast a message to all admins + * + * @param c + * message + */ + public static void BroadcastWithPerms(final C c) { + for (final Player player : Bukkit.getOnlinePlayers()) { + if (player.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(player, c); + } + } + System.out.println(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s()))); + } - public static void reloadTranslations() throws IOException { - translations = YamlConfiguration.loadConfiguration(translationsFile); - } + public static void reloadTranslations() throws IOException { + translations = YamlConfiguration.loadConfiguration(translationsFile); + } - public static long getLastPlayed(UUID uuid) { - if (uuid == null) { - return 0; - } - OfflinePlayer player; - if (((player = Bukkit.getOfflinePlayer(uuid)) == null) || !player.hasPlayedBefore()) { - return 0; - } - return player.getLastPlayed(); - } + public static long getLastPlayed(final UUID uuid) { + if (uuid == null) { + return 0; + } + OfflinePlayer player; + if (((player = Bukkit.getOfflinePlayer(uuid)) == null) || !player.hasPlayedBefore()) { + return 0; + } + return player.getLastPlayed(); + } - /** - * Load configuration files - */ - @SuppressWarnings("deprecation") - public static void configs() { - File folder = new File(getMain().getDataFolder() + File.separator + "config"); - if (!folder.exists() && !folder.mkdirs()) { - sendConsoleSenderMessage(C.PREFIX.s() - + "&cFailed to create the /plugins/config folder. Please create it manually."); - } - try { - configFile = - new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "settings.yml"); - if (!configFile.exists()) { - configFile.createNewFile(); - } - config = YamlConfiguration.loadConfiguration(configFile); - setupConfig(); - } - catch (Exception err_trans) { - Logger.add(LogLevel.DANGER, "Failed to save settings.yml"); - System.out.println("Failed to save settings.yml"); - } - try { - storageFile = - new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "storage.yml"); - if (!storageFile.exists()) { - storageFile.createNewFile(); - } - storage = YamlConfiguration.loadConfiguration(storageFile); - setupStorage(); - } - catch (Exception err_trans) { - Logger.add(LogLevel.DANGER, "Failed to save storage.yml"); - System.out.println("Failed to save storage.yml"); - } - try { - translationsFile = - new File(getMain().getDataFolder() + File.separator + "config" + File.separator - + "translations.yml"); - if (!translationsFile.exists()) { - translationsFile.createNewFile(); - } - translations = YamlConfiguration.loadConfiguration(translationsFile); - setupTranslations(); - } - catch (Exception err_trans) { - Logger.add(LogLevel.DANGER, "Failed to save translations.yml"); - System.out.println("Failed to save translations.yml"); - } + /** + * Load configuration files + */ + @SuppressWarnings("deprecation") + public static void configs() { + final File folder = new File(getMain().getDataFolder() + File.separator + "config"); + if (!folder.exists() && !folder.mkdirs()) { + sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create the /plugins/config folder. Please create it manually."); + } + try { + configFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "settings.yml"); + if (!configFile.exists()) { + configFile.createNewFile(); + } + config = YamlConfiguration.loadConfiguration(configFile); + setupConfig(); + } + catch (final Exception err_trans) { + Logger.add(LogLevel.DANGER, "Failed to save settings.yml"); + System.out.println("Failed to save settings.yml"); + } + try { + storageFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "storage.yml"); + if (!storageFile.exists()) { + storageFile.createNewFile(); + } + storage = YamlConfiguration.loadConfiguration(storageFile); + setupStorage(); + } + catch (final Exception err_trans) { + Logger.add(LogLevel.DANGER, "Failed to save storage.yml"); + System.out.println("Failed to save storage.yml"); + } + try { + translationsFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "translations.yml"); + if (!translationsFile.exists()) { + translationsFile.createNewFile(); + } + translations = YamlConfiguration.loadConfiguration(translationsFile); + setupTranslations(); + } + catch (final Exception err_trans) { + Logger.add(LogLevel.DANGER, "Failed to save translations.yml"); + System.out.println("Failed to save translations.yml"); + } - try { - config.save(configFile); - storage.save(storageFile); - translations.save(translationsFile); - } - catch (IOException e) { - Logger.add(LogLevel.DANGER, "Configuration file saving failed"); - e.printStackTrace(); - } - { - Settings.DB.USE_MYSQL = storage.getBoolean("mysql.use"); - Settings.DB.USER = storage.getString("mysql.user"); - Settings.DB.PASSWORD = storage.getString("mysql.password"); - Settings.DB.HOST_NAME = storage.getString("mysql.host"); - Settings.DB.PORT = storage.getString("mysql.port"); - Settings.DB.DATABASE = storage.getString("mysql.database"); - Settings.DB.USE_SQLITE = storage.getBoolean("sqlite.use"); - Settings.DB.SQLITE_DB = storage.getString("sqlite.db"); + try { + config.save(configFile); + storage.save(storageFile); + translations.save(translationsFile); + } + catch (final IOException e) { + Logger.add(LogLevel.DANGER, "Configuration file saving failed"); + e.printStackTrace(); + } + { + Settings.DB.USE_MYSQL = storage.getBoolean("mysql.use"); + Settings.DB.USER = storage.getString("mysql.user"); + Settings.DB.PASSWORD = storage.getString("mysql.password"); + Settings.DB.HOST_NAME = storage.getString("mysql.host"); + Settings.DB.PORT = storage.getString("mysql.port"); + Settings.DB.DATABASE = storage.getString("mysql.database"); + Settings.DB.USE_SQLITE = storage.getBoolean("sqlite.use"); + Settings.DB.SQLITE_DB = storage.getString("sqlite.db"); Settings.DB.PREFIX = storage.getString("prefix"); - } - { - Settings.METRICS = config.getBoolean("metrics"); - // Web - // Web.ENABLED = config.getBoolean("web.enabled"); - // Web.PORT = config.getInt("web.port"); + } + { + Settings.METRICS = config.getBoolean("metrics"); + // Web + // Web.ENABLED = config.getBoolean("web.enabled"); + // Web.PORT = config.getInt("web.port"); - Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); - Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); + Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); + Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); Settings.DELETE_PLOTS_ON_BAN = config.getBoolean("clear.on.ban"); Settings.API_URL = config.getString("api.location"); Settings.CUSTOM_API = config.getBoolean("api.custom"); - } - if (Settings.DEBUG) { - Map settings = new HashMap<>(); - settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); - settings.put("Use Metrics", "" + Settings.METRICS); + } + if (Settings.DEBUG) { + final Map settings = new HashMap<>(); + settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); + settings.put("Use Metrics", "" + Settings.METRICS); settings.put("Delete Plots On Ban", "" + Settings.DELETE_PLOTS_ON_BAN); - settings.put("Mob Pathfinding", "" + Settings.MOB_PATHFINDING); - settings.put("DB Mysql Enabled", "" + Settings.DB.USE_MYSQL); - settings.put("DB SQLite Enabled", "" + Settings.DB.USE_SQLITE); - settings.put("Auto Clear Enabled", "" + Settings.AUTO_CLEAR); - settings.put("Auto Clear Days", "" + Settings.AUTO_CLEAR_DAYS); + settings.put("Mob Pathfinding", "" + Settings.MOB_PATHFINDING); + settings.put("DB Mysql Enabled", "" + Settings.DB.USE_MYSQL); + settings.put("DB SQLite Enabled", "" + Settings.DB.USE_SQLITE); + settings.put("Auto Clear Enabled", "" + Settings.AUTO_CLEAR); + settings.put("Auto Clear Days", "" + Settings.AUTO_CLEAR_DAYS); settings.put("Schematics Save Path", "" + Settings.SCHEMATIC_SAVE_PATH); settings.put("API Location", "" + Settings.API_URL); - for (Entry setting : settings.entrySet()) { - sendConsoleSenderMessage(C.PREFIX.s() - + String.format("&cKey: &6%s&c, Value: &6%s", setting.getKey(), setting.getValue())); - } - } - } + for (final Entry setting : settings.entrySet()) { + sendConsoleSenderMessage(C.PREFIX.s() + String.format("&cKey: &6%s&c, Value: &6%s", setting.getKey(), setting.getValue())); + } + } + } - /** - * Kill all entities on roads - */ - @SuppressWarnings("deprecation") - public static void killAllEntities() { - Bukkit.getScheduler().scheduleSyncRepeatingTask(getMain(), new Runnable() { - Location location; + /** + * Kill all entities on roads + */ + @SuppressWarnings("deprecation") + public static void killAllEntities() { + Bukkit.getScheduler().scheduleSyncRepeatingTask(getMain(), new Runnable() { long ticked = 0l; - long error = 0l; + long error = 0l; { sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities started."); @@ -982,110 +1012,112 @@ public class PlotMain extends JavaPlugin { public void run() { if (this.ticked > 36000l) { this.ticked = 0l; - sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " - + this.error); + sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + this.error); this.error = 0l; } - for (String w : getPlotWorlds()) { + for (final String w : getPlotWorlds()) { getWorldSettings(w); - World world = Bukkit.getServer().getWorld(w); + final World world = Bukkit.getServer().getWorld(w); try { if (world.getLoadedChunks().length < 1) { continue; } - for (Chunk chunk : world.getLoadedChunks()) { - Entity[] entities = chunk.getEntities(); + for (final Chunk chunk : world.getLoadedChunks()) { + final Entity[] entities = chunk.getEntities(); for (int i = entities.length - 1; i >= 0; i--) { - Entity entity = entities[i]; - if ((entity instanceof Player) || PlayerEvents.isInPlot(entity.getLocation())) { + final Entity entity = entities[i]; + if ((entity instanceof Player) || PlotListener.isInPlot(entity.getLocation())) { continue; } entity.remove(); -// boolean tamed = false; -// if (Settings.MOB_PATHFINDING) { -// if (entity instanceof Tameable) { -// Tameable tameable = (Tameable) entity; -// if (tameable.isTamed()) { -// tamed = true; -// } -// } -// else -// if (entity instanceof LivingEntity) { -// LivingEntity livingEntity = ((LivingEntity) entity); -// if (livingEntity.getCustomName() != null) { -// tamed = true; -// } -// } -// if (!tamed) { -// entity.remove(); -// continue; -// } -// boolean found = false; -// int radius = 1; -// int dir = 0; -// int x = this.location.getBlockX(); -// int y = this.location.getBlockY(); -// int z = this.location.getBlockZ(); -// while (!found && (radius < 4)) { -// Location pos; -// switch (dir) { -// case 0: -// pos = new Location(world, x + radius, y, z); -// dir++; -// break; -// case 1: -// pos = new Location(world, x, y, z + radius); -// dir++; -// break; -// case 2: -// pos = new Location(world, x - radius, y, z); -// dir++; -// break; -// case 3: -// pos = new Location(world, x, y, z - radius); -// dir = 0; -// radius++; -// break; -// default: -// pos = this.location; -// break; -// -// } -// if (PlayerEvents.isInPlot(pos)) { -// entity.teleport(pos.add(0.5, 0, 0.5)); -// found = true; -// break; -// } -// } -// entity.teleport(this.location.subtract(this.location.getDirection().normalize().multiply(2))); -// } + // boolean tamed = false; + // if (Settings.MOB_PATHFINDING) { + // if (entity instanceof Tameable) { + // Tameable tameable = (Tameable) entity; + // if (tameable.isTamed()) { + // tamed = true; + // } + // } + // else + // if (entity instanceof LivingEntity) { + // LivingEntity livingEntity = ((LivingEntity) + // entity); + // if (livingEntity.getCustomName() != null) { + // tamed = true; + // } + // } + // if (!tamed) { + // entity.remove(); + // continue; + // } + // boolean found = false; + // int radius = 1; + // int dir = 0; + // int x = this.location.getBlockX(); + // int y = this.location.getBlockY(); + // int z = this.location.getBlockZ(); + // while (!found && (radius < 4)) { + // Location pos; + // switch (dir) { + // case 0: + // pos = new Location(world, x + radius, y, z); + // dir++; + // break; + // case 1: + // pos = new Location(world, x, y, z + radius); + // dir++; + // break; + // case 2: + // pos = new Location(world, x - radius, y, z); + // dir++; + // break; + // case 3: + // pos = new Location(world, x, y, z - radius); + // dir = 0; + // radius++; + // break; + // default: + // pos = this.location; + // break; + // + // } + // if (PlayerEvents.isInPlot(pos)) { + // entity.teleport(pos.add(0.5, 0, 0.5)); + // found = true; + // break; + // } + // } + // entity.teleport(this.location.subtract(this.location.getDirection().normalize().multiply(2))); + // } } } - } catch (Throwable e) { + } + catch (final Throwable e) { ++this.error; - } finally { + } + finally { ++this.ticked; } } } }, 2L, 2L); - } + } - /** - * SETUP: settings.yml - */ - private static void setupConfig() { - int config_ver = 1; + /** + * SETUP: settings.yml + */ + private static void setupConfig() { + final int config_ver = 1; config.set("version", config_ver); - Map options = new HashMap(); - options.put("auto_update", false); - options.put("worldguard.enabled", Settings.WORLDGUARD); - options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); - options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); - options.put("metrics", true); - options.put("debug", true); - options.put("clear.auto.enabled", false); - options.put("clear.auto.days", 365); + final Map options = new HashMap(); + options.put("auto_update", false); + options.put("worldguard.enabled", Settings.WORLDGUARD); + options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); + options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); + options.put("metrics", true); + options.put("debug", true); + options.put("clear.auto.enabled", false); + options.put("clear.auto.days", 365); options.put("clear.on.ban", false); options.put("max_plots", Settings.MAX_PLOTS); options.put("schematics.save_path", Settings.SCHEMATIC_SAVE_PATH); @@ -1093,186 +1125,185 @@ public class PlotMain extends JavaPlugin { options.put("api.custom", Settings.CUSTOM_API); options.put("titles", Settings.TITLES); - for (Entry node : options.entrySet()) { - if (!config.contains(node.getKey())) { - config.set(node.getKey(), node.getValue()); - } - } - Settings.DEBUG = config.getBoolean("debug"); - if (Settings.DEBUG) { - sendConsoleSenderMessage(C.PREFIX.s() + "&6Debug Mode Enabled (Default). Edit the config to turn this off."); - } - Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); - Settings.WORLDGUARD = config.getBoolean("worldguard.enabled"); - Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); - Settings.METRICS = config.getBoolean("metrics"); - Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); - Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); - Settings.TITLES = config.getBoolean("titles"); - Settings.MAX_PLOTS = config.getInt("max_plots"); + for (final Entry node : options.entrySet()) { + if (!config.contains(node.getKey())) { + config.set(node.getKey(), node.getValue()); + } + } + Settings.DEBUG = config.getBoolean("debug"); + if (Settings.DEBUG) { + sendConsoleSenderMessage(C.PREFIX.s() + "&6Debug Mode Enabled (Default). Edit the config to turn this off."); + } + Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); + Settings.WORLDGUARD = config.getBoolean("worldguard.enabled"); + Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); + Settings.METRICS = config.getBoolean("metrics"); + Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); + Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); + Settings.TITLES = config.getBoolean("titles"); + Settings.MAX_PLOTS = config.getInt("max_plots"); Settings.SCHEMATIC_SAVE_PATH = config.getString("schematics.save_path"); - } + } - public static void createConfiguration(PlotWorld plotworld) { - Map options = new HashMap(); + public static void createConfiguration(final PlotWorld plotworld) { + final Map options = new HashMap(); - for (ConfigurationNode setting : plotworld.getSettingNodes()) { - setting.getConstant(); - setting.getValue(); - } + for (final ConfigurationNode setting : plotworld.getSettingNodes()) { + setting.getConstant(); + setting.getValue(); + } - for (Entry node : options.entrySet()) { - if (!config.contains(node.getKey())) { - config.set(node.getKey(), node.getValue()); - } - } + for (final Entry node : options.entrySet()) { + if (!config.contains(node.getKey())) { + config.set(node.getKey(), node.getValue()); + } + } - try { - config.save(PlotMain.configFile); - } - catch (IOException e) { - PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save"); - } - } + try { + config.save(PlotMain.configFile); + } + catch (final IOException e) { + PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save"); + } + } - public static void loadWorld(String world, ChunkGenerator generator) { - if (getWorldSettings(world) != null) { - return; - } - Set worlds; - if (config.contains("worlds")) { - worlds = config.getConfigurationSection("worlds").getKeys(false); - } - else { - worlds = new HashSet(); - } - if (generator != null && generator instanceof PlotGenerator) { - sendConsoleSenderMessage(C.PREFIX.s() + "&aDetected world load for '" + world + "'."); - PlotGenerator plotgen = (PlotGenerator) generator; - PlotWorld plotworld = plotgen.getNewPlotWorld(world); - PlotManager manager = plotgen.getPlotManager(); + public static void loadWorld(final String world, final ChunkGenerator generator) { + if (getWorldSettings(world) != null) { + return; + } + Set worlds; + if (config.contains("worlds")) { + worlds = config.getConfigurationSection("worlds").getKeys(false); + } + else { + worlds = new HashSet(); + } + if ((generator != null) && (generator instanceof PlotGenerator)) { + sendConsoleSenderMessage(C.PREFIX.s() + "&aDetected world load for '" + world + "'."); + final PlotGenerator plotgen = (PlotGenerator) generator; + final PlotWorld plotworld = plotgen.getNewPlotWorld(world); + final PlotManager manager = plotgen.getPlotManager(); - if (!config.contains("worlds." + world)) { - config.createSection("worlds." + world); - } - - - plotworld.saveConfiguration(config.getConfigurationSection("worlds." + world)); - plotworld.loadDefaultConfiguration(config.getConfigurationSection("worlds." + world)); + if (!config.contains("worlds." + world)) { + config.createSection("worlds." + world); + } - try { - config.save(configFile); - } - catch (IOException e) { - e.printStackTrace(); - } + plotworld.saveConfiguration(config.getConfigurationSection("worlds." + world)); + plotworld.loadDefaultConfiguration(config.getConfigurationSection("worlds." + world)); - addPlotWorld(world, plotworld, manager); + try { + config.save(configFile); + } + catch (final IOException e) { + e.printStackTrace(); + } - } - else { - if (worlds.contains(world)) { - sendConsoleSenderMessage("&cWorld '" + world + "' in settings.yml is not using PlotSquared generator!"); + addPlotWorld(world, plotworld, manager); - PlotWorld plotworld = new DefaultPlotWorld(world); - PlotManager manager = new DefaultPlotManager(); + } + else { + if (worlds.contains(world)) { + sendConsoleSenderMessage("&cWorld '" + world + "' in settings.yml is not using PlotSquared generator!"); - if (!config.contains("worlds." + world)) { - config.createSection("worlds." + world); - } - plotworld.saveConfiguration(config.getConfigurationSection("worlds." + world)); + final PlotWorld plotworld = new DefaultPlotWorld(world); + final PlotManager manager = new DefaultPlotManager(); - plotworld.loadConfiguration(config.getConfigurationSection("worlds." + world)); + if (!config.contains("worlds." + world)) { + config.createSection("worlds." + world); + } + plotworld.saveConfiguration(config.getConfigurationSection("worlds." + world)); - try { - config.save(configFile); - } - catch (IOException e) { - e.printStackTrace(); - } + plotworld.loadConfiguration(config.getConfigurationSection("worlds." + world)); - addPlotWorld(world, plotworld, manager); - } - } - } + try { + config.save(configFile); + } + catch (final IOException e) { + e.printStackTrace(); + } - /** - * Adds an external world as a recognized PlotSquared world - The PlotWorld - * class created is based off the configuration in the settings.yml - Do not - * use this method unless the required world is preconfigured in the - * settings.yml - * - * @param world - */ - public static void loadWorld(World world) { - if (world == null) { - return; - } - ChunkGenerator generator = world.getGenerator(); - loadWorld(world.getName(), generator); - } + addPlotWorld(world, plotworld, manager); + } + } + } - /** - * SETUP: storage.properties - */ - private static void setupStorage() { - storage.set("version", storage_ver); - Map options = new HashMap(); - options.put("mysql.use", true); - options.put("sqlite.use", false); - options.put("sqlite.db", "storage"); - options.put("mysql.host", "localhost"); - options.put("mysql.port", "3306"); - options.put("mysql.user", "root"); - options.put("mysql.password", "password"); - options.put("mysql.database", "plot_db"); + /** + * Adds an external world as a recognized PlotSquared world - The PlotWorld + * class created is based off the configuration in the settings.yml - Do not + * use this method unless the required world is preconfigured in the + * settings.yml + * + * @param world + */ + public static void loadWorld(final World world) { + if (world == null) { + return; + } + final ChunkGenerator generator = world.getGenerator(); + loadWorld(world.getName(), generator); + } + + /** + * SETUP: storage.properties + */ + private static void setupStorage() { + storage.set("version", storage_ver); + final Map options = new HashMap(); + options.put("mysql.use", true); + options.put("sqlite.use", false); + options.put("sqlite.db", "storage"); + options.put("mysql.host", "localhost"); + options.put("mysql.port", "3306"); + options.put("mysql.user", "root"); + options.put("mysql.password", "password"); + options.put("mysql.database", "plot_db"); options.put("prefix", ""); - for (Entry node : options.entrySet()) { - if (!storage.contains(node.getKey())) { - storage.set(node.getKey(), node.getValue()); - } - } - } + for (final Entry node : options.entrySet()) { + if (!storage.contains(node.getKey())) { + storage.set(node.getKey(), node.getValue()); + } + } + } - /** - * SETUP: translations.properties - */ - public static void setupTranslations() { - translations.set("version", translations_ver); - for (C c : C.values()) { - if (!translations.contains(c.toString())) { - translations.set(c.toString(), c.s()); - } + /** + * SETUP: translations.properties + */ + public static void setupTranslations() { + translations.set("version", translations_ver); + for (final C c : C.values()) { + if (!translations.contains(c.toString())) { + translations.set(c.toString(), c.s()); + } - } - } + } + } - /** - * On unload - */ - @Override - public void onDisable() { - Logger.add(LogLevel.GENERAL, "Logger disabled"); - try { - Logger.write(); - } - catch (IOException e1) { - e1.printStackTrace(); - } - try { - connection.close(); - mySQL.closeConnection(); - } - catch (NullPointerException | SQLException e) { - if (connection != null) { - Logger.add(LogLevel.DANGER, "Could not close mysql connection"); - } - } - /* - * if(PlotWeb.PLOTWEB != null) { try { PlotWeb.PLOTWEB.stop(); } catch - * (Exception e) { e.printStackTrace(); } } - */ - } + /** + * On unload + */ + @Override + public void onDisable() { + Logger.add(LogLevel.GENERAL, "Logger disabled"); + try { + Logger.write(); + } + catch (final IOException e1) { + e1.printStackTrace(); + } + try { + connection.close(); + mySQL.closeConnection(); + } + catch (NullPointerException | SQLException e) { + if (connection != null) { + Logger.add(LogLevel.DANGER, "Could not close mysql connection"); + } + } + /* + * if(PlotWeb.PLOTWEB != null) { try { PlotWeb.PLOTWEB.stop(); } catch + * (Exception e) { e.printStackTrace(); } } + */ + } // Material.STONE_BUTTON, Material.WOOD_BUTTON, // Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, @@ -1296,30 +1327,13 @@ public class PlotMain extends JavaPlugin { } private static void addPlusFlags() { - List booleanFlags = Arrays.asList( - "notify-enter", - "notify-leave", - "item-drop", - "invincible", - "instabreak", - "drop-protection", - "forcefield", - "titles", - "pve", - "pvp" - ); - List intervalFlags = Arrays.asList( - "feed", - "heal" - ); - List stringFlags = Arrays.asList( - "greeting", - "farewell" - ); - for(String flag : stringFlags) { + final List booleanFlags = Arrays.asList("notify-enter", "notify-leave", "item-drop", "invincible", "instabreak", "drop-protection", "forcefield", "titles", "pve", "pvp"); + final List intervalFlags = Arrays.asList("feed", "heal"); + final List stringFlags = Arrays.asList("greeting", "farewell"); + for (final String flag : stringFlags) { FlagManager.addFlag(new AbstractFlag(flag) { @Override - public String parseValue(String value) { + public String parseValue(final String value) { return value; } @@ -1329,25 +1343,28 @@ public class PlotMain extends JavaPlugin { } }); } - for(String flag : intervalFlags) { + for (final String flag : intervalFlags) { FlagManager.addFlag(new AbstractFlag(flag) { @Override - public String parseValue(String value) { + public String parseValue(final String value) { int seconds; int amount; - String[] values = value.split(" "); + final String[] values = value.split(" "); if (values.length < 2) { seconds = 1; try { amount = Integer.parseInt(values[0]); - } catch (Exception e) { + } + catch (final Exception e) { return null; } - } else { + } + else { try { amount = Integer.parseInt(values[0]); seconds = Integer.parseInt(values[1]); - } catch (Exception e) { + } + catch (final Exception e) { return null; } } @@ -1360,10 +1377,10 @@ public class PlotMain extends JavaPlugin { } }); } - for(String flag : booleanFlags) { + for (final String flag : booleanFlags) { FlagManager.addFlag(new AbstractFlag(flag) { @Override - public String parseValue(String value) { + public String parseValue(final String value) { switch (value) { case "on": case "1": @@ -1392,7 +1409,7 @@ public class PlotMain extends JavaPlugin { addPlusFlags(); FlagManager.addFlag(new AbstractFlag("fly") { @Override - public String parseValue(String value) { + public String parseValue(final String value) { switch (value) { case "on": case "enabled": @@ -1415,11 +1432,11 @@ public class PlotMain extends JavaPlugin { } }); - for(String str : booleanFlags.values()) { + for (final String str : booleanFlags.values()) { FlagManager.addFlag(new AbstractFlag(str) { - + @Override - public String parseValue(String value) { + public String parseValue(final String value) { switch (value) { case "true": case "1": @@ -1438,14 +1455,13 @@ public class PlotMain extends JavaPlugin { public String getValueDesc() { return "Flag value must be a boolean: true, false"; } - - + }); } - + FlagManager.addFlag(new AbstractFlag("gamemode") { @Override - public String parseValue(String value) { + public String parseValue(final String value) { switch (value) { case "creative": case "c": @@ -1469,14 +1485,14 @@ public class PlotMain extends JavaPlugin { return "Flag value must be a gamemode: 'creative' , 'survival' or 'adventure'"; } }); - + FlagManager.addFlag(new AbstractFlag("time") { @Override - public String parseValue(String value) { + public String parseValue(final String value) { try { - return Long.parseLong(value)+""; + return Long.parseLong(value) + ""; } - catch (Exception e) { + catch (final Exception e) { return null; } } @@ -1486,21 +1502,21 @@ public class PlotMain extends JavaPlugin { return "Flag value must be a time in ticks: 0=sunrise 12000=noon 18000=sunset 24000=night"; } }); - + FlagManager.addFlag(new AbstractFlag("weather") { @Override - public String parseValue(String value) { + public String parseValue(final String value) { switch (value) { - case "rain": - case "storm": - case "on": - return "rain"; - case "clear": - case "off": - case "sun": - return "clear"; - default: - return null; + case "rain": + case "storm": + case "on": + return "rain"; + case "clear": + case "off": + case "sun": + return "clear"; + default: + return null; } } @@ -1511,30 +1527,30 @@ public class PlotMain extends JavaPlugin { }); } - public static void addPlotWorld(String world, PlotWorld plotworld, PlotManager manager) { - worlds.put(world, plotworld); - managers.put(world, manager); - if (!plots.containsKey(world)) { - plots.put(world, new HashMap()); - } - } - - public static void removePlotWorld(String world) { - plots.remove(world); - managers.remove(world); - worlds.remove(world); - } + public static void addPlotWorld(final String world, final PlotWorld plotworld, final PlotManager manager) { + worlds.put(world, plotworld); + managers.put(world, manager); + if (!plots.containsKey(world)) { + plots.put(world, new HashMap()); + } + } + + public static void removePlotWorld(final String world) { + plots.remove(world); + managers.remove(world); + worlds.remove(world); + } @SuppressWarnings("unused") - public static HashMap> getAllPlotsRaw() { + public static HashMap> getAllPlotsRaw() { return plots; } - public static void setAllPlotsRaw(LinkedHashMap> plots) { + public static void setAllPlotsRaw(final LinkedHashMap> plots) { PlotMain.plots = plots; } - public static void setAllPlotsRaw(HashMap> plots) { + public static void setAllPlotsRaw(final HashMap> plots) { PlotMain.plots = new LinkedHashMap>(); PlotMain.plots.putAll(plots); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotManager.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotManager.java index 1c7f27b46..eb96dbc4b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotManager.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotManager.java @@ -5,70 +5,69 @@ import java.util.ArrayList; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; -import org.bukkit.entity.Player; public abstract class PlotManager { - /* - * Plot locations (methods with Abs in them will not need to consider mega - * plots) - */ + /* + * Plot locations (methods with Abs in them will not need to consider mega + * plots) + */ - public abstract PlotId getPlotIdAbs(PlotWorld plotworld, Location loc); + public abstract PlotId getPlotIdAbs(final PlotWorld plotworld, final Location loc); - public abstract PlotId getPlotId(PlotWorld plotworld, Location loc); + public abstract PlotId getPlotId(final PlotWorld plotworld, final Location loc); - public abstract boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid); + public abstract boolean isInPlotAbs(final PlotWorld plotworld, final Location loc, final PlotId plotid); - // If you have a circular plot, just return the corner if it were a square - public abstract Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid); + // If you have a circular plot, just return the corner if it were a square + public abstract Location getPlotBottomLocAbs(final PlotWorld plotworld, final PlotId plotid); - // the same applies here - public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid); + // the same applies here + public abstract Location getPlotTopLocAbs(final PlotWorld plotworld, final PlotId plotid); - /* - * Plot clearing (return false if you do not support some method) - */ + /* + * Plot clearing (return false if you do not support some method) + */ - public abstract boolean clearPlot(World world, Plot plot); + public abstract boolean clearPlot(final World world, final Plot plot); - public abstract Location getSignLoc(World world, PlotWorld plotworld, Plot plot); + public abstract Location getSignLoc(final World world, final PlotWorld plotworld, final Plot plot); - /* - * Plot set functions (return false if you do not support the specific set - * method) - */ + /* + * Plot set functions (return false if you do not support the specific set + * method) + */ - public abstract boolean setWallFilling(World world, PlotWorld plotworld, PlotId plotid, PlotBlock block); - - public abstract boolean setWall(World world, PlotWorld plotworld, PlotId plotid, PlotBlock block); + public abstract boolean setWallFilling(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock block); - public abstract boolean setFloor(World world, PlotWorld plotworld, PlotId plotid, PlotBlock[] block); + public abstract boolean setWall(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock block); - public abstract boolean setBiome(World world, Plot plot, Biome biome); + public abstract boolean setFloor(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] block); - /* - * PLOT MERGING (return false if your generator does not support plot - * merging) - */ - public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot); + public abstract boolean setBiome(final World world, final Plot plot, final Biome biome); - public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot); + /* + * PLOT MERGING (return false if your generator does not support plot + * merging) + */ + public abstract boolean createRoadEast(final PlotWorld plotworld, final Plot plot); - public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot); + public abstract boolean createRoadSouth(final PlotWorld plotworld, final Plot plot); - public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot); + public abstract boolean createRoadSouthEast(final PlotWorld plotworld, final Plot plot); - public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot); + public abstract boolean removeRoadEast(final PlotWorld plotworld, final Plot plot); - public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot); - - public abstract boolean startPlotMerge(World world, PlotWorld plotworld, ArrayList plotIds); - - public abstract boolean startPlotUnlink(World world, PlotWorld plotworld, ArrayList plotIds); + public abstract boolean removeRoadSouth(final PlotWorld plotworld, final Plot plot); - public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList plotIds); - - public abstract boolean finishPlotUnlink(World world, PlotWorld plotworld, ArrayList plotIds); + public abstract boolean removeRoadSouthEast(final PlotWorld plotworld, final Plot plot); + + public abstract boolean startPlotMerge(final World world, final PlotWorld plotworld, final ArrayList plotIds); + + public abstract boolean startPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList plotIds); + + public abstract boolean finishPlotMerge(final World world, final PlotWorld plotworld, final ArrayList plotIds); + + public abstract boolean finishPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList plotIds); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSelection.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSelection.java index 5a83659ed..0ad1ca03d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSelection.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSelection.java @@ -1,17 +1,11 @@ package com.intellectualcrafters.plot; -import org.bukkit.Chunk; +import java.util.HashMap; + import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Entity; - -import com.sk89q.worldedit.blocks.TileEntityBlock; - -import java.util.ArrayList; -import java.util.HashMap; /** * Created by Citymonstret on 2014-10-12. @@ -20,103 +14,85 @@ public class PlotSelection { public static HashMap currentSelection = new HashMap<>(); - private PlotBlock[] plotBlocks; + private final PlotBlock[] plotBlocks; - private int width; + private final int width; - private Plot plot; - - private Biome biome; + private final Plot plot; - public PlotSelection(int width, World world, Plot plot) { + private final Biome biome; + + public PlotSelection(final int width, final World world, final Plot plot) { this.width = width; this.plot = plot; - plotBlocks = new PlotBlock[(width * width) * (world.getMaxHeight() - 1)]; + this.plotBlocks = new PlotBlock[(width * width) * (world.getMaxHeight() - 1)]; - Location - bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), - top = PlotHelper.getPlotTopLocAbs(world, plot.getId()); - int - minX = bot.getBlockX(), - maxX = top.getBlockX(), - minZ = bot.getBlockZ(), - maxZ = top.getBlockZ(), - minY = 1, - maxY = world.getMaxHeight(); + final Location bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), top = PlotHelper.getPlotTopLocAbs(world, plot.getId()); + final int minX = bot.getBlockX(), maxX = top.getBlockX(), minZ = bot.getBlockZ(), maxZ = top.getBlockZ(), minY = 1, maxY = world.getMaxHeight(); Block current; - + this.biome = world.getBiome(minX, minZ); - + int index = 0; for (int x = minX; x < maxX; x++) { for (int z = minZ; z < maxZ; z++) { for (int y = minY; y < maxY; y++) { current = world.getBlockAt(x + 1, y, z + 1); - plotBlocks[index++] = new PlotBlock( - (short) current.getTypeId(), - current.getData() - ); + this.plotBlocks[index++] = new PlotBlock((short) current.getTypeId(), current.getData()); } } } - - - - //Yay :D + + // Yay :D } public PlotBlock[] getBlocks() { - return plotBlocks; + return this.plotBlocks; } public int getWidth() { - return width; + return this.width; } public Plot getPlot() { - return plot; + return this.plot; } - - public static boolean swap(World world, PlotId id1, PlotId id2) { - - Location bot2 = PlotHelper.getPlotBottomLocAbs(world, id2).add(1, 0, 1); - Location bot1 = PlotHelper.getPlotBottomLocAbs(world, id1).add(1, 0, 1); - Location top1 = PlotHelper.getPlotTopLocAbs(world, id1); - - int - minX = bot1.getBlockX(), - maxX = top1.getBlockX(), - minZ = bot1.getBlockZ(), - maxZ = top1.getBlockZ(), - - minX2 = bot2.getBlockX(), - minZ2 = bot2.getBlockZ(); - - boolean canSetFast = PlotHelper.canSetFast; - - for (int x = 0; x <= maxX - minX; x++) { - for (int z = 0; z <= maxZ - minZ; z++) { + + public static boolean swap(final World world, final PlotId id1, final PlotId id2) { + + final Location bot2 = PlotHelper.getPlotBottomLocAbs(world, id2).add(1, 0, 1); + final Location bot1 = PlotHelper.getPlotBottomLocAbs(world, id1).add(1, 0, 1); + final Location top1 = PlotHelper.getPlotTopLocAbs(world, id1); + + final int minX = bot1.getBlockX(), maxX = top1.getBlockX(), minZ = bot1.getBlockZ(), maxZ = top1.getBlockZ(), + + minX2 = bot2.getBlockX(), minZ2 = bot2.getBlockZ(); + + final boolean canSetFast = PlotHelper.canSetFast; + + for (int x = 0; x <= (maxX - minX); x++) { + for (int z = 0; z <= (maxZ - minZ); z++) { for (int y = 1; y <= world.getMaxHeight(); y++) { - + final Block block1 = world.getBlockAt(x + minX, y, z + minZ); final Block block2 = world.getBlockAt(x + minX2, y, z + minZ2); - - + final BlockWrapper b1 = wrapBlock(block1); final BlockWrapper b2 = wrapBlock(block2); - - if (b1.id != b2.id || b1.data != b2.data) { + + if ((b1.id != b2.id) || (b1.data != b2.data)) { if (canSetFast) { try { SetBlockFast.set(world, b1.x, b1.y, b1.z, b2.id, b2.data); SetBlockFast.set(world, b2.x, b2.y, b2.z, b1.id, b1.data); - } catch (NoSuchMethodException e) { + } + catch (final NoSuchMethodException e) { PlotHelper.canSetFast = false; } } else { - if (b1.id != b2.id && b1.data != b2.data) { + if ((b1.id != b2.id) && (b1.data != b2.data)) { block1.setTypeIdAndData(b2.id, b2.data, false); block2.setTypeIdAndData(b1.id, b1.data, false); } @@ -135,35 +111,26 @@ public class PlotSelection { } return true; } - - private static BlockWrapper wrapBlock(Block block) { + + private static BlockWrapper wrapBlock(final Block block) { return new BlockWrapper(block.getX(), block.getY(), block.getZ(), (short) block.getTypeId(), block.getData()); } - public void paste(World world, Plot plot) { - - - Location - bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), - top = PlotHelper.getPlotTopLocAbs(world, plot.getId()); - int - minX = bot.getBlockX(), - maxX = top.getBlockX(), - minZ = bot.getBlockZ(), - maxZ = top.getBlockZ(), - minY = 1, - maxY = world.getMaxHeight(); - + public void paste(final World world, final Plot plot) { + + final Location bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), top = PlotHelper.getPlotTopLocAbs(world, plot.getId()); + final int minX = bot.getBlockX(), maxX = top.getBlockX(), minZ = bot.getBlockZ(), maxZ = top.getBlockZ(), minY = 1, maxY = world.getMaxHeight(); + if (this.biome != world.getBiome(minX, minZ)) { PlotHelper.setBiome(world, plot, this.biome); } - + int index = 0; PlotBlock current; for (int x = minX; x < maxX; x++) { for (int z = minZ; z < maxZ; z++) { for (int y = minY; y < maxY; y++) { - current = plotBlocks[index++]; + current = this.plotBlocks[index++]; world.getBlockAt(x + 1, y, z + 1).setTypeIdAndData(current.id, current.data, true); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSettings.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSettings.java index ceeed855a..8f5d0b785 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSettings.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSettings.java @@ -2,191 +2,187 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlotSettings.java >> Generated by: Citymonstret at 2014-08-09 01:44 */ package com.intellectualcrafters.plot; -import org.bukkit.block.Biome; - -import com.intellectualcrafters.plot.database.DBFunc; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import org.bukkit.block.Biome; + /** * plot settings * * @author Citymonstret */ public class PlotSettings { - /** - * merged plots - */ - private boolean[] merged = new boolean[] { false, false, false, false }; - /** - * plot alias - */ - private String alias; - /** - * plot biome - */ - private Biome biome; + /** + * merged plots + */ + private boolean[] merged = new boolean[] { false, false, false, false }; + /** + * plot alias + */ + private String alias; + /** + * plot biome + */ + private Biome biome; - private ArrayList comments = null; - /** - * - */ - private Set flags; + private ArrayList comments = null; + /** + * + */ + private Set flags; - private PlotHomePosition position; + private PlotHomePosition position; - /** - * Constructor - * - * @param plot - */ - public PlotSettings(Plot plot) { - this.alias = ""; - } - - /** - * Check if the plot is merged in a direction
    - * 0 = North
    - * 1 = East
    - * 2 = South
    - * 3 = West
    - * - * @param direction - * @return boolean - */ - public boolean getMerged(int direction) { - return this.merged[direction]; - } - - /** - * Returns true if the plot is merged (i.e. if it's a mega plot) - */ - public boolean isMerged() { - return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]); - } - - public boolean[] getMerged() { - return this.merged; - } - - public void setMerged(boolean[] merged) { - this.merged = merged; - } - - public void setMerged(int direction, boolean merged) { - this.merged[direction] = merged; - } - - /** - * @param b - */ - public void setBiome(Biome b) { - this.biome = b; - } - - - /** - * @return - * @deprecated - */ - @Deprecated - public Biome getBiome() { - return this.biome; - } - - - - /** - * @param alias - */ - public void setAlias(String alias) { - this.alias = alias; - } - - /** - * @param flag - */ - public void addFlag(Flag flag) { - Flag hasFlag = getFlag(flag.getKey()); - if (hasFlag != null) { - this.flags.remove(hasFlag); - } - this.flags.add(flag); - } - - /** - * @param flags - */ - public void setFlags(Flag[] flags) { - this.flags = new HashSet(Arrays.asList(flags)); - } - - /** - * @return - */ - public Set getFlags() { - return this.flags; - } - - /** - * @param flag - * @return - */ - public Flag getFlag(String flag) { - for (Flag myflag : this.flags) { - if (myflag.getKey().equals(flag)) { - return myflag; - } - } - return null; - } - - public PlotHomePosition getPosition() { - return this.position; - } - - public void setPosition(PlotHomePosition position) { - this.position = position; - } - - public String getAlias() { - return this.alias; - } - - public String getJoinMessage() { - return ""; - } - - public String getLeaveMessage() { - return ""; - } - public ArrayList getComments(int tier) { - ArrayList c = new ArrayList(); - for (PlotComment comment : this.comments) { - if (comment.tier == tier) { - c.add(comment); - } - } - return c; - } - - public void setComments(ArrayList comments) { - this.comments = comments; + /** + * Constructor + * + * @param plot + */ + public PlotSettings(final Plot plot) { + this.alias = ""; } - - public void addComment(PlotComment comment) { - if (this.comments == null) { + + /** + * Check if the plot is merged in a direction
    + * 0 = North
    + * 1 = East
    + * 2 = South
    + * 3 = West
    + * + * @param direction + * @return boolean + */ + public boolean getMerged(final int direction) { + return this.merged[direction]; + } + + /** + * Returns true if the plot is merged (i.e. if it's a mega plot) + */ + public boolean isMerged() { + return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]); + } + + public boolean[] getMerged() { + return this.merged; + } + + public void setMerged(final boolean[] merged) { + this.merged = merged; + } + + public void setMerged(final int direction, final boolean merged) { + this.merged[direction] = merged; + } + + /** + * @param b + */ + public void setBiome(final Biome b) { + this.biome = b; + } + + /** + * @return + * @deprecated + */ + @Deprecated + public Biome getBiome() { + return this.biome; + } + + /** + * @param alias + */ + public void setAlias(final String alias) { + this.alias = alias; + } + + /** + * @param flag + */ + public void addFlag(final Flag flag) { + final Flag hasFlag = getFlag(flag.getKey()); + if (hasFlag != null) { + this.flags.remove(hasFlag); + } + this.flags.add(flag); + } + + /** + * @param flags + */ + public void setFlags(final Flag[] flags) { + this.flags = new HashSet(Arrays.asList(flags)); + } + + /** + * @return + */ + public Set getFlags() { + return this.flags; + } + + /** + * @param flag + * @return + */ + public Flag getFlag(final String flag) { + for (final Flag myflag : this.flags) { + if (myflag.getKey().equals(flag)) { + return myflag; + } + } + return null; + } + + public PlotHomePosition getPosition() { + return this.position; + } + + public void setPosition(final PlotHomePosition position) { + this.position = position; + } + + public String getAlias() { + return this.alias; + } + + public String getJoinMessage() { + return ""; + } + + public String getLeaveMessage() { + return ""; + } + + public ArrayList getComments(final int tier) { + final ArrayList c = new ArrayList(); + for (final PlotComment comment : this.comments) { + if (comment.tier == tier) { + c.add(comment); + } + } + return c; + } + + public void setComments(final ArrayList comments) { + this.comments = comments; + } + + public void addComment(final PlotComment comment) { + if (this.comments == null) { this.comments = new ArrayList(); } this.comments.add(comment); - } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquaredException.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquaredException.java index 3414f3e2c..0e6115000 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquaredException.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotSquaredException.java @@ -5,26 +5,26 @@ package com.intellectualcrafters.plot; */ public class PlotSquaredException extends RuntimeException { - public PlotSquaredException(PlotError error, String details) { - super("PlotError >> " + error.getHeader() + ": " + details); - PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + error.getHeader() + ": &6" + details); - } + public PlotSquaredException(final PlotError error, final String details) { + super("PlotError >> " + error.getHeader() + ": " + details); + PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + error.getHeader() + ": &6" + details); + } - public static enum PlotError { - MISSING_DEPENDENCY("Missing Dependency"); - private String errorHeader; + public static enum PlotError { + MISSING_DEPENDENCY("Missing Dependency"); + private String errorHeader; - PlotError(String errorHeader) { - this.errorHeader = errorHeader; - } + PlotError(final String errorHeader) { + this.errorHeader = errorHeader; + } - public String getHeader() { - return this.errorHeader; - } + public String getHeader() { + return this.errorHeader; + } - @Override - public String toString() { - return this.getHeader(); - } - } + @Override + public String toString() { + return this.getHeader(); + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotWorld.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotWorld.java index 138f571a1..dcc3d9378 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotWorld.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/PlotWorld.java @@ -1,179 +1,247 @@ package com.intellectualcrafters.plot; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.configuration.ConfigurationSection; +import static org.bukkit.Material.ACACIA_STAIRS; +import static org.bukkit.Material.BEACON; +import static org.bukkit.Material.BEDROCK; +import static org.bukkit.Material.BIRCH_WOOD_STAIRS; +import static org.bukkit.Material.BOOKSHELF; +import static org.bukkit.Material.BREWING_STAND; +import static org.bukkit.Material.BRICK; +import static org.bukkit.Material.BRICK_STAIRS; +import static org.bukkit.Material.BURNING_FURNACE; +import static org.bukkit.Material.CAKE_BLOCK; +import static org.bukkit.Material.CAULDRON; +import static org.bukkit.Material.CLAY; +import static org.bukkit.Material.CLAY_BRICK; +import static org.bukkit.Material.COAL_BLOCK; +import static org.bukkit.Material.COAL_ORE; +import static org.bukkit.Material.COBBLESTONE; +import static org.bukkit.Material.COBBLESTONE_STAIRS; +import static org.bukkit.Material.COBBLE_WALL; +import static org.bukkit.Material.COMMAND; +import static org.bukkit.Material.DARK_OAK_STAIRS; +import static org.bukkit.Material.DAYLIGHT_DETECTOR; +import static org.bukkit.Material.DIAMOND_BLOCK; +import static org.bukkit.Material.DIAMOND_ORE; +import static org.bukkit.Material.DIRT; +import static org.bukkit.Material.DISPENSER; +import static org.bukkit.Material.DROPPER; +import static org.bukkit.Material.EMERALD_BLOCK; +import static org.bukkit.Material.EMERALD_ORE; +import static org.bukkit.Material.ENCHANTMENT_TABLE; +import static org.bukkit.Material.ENDER_PORTAL_FRAME; +import static org.bukkit.Material.ENDER_STONE; +import static org.bukkit.Material.FURNACE; +import static org.bukkit.Material.GLASS; +import static org.bukkit.Material.GLOWSTONE; +import static org.bukkit.Material.GOLD_BLOCK; +import static org.bukkit.Material.GOLD_ORE; +import static org.bukkit.Material.GRASS; +import static org.bukkit.Material.GRAVEL; +import static org.bukkit.Material.HARD_CLAY; +import static org.bukkit.Material.HAY_BLOCK; +import static org.bukkit.Material.HUGE_MUSHROOM_1; +import static org.bukkit.Material.HUGE_MUSHROOM_2; +import static org.bukkit.Material.IRON_BLOCK; +import static org.bukkit.Material.IRON_ORE; +import static org.bukkit.Material.JACK_O_LANTERN; +import static org.bukkit.Material.JUKEBOX; +import static org.bukkit.Material.JUNGLE_WOOD_STAIRS; +import static org.bukkit.Material.LAPIS_BLOCK; +import static org.bukkit.Material.LAPIS_ORE; +import static org.bukkit.Material.LEAVES; +import static org.bukkit.Material.LEAVES_2; +import static org.bukkit.Material.LOG; +import static org.bukkit.Material.LOG_2; +import static org.bukkit.Material.MELON_BLOCK; +import static org.bukkit.Material.MOB_SPAWNER; +import static org.bukkit.Material.MOSSY_COBBLESTONE; +import static org.bukkit.Material.MYCEL; +import static org.bukkit.Material.NETHERRACK; +import static org.bukkit.Material.NETHER_BRICK; +import static org.bukkit.Material.NETHER_BRICK_STAIRS; +import static org.bukkit.Material.NOTE_BLOCK; +import static org.bukkit.Material.OBSIDIAN; +import static org.bukkit.Material.PACKED_ICE; +import static org.bukkit.Material.PUMPKIN; +import static org.bukkit.Material.QUARTZ_BLOCK; +import static org.bukkit.Material.QUARTZ_ORE; +import static org.bukkit.Material.QUARTZ_STAIRS; +import static org.bukkit.Material.REDSTONE_BLOCK; +import static org.bukkit.Material.SAND; +import static org.bukkit.Material.SANDSTONE; +import static org.bukkit.Material.SANDSTONE_STAIRS; +import static org.bukkit.Material.SMOOTH_BRICK; +import static org.bukkit.Material.SMOOTH_STAIRS; +import static org.bukkit.Material.SNOW_BLOCK; +import static org.bukkit.Material.SOUL_SAND; +import static org.bukkit.Material.SPONGE; +import static org.bukkit.Material.SPRUCE_WOOD_STAIRS; +import static org.bukkit.Material.STONE; +import static org.bukkit.Material.WOOD; +import static org.bukkit.Material.WOOD_STAIRS; +import static org.bukkit.Material.WOOL; +import static org.bukkit.Material.WORKBENCH; +import static org.bukkit.Material.getMaterial; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; -import static org.bukkit.Material.*; +import org.bukkit.Material; +import org.bukkit.block.Biome; +import org.bukkit.configuration.ConfigurationSection; /** - * + * * @author Jesse Boyd * */ public abstract class PlotWorld { - // TODO make this configurable - // make non static and static_default_valu + add config option - @SuppressWarnings("deprecation") - public static ArrayList BLOCKS = new ArrayList(Arrays.asList(new Material[] { ACACIA_STAIRS, - BEACON, BEDROCK, BIRCH_WOOD_STAIRS, BOOKSHELF, BREWING_STAND, BRICK, BRICK_STAIRS, BURNING_FURNACE, - CAKE_BLOCK, CAULDRON, CLAY_BRICK, CLAY, COAL_BLOCK, COAL_ORE, COBBLE_WALL, COBBLESTONE, COBBLESTONE_STAIRS, - COMMAND, DARK_OAK_STAIRS, DAYLIGHT_DETECTOR, DIAMOND_ORE, DIAMOND_BLOCK, DIRT, DISPENSER, DROPPER, - EMERALD_BLOCK, EMERALD_ORE, ENCHANTMENT_TABLE, ENDER_PORTAL_FRAME, ENDER_STONE, FURNACE, GLOWSTONE, - GOLD_ORE, GOLD_BLOCK, GRASS, GRAVEL, GLASS, HARD_CLAY, HAY_BLOCK, HUGE_MUSHROOM_1, HUGE_MUSHROOM_2, - IRON_BLOCK, IRON_ORE, JACK_O_LANTERN, JUKEBOX, JUNGLE_WOOD_STAIRS, LAPIS_BLOCK, LAPIS_ORE, LEAVES, - LEAVES_2, LOG, LOG_2, MELON_BLOCK, MOB_SPAWNER, MOSSY_COBBLESTONE, MYCEL, NETHER_BRICK, - NETHER_BRICK_STAIRS, NETHERRACK, NOTE_BLOCK, OBSIDIAN, PACKED_ICE, PUMPKIN, QUARTZ_BLOCK, QUARTZ_ORE, - QUARTZ_STAIRS, REDSTONE_BLOCK, SANDSTONE, SAND, SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK, - SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44), - getMaterial(126) })); + // TODO make this configurable + // make non static and static_default_valu + add config option + @SuppressWarnings("deprecation") + public static ArrayList BLOCKS = new ArrayList(Arrays.asList(new Material[] { ACACIA_STAIRS, BEACON, BEDROCK, BIRCH_WOOD_STAIRS, BOOKSHELF, BREWING_STAND, BRICK, BRICK_STAIRS, BURNING_FURNACE, CAKE_BLOCK, CAULDRON, CLAY_BRICK, CLAY, COAL_BLOCK, COAL_ORE, COBBLE_WALL, COBBLESTONE, COBBLESTONE_STAIRS, COMMAND, DARK_OAK_STAIRS, DAYLIGHT_DETECTOR, DIAMOND_ORE, DIAMOND_BLOCK, DIRT, DISPENSER, DROPPER, EMERALD_BLOCK, EMERALD_ORE, ENCHANTMENT_TABLE, ENDER_PORTAL_FRAME, ENDER_STONE, FURNACE, GLOWSTONE, GOLD_ORE, GOLD_BLOCK, GRASS, GRAVEL, GLASS, HARD_CLAY, HAY_BLOCK, HUGE_MUSHROOM_1, HUGE_MUSHROOM_2, IRON_BLOCK, IRON_ORE, JACK_O_LANTERN, JUKEBOX, JUNGLE_WOOD_STAIRS, LAPIS_BLOCK, LAPIS_ORE, LEAVES, LEAVES_2, LOG, LOG_2, MELON_BLOCK, MOB_SPAWNER, MOSSY_COBBLESTONE, MYCEL, NETHER_BRICK, NETHER_BRICK_STAIRS, NETHERRACK, NOTE_BLOCK, OBSIDIAN, PACKED_ICE, PUMPKIN, QUARTZ_BLOCK, QUARTZ_ORE, QUARTZ_STAIRS, REDSTONE_BLOCK, SANDSTONE, SAND, + SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK, SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44), getMaterial(126) })); - public boolean AUTO_MERGE; - public static boolean AUTO_MERGE_DEFAULT = false; + public boolean AUTO_MERGE; + public static boolean AUTO_MERGE_DEFAULT = false; - public boolean MOB_SPAWNING; - public static boolean MOB_SPAWNING_DEFAULT = false; + public boolean MOB_SPAWNING; + public static boolean MOB_SPAWNING_DEFAULT = false; - public Biome PLOT_BIOME; - public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST; + public Biome PLOT_BIOME; + public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST; - public boolean PLOT_CHAT; - public static boolean PLOT_CHAT_DEFAULT = false; + public boolean PLOT_CHAT; + public static boolean PLOT_CHAT_DEFAULT = false; - public boolean SCHEMATIC_CLAIM_SPECIFY = false; - public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false; + public boolean SCHEMATIC_CLAIM_SPECIFY = false; + public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false; - public boolean SCHEMATIC_ON_CLAIM; - public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false; + public boolean SCHEMATIC_ON_CLAIM; + public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false; - public String SCHEMATIC_FILE; - public static String SCHEMATIC_FILE_DEFAULT = "null"; + public String SCHEMATIC_FILE; + public static String SCHEMATIC_FILE_DEFAULT = "null"; - public List SCHEMATICS; - public static List SCHEMATICS_DEFAULT = null; + public List SCHEMATICS; + public static List SCHEMATICS_DEFAULT = null; - public List DEFAULT_FLAGS; - public static List DEFAULT_FLAGS_DEFAULT = new ArrayList(); + public List DEFAULT_FLAGS; + public static List DEFAULT_FLAGS_DEFAULT = new ArrayList(); - public boolean USE_ECONOMY; - public static boolean USE_ECONOMY_DEFAULT = false; + public boolean USE_ECONOMY; + public static boolean USE_ECONOMY_DEFAULT = false; - public double PLOT_PRICE; - public static double PLOT_PRICE_DEFAULT = 100; + public double PLOT_PRICE; + public static double PLOT_PRICE_DEFAULT = 100; - public double MERGE_PRICE; - public static double MERGE_PRICE_DEFAULT = 100; + public double MERGE_PRICE; + public static double MERGE_PRICE_DEFAULT = 100; - public double SELL_PRICE; - public static double SELL_PRICE_DEFAULT = 75; + public double SELL_PRICE; + public static double SELL_PRICE_DEFAULT = 75; - public boolean PVP; - public static boolean PVP_DEFAULT = false; + public boolean PVP; + public static boolean PVP_DEFAULT = false; - public boolean PVE; - public static boolean PVE_DEFAULT = false; + public boolean PVE; + public static boolean PVE_DEFAULT = false; - public boolean SPAWN_EGGS; - public static boolean SPAWN_EGGS_DEFAULT = false; + public boolean SPAWN_EGGS; + public static boolean SPAWN_EGGS_DEFAULT = false; - public boolean SPAWN_CUSTOM; - public static boolean SPAWN_CUSTOM_DEFAULT = true; + public boolean SPAWN_CUSTOM; + public static boolean SPAWN_CUSTOM_DEFAULT = true; - public boolean SPAWN_BREEDING; - public static boolean SPAWN_BREEDING_DEFAULT = false; + public boolean SPAWN_BREEDING; + public static boolean SPAWN_BREEDING_DEFAULT = false; + public PlotWorld(final String worldname) { + this.worldname = worldname; + } - public PlotWorld(String worldname) { - this.worldname = worldname; - } - - /** - * When a world is created, the following method will be called for each - * - @param config - */ - public void loadDefaultConfiguration(ConfigurationSection config) - { - this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning"); - this.AUTO_MERGE = config.getBoolean("plot.auto_merge"); - this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome")); - this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim"); - this.SCHEMATIC_FILE = config.getString("schematic.file"); - this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim"); - this.SCHEMATICS = config.getStringList("schematic.schematics"); - this.USE_ECONOMY = config.getBoolean("economy.use"); - this.PLOT_PRICE = config.getDouble("economy.prices.claim"); - this.MERGE_PRICE = config.getDouble("economy.prices.merge"); - this.SELL_PRICE = config.getDouble("economy.prices.sell"); - this.PLOT_CHAT = config.getBoolean("chat.enabled"); - this.DEFAULT_FLAGS = config.getStringList("flags.default"); - this.PVP = config.getBoolean("event.pvp"); + /** + * When a world is created, the following method will be called for each + * + * @param config + */ + public void loadDefaultConfiguration(final ConfigurationSection config) { + this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning"); + this.AUTO_MERGE = config.getBoolean("plot.auto_merge"); + this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome")); + this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim"); + this.SCHEMATIC_FILE = config.getString("schematic.file"); + this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim"); + this.SCHEMATICS = config.getStringList("schematic.schematics"); + this.USE_ECONOMY = config.getBoolean("economy.use"); + this.PLOT_PRICE = config.getDouble("economy.prices.claim"); + this.MERGE_PRICE = config.getDouble("economy.prices.merge"); + this.SELL_PRICE = config.getDouble("economy.prices.sell"); + this.PLOT_CHAT = config.getBoolean("chat.enabled"); + this.DEFAULT_FLAGS = config.getStringList("flags.default"); + this.PVP = config.getBoolean("event.pvp"); this.PVE = config.getBoolean("event.pve"); this.SPAWN_EGGS = config.getBoolean("event.spawn.egg"); this.SPAWN_CUSTOM = config.getBoolean("event.spawn.custom"); this.SPAWN_BREEDING = config.getBoolean("event.spawn.breeding"); loadConfiguration(config); - } + } - public abstract void loadConfiguration(ConfigurationSection config); + public abstract void loadConfiguration(final ConfigurationSection config); - /** - * Saving core plotworld settings - * @param config - */ - public void saveConfiguration(ConfigurationSection config) - { - HashMap options = new HashMap(); + /** + * Saving core plotworld settings + * + * @param config + */ + public void saveConfiguration(final ConfigurationSection config) { + final HashMap options = new HashMap(); - options.put("natural_mob_spawning", PlotWorld.MOB_SPAWNING_DEFAULT); - options.put("plot.auto_merge", PlotWorld.AUTO_MERGE_DEFAULT); - options.put("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT.toString()); - options.put("schematic.on_claim", PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT); - options.put("schematic.file", PlotWorld.SCHEMATIC_FILE_DEFAULT); - options.put("schematic.specify_on_claim", PlotWorld.SCHEMATIC_CLAIM_SPECIFY_DEFAULT); - options.put("schematic.schematics", PlotWorld.SCHEMATICS_DEFAULT); - options.put("economy.use", PlotWorld.USE_ECONOMY_DEFAULT); - options.put("economy.prices.claim", PlotWorld.PLOT_PRICE_DEFAULT); - options.put("economy.prices.merge", PlotWorld.MERGE_PRICE_DEFAULT); - options.put("economy.prices.sell", PlotWorld.SELL_PRICE_DEFAULT); - options.put("chat.enabled", PlotWorld.PLOT_CHAT_DEFAULT); - options.put("flags.default", PlotWorld.DEFAULT_FLAGS_DEFAULT); + options.put("natural_mob_spawning", PlotWorld.MOB_SPAWNING_DEFAULT); + options.put("plot.auto_merge", PlotWorld.AUTO_MERGE_DEFAULT); + options.put("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT.toString()); + options.put("schematic.on_claim", PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT); + options.put("schematic.file", PlotWorld.SCHEMATIC_FILE_DEFAULT); + options.put("schematic.specify_on_claim", PlotWorld.SCHEMATIC_CLAIM_SPECIFY_DEFAULT); + options.put("schematic.schematics", PlotWorld.SCHEMATICS_DEFAULT); + options.put("economy.use", PlotWorld.USE_ECONOMY_DEFAULT); + options.put("economy.prices.claim", PlotWorld.PLOT_PRICE_DEFAULT); + options.put("economy.prices.merge", PlotWorld.MERGE_PRICE_DEFAULT); + options.put("economy.prices.sell", PlotWorld.SELL_PRICE_DEFAULT); + options.put("chat.enabled", PlotWorld.PLOT_CHAT_DEFAULT); + options.put("flags.default", PlotWorld.DEFAULT_FLAGS_DEFAULT); options.put("event.pvp", PlotWorld.PVP_DEFAULT); options.put("event.pve", PlotWorld.PVE_DEFAULT); options.put("event.spawn.egg", PlotWorld.SPAWN_EGGS_DEFAULT); options.put("event.spawn.custom", PlotWorld.SPAWN_CUSTOM_DEFAULT); options.put("event.spawn.breeding", PlotWorld.SPAWN_BREEDING_DEFAULT); - ConfigurationNode[] settings = getSettingNodes(); + final ConfigurationNode[] settings = getSettingNodes(); - /* - * Saving generator specific settings - */ - for (ConfigurationNode setting : settings) - { - options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue())); - } + /* + * Saving generator specific settings + */ + for (final ConfigurationNode setting : settings) { + options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue())); + } - for (String option : options.keySet()) - { - if (!config.contains(option)) { - config.set(option, options.get(option)); - } - } - } + for (final String option : options.keySet()) { + if (!config.contains(option)) { + config.set(option, options.get(option)); + } + } + } - public String worldname; + public String worldname; - /** - * Used for the /plot setup command Return null if you do not want to - * support this feature - * - * @return ConfigurationNode[] - */ - public abstract ConfigurationNode[] getSettingNodes(); + /** + * Used for the /plot setup command Return null if you do not want to + * support this feature + * + * @return ConfigurationNode[] + */ + public abstract ConfigurationNode[] getSettingNodes(); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/RUtils.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/RUtils.java index 5d08e1436..5471d0641 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/RUtils.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/RUtils.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = RUtils.java >> Generated by: Citymonstret at 2014-08-09 01:44 */ @@ -18,70 +18,70 @@ import org.bukkit.entity.Player; */ public class RUtils { - public static long getTotalRam() { - return (Runtime.getRuntime().maxMemory() / 1024) / 1024; - } + public static long getTotalRam() { + return (Runtime.getRuntime().maxMemory() / 1024) / 1024; + } - public static long getFreeRam() { - return (Runtime.getRuntime().freeMemory() / 1024) / 1024; - } + public static long getFreeRam() { + return (Runtime.getRuntime().freeMemory() / 1024) / 1024; + } - public static long getRamPercentage() { - return (getFreeRam() / getTotalRam()) * 100; - } + public static long getRamPercentage() { + return (getFreeRam() / getTotalRam()) * 100; + } - public static String formatTime(double sec) { - double h = sec / 3600; - double m = (sec % 3600) / 60; - double s = sec % 60; - String string = C.TIME_FORMAT.s(); + public static String formatTime(final double sec) { + final double h = sec / 3600; + final double m = (sec % 3600) / 60; + final double s = sec % 60; + final String string = C.TIME_FORMAT.s(); - String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour"); - String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute"); - String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second"); - return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h); - } + final String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour"); + final String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute"); + final String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second"); + return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h); + } - enum Direction { - SOUTH(0), - EAST(1), - NORTH(2), - WEST(3); - private int i; + enum Direction { + SOUTH(0), + EAST(1), + NORTH(2), + WEST(3); + private final int i; - Direction(int i) { - this.i = i; - } + Direction(final int i) { + this.i = i; + } - public int getInt() { - return this.i; - } - } + public int getInt() { + return this.i; + } + } - public void forceTexture(Player p) { - p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); - } + public void forceTexture(final Player p) { + p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); + } - public Direction getDirection(Location l) { - double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D; - int i = (int) d; - int x = d < i ? i - 1 : i; - switch (x) { - case 0: - return Direction.SOUTH; - case 1: - return Direction.EAST; - case 2: - return Direction.NORTH; - case 3: - return Direction.WEST; - default: - return null; - } - } + public Direction getDirection(final Location l) { + final double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D; + final int i = (int) d; + final int x = d < i ? i - 1 : i; + switch (x) { + case 0: + return Direction.SOUTH; + case 1: + return Direction.EAST; + case 2: + return Direction.NORTH; + case 3: + return Direction.WEST; + default: + return null; + } + } - public boolean compareDirections(Location l1, Location l2) { - return getDirection(l1) == getDirection(l2); - } + public boolean compareDirections(final Location l1, final Location l2) { + return getDirection(l1) == getDirection(l2); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/ReflectionUtils.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/ReflectionUtils.java index 4b75ea561..a7be3fa64 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/ReflectionUtils.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/ReflectionUtils.java @@ -17,579 +17,574 @@ import org.bukkit.Server; @SuppressWarnings({ "UnusedDeclaration", "rawtypes" }) public class ReflectionUtils { - /** prefix of bukkit classes */ - private static String preClassB = "org.bukkit.craftbukkit"; - /** prefix of minecraft classes */ - private static String preClassM = "net.minecraft.server"; - /** boolean value, TRUE if server uses forge or MCPC+ */ - private static boolean forge = false; + /** prefix of bukkit classes */ + private static String preClassB = "org.bukkit.craftbukkit"; + /** prefix of minecraft classes */ + private static String preClassM = "net.minecraft.server"; + /** boolean value, TRUE if server uses forge or MCPC+ */ + private static boolean forge = false; - /** check server version and class names */ - static { - if (Bukkit.getServer() != null) { - if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) { - forge = true; - } - Server server = Bukkit.getServer(); - Class bukkitServerClass = server.getClass(); - String[] pas = bukkitServerClass.getName().split("\\."); - if (pas.length == 5) { - String verB = pas[3]; - preClassB += "." + verB; - } - try { - Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); - Object handle = getHandle.invoke(server); - Class handleServerClass = handle.getClass(); - pas = handleServerClass.getName().split("\\."); - if (pas.length == 5) { - String verM = pas[3]; - preClassM += "." + verM; - } - } - catch (Exception ignored) { - } - } - } + /** check server version and class names */ + static { + if (Bukkit.getServer() != null) { + if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) { + forge = true; + } + final Server server = Bukkit.getServer(); + final Class bukkitServerClass = server.getClass(); + String[] pas = bukkitServerClass.getName().split("\\."); + if (pas.length == 5) { + final String verB = pas[3]; + preClassB += "." + verB; + } + try { + final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); + final Object handle = getHandle.invoke(server); + final Class handleServerClass = handle.getClass(); + pas = handleServerClass.getName().split("\\."); + if (pas.length == 5) { + final String verM = pas[3]; + preClassM += "." + verM; + } + } + catch (final Exception ignored) { + } + } + } - /** - * @return true if server has forge classes - */ - public static boolean isForge() { - return forge; - } + /** + * @return true if server has forge classes + */ + public static boolean isForge() { + return forge; + } - /** - * Get class for name. Replace {nms} to net.minecraft.server.V*. Replace - * {cb} to org.bukkit.craftbukkit.V*. Replace {nm} to net.minecraft - * - * @param classes - * possible class paths - * @return RefClass object - * @throws RuntimeException - * if no class found - */ - public static RefClass getRefClass(String... classes) { - for (String className : classes) { - try { - className = - className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft"); - return getRefClass(Class.forName(className)); - } - catch (ClassNotFoundException ignored) { - } - } - throw new RuntimeException("no class found"); - } + /** + * Get class for name. Replace {nms} to net.minecraft.server.V*. Replace + * {cb} to org.bukkit.craftbukkit.V*. Replace {nm} to net.minecraft + * + * @param classes + * possible class paths + * @return RefClass object + * @throws RuntimeException + * if no class found + */ + public static RefClass getRefClass(final String... classes) { + for (String className : classes) { + try { + className = className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft"); + return getRefClass(Class.forName(className)); + } + catch (final ClassNotFoundException ignored) { + } + } + throw new RuntimeException("no class found"); + } - /** - * get RefClass object by real class - * - * @param clazz - * class - * @return RefClass based on passed class - */ - public static RefClass getRefClass(Class clazz) { - return new RefClass(clazz); - } + /** + * get RefClass object by real class + * + * @param clazz + * class + * @return RefClass based on passed class + */ + public static RefClass getRefClass(final Class clazz) { + return new RefClass(clazz); + } - /** - * RefClass - utility to simplify work with reflections. - */ - public static class RefClass { - private final Class clazz; + /** + * RefClass - utility to simplify work with reflections. + */ + public static class RefClass { + private final Class clazz; - /** - * get passed class - * - * @return class - */ - public Class getRealClass() { - return this.clazz; - } + /** + * get passed class + * + * @return class + */ + public Class getRealClass() { + return this.clazz; + } - private RefClass(Class clazz) { - this.clazz = clazz; - } + private RefClass(final Class clazz) { + this.clazz = clazz; + } - /** - * see {@link Class#isInstance(Object)} - * - * @param object - * the object to check - * @return true if object is an instance of this class - */ - public boolean isInstance(Object object) { - return this.clazz.isInstance(object); - } + /** + * see {@link Class#isInstance(Object)} + * + * @param object + * the object to check + * @return true if object is an instance of this class + */ + public boolean isInstance(final Object object) { + return this.clazz.isInstance(object); + } - /** - * get existing method by name and types - * - * @param name - * name - * @param types - * method parameters. can be Class or RefClass - * @return RefMethod object - * @throws RuntimeException - * if method not found - */ - public RefMethod getMethod(String name, Object... types) throws NoSuchMethodException { - try { - Class[] classes = new Class[types.length]; - int i = 0; - for (Object e : types) { - if (e instanceof Class) { - classes[i++] = (Class) e; - } - else - if (e instanceof RefClass) { - classes[i++] = ((RefClass) e).getRealClass(); - } - else { - classes[i++] = e.getClass(); - } - } - try { - return new RefMethod(this.clazz.getMethod(name, classes)); - } - catch (NoSuchMethodException ignored) { - return new RefMethod(this.clazz.getDeclaredMethod(name, classes)); - } - } - catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * get existing method by name and types + * + * @param name + * name + * @param types + * method parameters. can be Class or RefClass + * @return RefMethod object + * @throws RuntimeException + * if method not found + */ + public RefMethod getMethod(final String name, final Object... types) throws NoSuchMethodException { + try { + final Class[] classes = new Class[types.length]; + int i = 0; + for (final Object e : types) { + if (e instanceof Class) { + classes[i++] = (Class) e; + } + else if (e instanceof RefClass) { + classes[i++] = ((RefClass) e).getRealClass(); + } + else { + classes[i++] = e.getClass(); + } + } + try { + return new RefMethod(this.clazz.getMethod(name, classes)); + } + catch (final NoSuchMethodException ignored) { + return new RefMethod(this.clazz.getDeclaredMethod(name, classes)); + } + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } - /** - * get existing constructor by types - * - * @param types - * parameters. can be Class or RefClass - * @return RefMethod object - * @throws RuntimeException - * if constructor not found - */ - public RefConstructor getConstructor(Object... types) { - try { - Class[] classes = new Class[types.length]; - int i = 0; - for (Object e : types) { - if (e instanceof Class) { - classes[i++] = (Class) e; - } - else - if (e instanceof RefClass) { - classes[i++] = ((RefClass) e).getRealClass(); - } - else { - classes[i++] = e.getClass(); - } - } - try { - return new RefConstructor(this.clazz.getConstructor(classes)); - } - catch (NoSuchMethodException ignored) { - return new RefConstructor(this.clazz.getDeclaredConstructor(classes)); - } - } - catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * get existing constructor by types + * + * @param types + * parameters. can be Class or RefClass + * @return RefMethod object + * @throws RuntimeException + * if constructor not found + */ + public RefConstructor getConstructor(final Object... types) { + try { + final Class[] classes = new Class[types.length]; + int i = 0; + for (final Object e : types) { + if (e instanceof Class) { + classes[i++] = (Class) e; + } + else if (e instanceof RefClass) { + classes[i++] = ((RefClass) e).getRealClass(); + } + else { + classes[i++] = e.getClass(); + } + } + try { + return new RefConstructor(this.clazz.getConstructor(classes)); + } + catch (final NoSuchMethodException ignored) { + return new RefConstructor(this.clazz.getDeclaredConstructor(classes)); + } + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } - /** - * find method by type parameters - * - * @param types - * parameters. can be Class or RefClass - * @return RefMethod object - * @throws RuntimeException - * if method not found - */ - public RefMethod findMethod(Object... types) { - Class[] classes = new Class[types.length]; - int t = 0; - for (Object e : types) { - if (e instanceof Class) { - classes[t++] = (Class) e; - } - else - if (e instanceof RefClass) { - classes[t++] = ((RefClass) e).getRealClass(); - } - else { - classes[t++] = e.getClass(); - } - } - List methods = new ArrayList<>(); - Collections.addAll(methods, this.clazz.getMethods()); - Collections.addAll(methods, this.clazz.getDeclaredMethods()); - findMethod: - for (Method m : methods) { - Class[] methodTypes = m.getParameterTypes(); - if (methodTypes.length != classes.length) { - continue; - } - for (int i = 0; i < classes.length; i++) { - if (!classes.equals(methodTypes)) { - continue findMethod; - } - return new RefMethod(m); - } - } - throw new RuntimeException("no such method"); - } + /** + * find method by type parameters + * + * @param types + * parameters. can be Class or RefClass + * @return RefMethod object + * @throws RuntimeException + * if method not found + */ + public RefMethod findMethod(final Object... types) { + final Class[] classes = new Class[types.length]; + int t = 0; + for (final Object e : types) { + if (e instanceof Class) { + classes[t++] = (Class) e; + } + else if (e instanceof RefClass) { + classes[t++] = ((RefClass) e).getRealClass(); + } + else { + classes[t++] = e.getClass(); + } + } + final List methods = new ArrayList<>(); + Collections.addAll(methods, this.clazz.getMethods()); + Collections.addAll(methods, this.clazz.getDeclaredMethods()); + findMethod: for (final Method m : methods) { + final Class[] methodTypes = m.getParameterTypes(); + if (methodTypes.length != classes.length) { + continue; + } + for (int i = 0; i < classes.length; i++) { + if (!classes.equals(methodTypes)) { + continue findMethod; + } + return new RefMethod(m); + } + } + throw new RuntimeException("no such method"); + } - /** - * find method by name - * - * @param names - * possible names of method - * @return RefMethod object - * @throws RuntimeException - * if method not found - */ - public RefMethod findMethodByName(String... names) { - List methods = new ArrayList<>(); - Collections.addAll(methods, this.clazz.getMethods()); - Collections.addAll(methods, this.clazz.getDeclaredMethods()); - for (Method m : methods) { - for (String name : names) { - if (m.getName().equals(name)) { - return new RefMethod(m); - } - } - } - throw new RuntimeException("no such method"); - } + /** + * find method by name + * + * @param names + * possible names of method + * @return RefMethod object + * @throws RuntimeException + * if method not found + */ + public RefMethod findMethodByName(final String... names) { + final List methods = new ArrayList<>(); + Collections.addAll(methods, this.clazz.getMethods()); + Collections.addAll(methods, this.clazz.getDeclaredMethods()); + for (final Method m : methods) { + for (final String name : names) { + if (m.getName().equals(name)) { + return new RefMethod(m); + } + } + } + throw new RuntimeException("no such method"); + } - /** - * find method by return value - * - * @param type - * type of returned value - * @throws RuntimeException - * if method not found - * @return RefMethod - */ - public RefMethod findMethodByReturnType(RefClass type) { - return findMethodByReturnType(type.clazz); - } + /** + * find method by return value + * + * @param type + * type of returned value + * @throws RuntimeException + * if method not found + * @return RefMethod + */ + public RefMethod findMethodByReturnType(final RefClass type) { + return findMethodByReturnType(type.clazz); + } - /** - * find method by return value - * - * @param type - * type of returned value - * @return RefMethod - * @throws RuntimeException - * if method not found - */ - public RefMethod findMethodByReturnType(Class type) { - if (type == null) { - type = void.class; - } - List methods = new ArrayList<>(); - Collections.addAll(methods, this.clazz.getMethods()); - Collections.addAll(methods, this.clazz.getDeclaredMethods()); - for (Method m : methods) { - if (type.equals(m.getReturnType())) { - return new RefMethod(m); - } - } - throw new RuntimeException("no such method"); - } + /** + * find method by return value + * + * @param type + * type of returned value + * @return RefMethod + * @throws RuntimeException + * if method not found + */ + public RefMethod findMethodByReturnType(Class type) { + if (type == null) { + type = void.class; + } + final List methods = new ArrayList<>(); + Collections.addAll(methods, this.clazz.getMethods()); + Collections.addAll(methods, this.clazz.getDeclaredMethods()); + for (final Method m : methods) { + if (type.equals(m.getReturnType())) { + return new RefMethod(m); + } + } + throw new RuntimeException("no such method"); + } - /** - * find constructor by number of arguments - * - * @param number - * number of arguments - * @return RefConstructor - * @throws RuntimeException - * if constructor not found - */ - public RefConstructor findConstructor(int number) { - List constructors = new ArrayList<>(); - Collections.addAll(constructors, this.clazz.getConstructors()); - Collections.addAll(constructors, this.clazz.getDeclaredConstructors()); - for (Constructor m : constructors) { - if (m.getParameterTypes().length == number) { - return new RefConstructor(m); - } - } - throw new RuntimeException("no such constructor"); - } + /** + * find constructor by number of arguments + * + * @param number + * number of arguments + * @return RefConstructor + * @throws RuntimeException + * if constructor not found + */ + public RefConstructor findConstructor(final int number) { + final List constructors = new ArrayList<>(); + Collections.addAll(constructors, this.clazz.getConstructors()); + Collections.addAll(constructors, this.clazz.getDeclaredConstructors()); + for (final Constructor m : constructors) { + if (m.getParameterTypes().length == number) { + return new RefConstructor(m); + } + } + throw new RuntimeException("no such constructor"); + } - /** - * get field by name - * - * @param name - * field name - * @return RefField - * @throws RuntimeException - * if field not found - */ - public RefField getField(String name) { - try { - try { - return new RefField(this.clazz.getField(name)); - } - catch (NoSuchFieldException ignored) { - return new RefField(this.clazz.getDeclaredField(name)); - } - } - catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * get field by name + * + * @param name + * field name + * @return RefField + * @throws RuntimeException + * if field not found + */ + public RefField getField(final String name) { + try { + try { + return new RefField(this.clazz.getField(name)); + } + catch (final NoSuchFieldException ignored) { + return new RefField(this.clazz.getDeclaredField(name)); + } + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } - /** - * find field by type - * - * @param type - * field type - * @return RefField - * @throws RuntimeException - * if field not found - */ - public RefField findField(RefClass type) { - return findField(type.clazz); - } + /** + * find field by type + * + * @param type + * field type + * @return RefField + * @throws RuntimeException + * if field not found + */ + public RefField findField(final RefClass type) { + return findField(type.clazz); + } - /** - * find field by type - * - * @param type - * field type - * @return RefField - * @throws RuntimeException - * if field not found - */ - public RefField findField(Class type) { - if (type == null) { - type = void.class; - } - List fields = new ArrayList<>(); - Collections.addAll(fields, this.clazz.getFields()); - Collections.addAll(fields, this.clazz.getDeclaredFields()); - for (Field f : fields) { - if (type.equals(f.getType())) { - return new RefField(f); - } - } - throw new RuntimeException("no such field"); - } - } + /** + * find field by type + * + * @param type + * field type + * @return RefField + * @throws RuntimeException + * if field not found + */ + public RefField findField(Class type) { + if (type == null) { + type = void.class; + } + final List fields = new ArrayList<>(); + Collections.addAll(fields, this.clazz.getFields()); + Collections.addAll(fields, this.clazz.getDeclaredFields()); + for (final Field f : fields) { + if (type.equals(f.getType())) { + return new RefField(f); + } + } + throw new RuntimeException("no such field"); + } + } - /** - * Method wrapper - */ - public static class RefMethod { - private final Method method; + /** + * Method wrapper + */ + public static class RefMethod { + private final Method method; - /** - * @return passed method - */ - public Method getRealMethod() { - return this.method; - } + /** + * @return passed method + */ + public Method getRealMethod() { + return this.method; + } - /** - * @return owner class of method - */ - public RefClass getRefClass() { - return new RefClass(this.method.getDeclaringClass()); - } + /** + * @return owner class of method + */ + public RefClass getRefClass() { + return new RefClass(this.method.getDeclaringClass()); + } - /** - * @return class of method return type - */ - public RefClass getReturnRefClass() { - return new RefClass(this.method.getReturnType()); - } + /** + * @return class of method return type + */ + public RefClass getReturnRefClass() { + return new RefClass(this.method.getReturnType()); + } - private RefMethod(Method method) { - this.method = method; - method.setAccessible(true); - } + private RefMethod(final Method method) { + this.method = method; + method.setAccessible(true); + } - /** - * apply method to object - * - * @param e - * object to which the method is applied - * @return RefExecutor with method call(...) - */ - public RefExecutor of(Object e) { - return new RefExecutor(e); - } + /** + * apply method to object + * + * @param e + * object to which the method is applied + * @return RefExecutor with method call(...) + */ + public RefExecutor of(final Object e) { + return new RefExecutor(e); + } - /** - * call static method - * - * @param params - * sent parameters - * @return return value - */ - public Object call(Object... params) { - try { - return this.method.invoke(null, params); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * call static method + * + * @param params + * sent parameters + * @return return value + */ + public Object call(final Object... params) { + try { + return this.method.invoke(null, params); + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } - public class RefExecutor { - Object e; + public class RefExecutor { + Object e; - public RefExecutor(Object e) { - this.e = e; - } + public RefExecutor(final Object e) { + this.e = e; + } - /** - * apply method for selected object - * - * @param params - * sent parameters - * @return return value - * @throws RuntimeException - * if something went wrong - */ - public Object call(Object... params) { - try { - return RefMethod.this.method.invoke(this.e, params); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } + /** + * apply method for selected object + * + * @param params + * sent parameters + * @return return value + * @throws RuntimeException + * if something went wrong + */ + public Object call(final Object... params) { + try { + return RefMethod.this.method.invoke(this.e, params); + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } + } + } - /** - * Constructor wrapper - */ - public static class RefConstructor { - private final Constructor constructor; + /** + * Constructor wrapper + */ + public static class RefConstructor { + private final Constructor constructor; - /** - * @return passed constructor - */ - public Constructor getRealConstructor() { - return this.constructor; - } + /** + * @return passed constructor + */ + public Constructor getRealConstructor() { + return this.constructor; + } - /** - * @return owner class of method - */ - public RefClass getRefClass() { - return new RefClass(this.constructor.getDeclaringClass()); - } + /** + * @return owner class of method + */ + public RefClass getRefClass() { + return new RefClass(this.constructor.getDeclaringClass()); + } - private RefConstructor(Constructor constructor) { - this.constructor = constructor; - constructor.setAccessible(true); - } + private RefConstructor(final Constructor constructor) { + this.constructor = constructor; + constructor.setAccessible(true); + } - /** - * create new instance with constructor - * - * @param params - * parameters for constructor - * @return new object - * @throws RuntimeException - * if something went wrong - */ - public Object create(Object... params) { - try { - return this.constructor.newInstance(params); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - } + /** + * create new instance with constructor + * + * @param params + * parameters for constructor + * @return new object + * @throws RuntimeException + * if something went wrong + */ + public Object create(final Object... params) { + try { + return this.constructor.newInstance(params); + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } + } - public static class RefField { - private Field field; + public static class RefField { + private final Field field; - /** - * @return passed field - */ - public Field getRealField() { - return this.field; - } + /** + * @return passed field + */ + public Field getRealField() { + return this.field; + } - /** - * @return owner class of field - */ - public RefClass getRefClass() { - return new RefClass(this.field.getDeclaringClass()); - } + /** + * @return owner class of field + */ + public RefClass getRefClass() { + return new RefClass(this.field.getDeclaringClass()); + } - /** - * @return type of field - */ - public RefClass getFieldRefClass() { - return new RefClass(this.field.getType()); - } + /** + * @return type of field + */ + public RefClass getFieldRefClass() { + return new RefClass(this.field.getType()); + } - private RefField(Field field) { - this.field = field; - field.setAccessible(true); - } + private RefField(final Field field) { + this.field = field; + field.setAccessible(true); + } - /** - * apply fiend for object - * - * @param e - * applied object - * @return RefExecutor with getter and setter - */ - public RefExecutor of(Object e) { - return new RefExecutor(e); - } + /** + * apply fiend for object + * + * @param e + * applied object + * @return RefExecutor with getter and setter + */ + public RefExecutor of(final Object e) { + return new RefExecutor(e); + } - public class RefExecutor { - Object e; + public class RefExecutor { + Object e; - public RefExecutor(Object e) { - this.e = e; - } + public RefExecutor(final Object e) { + this.e = e; + } - /** - * set field value for applied object - * - * @param param - * value - */ - public void set(Object param) { - try { - RefField.this.field.set(this.e, param); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * set field value for applied object + * + * @param param + * value + */ + public void set(final Object param) { + try { + RefField.this.field.set(this.e, param); + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } - /** - * get field value for applied object - * - * @return value of field - */ - public Object get() { - try { - return RefField.this.field.get(this.e); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } + /** + * get field value for applied object + * + * @return value of field + */ + public Object get() { + try { + return RefField.this.field.get(this.e); + } + catch (final Exception e) { + throw new RuntimeException(e); + } + } + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/SchematicHandler.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/SchematicHandler.java index 2ad94f1d4..efd6c4121 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/SchematicHandler.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/SchematicHandler.java @@ -1,14 +1,5 @@ package com.intellectualcrafters.plot; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.plugin.java.JavaPlugin; - -import com.intellectualcrafters.jnbt.*; -import com.intellectualcrafters.plot.SchematicHandler.DataCollection; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -21,263 +12,342 @@ import java.util.Map; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.plugin.java.JavaPlugin; + +import com.intellectualcrafters.jnbt.ByteArrayTag; +import com.intellectualcrafters.jnbt.CompoundTag; +import com.intellectualcrafters.jnbt.IntTag; +import com.intellectualcrafters.jnbt.ListTag; +import com.intellectualcrafters.jnbt.NBTInputStream; +import com.intellectualcrafters.jnbt.NBTOutputStream; +import com.intellectualcrafters.jnbt.ShortTag; +import com.intellectualcrafters.jnbt.StringTag; +import com.intellectualcrafters.jnbt.Tag; + /** * Schematic Handler + * * @author Citymonstret * @author Empire92 */ -@SuppressWarnings({"all"}) +@SuppressWarnings({ "all" }) public class SchematicHandler { /** * Paste a schematic - * @param location origin - * @param schematic schematic to paste - * @param plot plot to paste in + * + * @param location + * origin + * @param schematic + * schematic to paste + * @param plot + * plot to paste in * @return true if succeeded */ - public static boolean paste(Location location, Schematic schematic, Plot plot, int x_offset, int z_offset) { - if (schematic == null) { - PlotMain.sendConsoleSenderMessage("Schematic == null :|"); - return false; - } - try { - Dimension demensions = schematic.getSchematicDimension(); - - int WIDTH = demensions.getX(); - int LENGTH = demensions.getZ(); - int HEIGHT = demensions.getY(); - - DataCollection[] blocks = schematic.getBlockCollection(); - - - - Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); - - int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX()+1, l1.getBlockZ()+1); - - l1 = l1.add(1, sy-1, 1); - - World world = location.getWorld(); - - for (int x = 0; x < WIDTH; x++) { - for (int z = 0; z < LENGTH; z++) { - for (int y = 0; y < HEIGHT; y++) { - int index = y * WIDTH * LENGTH + z * WIDTH + x; - - short id = blocks[index].getBlock(); - byte data = blocks[index].getData(); - - Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset); - - PlotBlock plotblock = new PlotBlock(id, data); - - PlotHelper.setBlock(block, plotblock); - } - } + public static boolean paste(final Location location, final Schematic schematic, final Plot plot, final int x_offset, final int z_offset) { + if (schematic == null) { + PlotMain.sendConsoleSenderMessage("Schematic == null :|"); + return false; + } + try { + final Dimension demensions = schematic.getSchematicDimension(); + + final int WIDTH = demensions.getX(); + final int LENGTH = demensions.getZ(); + final int HEIGHT = demensions.getY(); + + final DataCollection[] blocks = schematic.getBlockCollection(); + + Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); + + final int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX() + 1, l1.getBlockZ() + 1); + + l1 = l1.add(1, sy - 1, 1); + + final World world = location.getWorld(); + + int y_offset; + if (HEIGHT == location.getWorld().getMaxHeight()) { + y_offset = 0; } - } - catch (Exception e) { - return false; - } - return true; - } + else { + y_offset = l1.getBlockY(); + } + + for (int x = 0; x < WIDTH; x++) { + for (int z = 0; z < LENGTH; z++) { + for (int y = 0; y < HEIGHT; y++) { + final int index = (y * WIDTH * LENGTH) + (z * WIDTH) + x; + + final DataCollection block = blocks[index]; + + final short id = block.getBlock(); + final byte data = block.getData(); + + // if (block.tag != null) { + // WorldEditUtils.setNBT(world, id, data, l1.getBlockX() + // + x + x_offset, y + y_offset, l1.getBlockZ() + z + + // z_offset, block.tag); + // } + // else { + final Block bukkitBlock = world.getBlockAt(l1.getBlockX() + x + x_offset, y + y_offset, l1.getBlockZ() + z + z_offset); + + final PlotBlock plotblock = new PlotBlock(id, data); + + PlotHelper.setBlock(bukkitBlock, plotblock); + // } + } + } + } + } + catch (final Exception e) { + return false; + } + return true; + } /** * Get a schematic - * @param name to check + * + * @param name + * to check * @return schematic if found, else null */ - public static Schematic getSchematic(String name) { - { - File parent = - new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"); - if (!parent.exists()) { - parent.mkdir(); - } - } - File file = - new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" - + File.separator + name + ".schematic"); - if (!file.exists()) { - PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist"); - return null; - } + public static Schematic getSchematic(final String name) { + { + final File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"); + if (!parent.exists()) { + parent.mkdir(); + } + } + final File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic"); + if (!file.exists()) { + PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist"); + return null; + } - Schematic schematic; - try { - InputStream iStream = new FileInputStream(file); - NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream)); - CompoundTag tag = (CompoundTag) stream.readTag(); - stream.close(); - Map tagMap = tag.getValue(); + Schematic schematic; + try { + final InputStream iStream = new FileInputStream(file); + final NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream)); + final CompoundTag tag = (CompoundTag) stream.readTag(); + stream.close(); + final Map tagMap = tag.getValue(); - byte[] addId = new byte[0]; - if (tagMap.containsKey("AddBlocks")) { - addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); - } - short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); - short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); - short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); + byte[] addId = new byte[0]; + if (tagMap.containsKey("AddBlocks")) { + addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); + } + final short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); + final short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); + final short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); - byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); - byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); - short[] blocks = new short[b.length]; + final byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); + final byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); + final short[] blocks = new short[b.length]; - Dimension dimension = new Dimension(width, height, length); + final Dimension dimension = new Dimension(width, height, length); - for (int index = 0; index < b.length; index++) { - if ((index >> 1) >= addId.length) { // No corresponding - // AddBlocks index - blocks[index] = (short) (b[index] & 0xFF); - } - else { - if ((index & 1) == 0) { - blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); - } - else { - blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); - } - } - } + for (int index = 0; index < b.length; index++) { + if ((index >> 1) >= addId.length) { // No corresponding + // AddBlocks index + blocks[index] = (short) (b[index] & 0xFF); + } + else { + if ((index & 1) == 0) { + blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); + } + else { + blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); + } + } + } - DataCollection[] collection = new DataCollection[b.length]; + final DataCollection[] collection = new DataCollection[b.length]; - for (int x = 0; x < b.length; x++) { - collection[x] = new DataCollection(blocks[x], d[x]); - } - - schematic = new Schematic(collection, dimension, file); - } - catch (Exception e) { - e.printStackTrace(); - return null; - } - return schematic; - } + for (int x = 0; x < b.length; x++) { + collection[x] = new DataCollection(blocks[x], d[x]); + } + // if (PlotMain.worldEdit!=null) { + // List tileEntities = requireTag(tagMap, "TileEntities", + // ListTag.class).getValue(); + // + // for (Tag blocktag : tileEntities) { + // if (!(blocktag instanceof CompoundTag)) continue; + // CompoundTag t = (CompoundTag) blocktag; + // + // int x = 0; + // int y = 0; + // int z = 0; + // + // Map values = new HashMap(); + // + // for (Map.Entry entry : t.getValue().entrySet()) { + // if (entry.getKey().equals("x")) { + // if (entry.getValue() instanceof IntTag) { + // x = ((IntTag) entry.getValue()).getValue(); + // } + // } else if (entry.getKey().equals("y")) { + // if (entry.getValue() instanceof IntTag) { + // y = ((IntTag) entry.getValue()).getValue(); + // } + // } else if (entry.getKey().equals("z")) { + // if (entry.getValue() instanceof IntTag) { + // z = ((IntTag) entry.getValue()).getValue(); + // } + // } + // + // values.put(entry.getKey(), entry.getValue()); + // } + // + // int index = y * width * length + z * height + x; + // collection[index].tag = new CompoundTag("", values); + // } + // } + schematic = new Schematic(collection, dimension, file); + } + catch (final Exception e) { + e.printStackTrace(); + return null; + } + return schematic; + } /** * Schematic Class + * * @author Citymonstret */ - public static class Schematic { - private DataCollection[] blockCollection; - private Dimension schematicDimension; - private File file; + public static class Schematic { + private final DataCollection[] blockCollection; + private final Dimension schematicDimension; + private final File file; - public Schematic(DataCollection[] blockCollection, Dimension schematicDimension, File file) { - this.blockCollection = blockCollection; - this.schematicDimension = schematicDimension; - this.file = file; - } + public Schematic(final DataCollection[] blockCollection, final Dimension schematicDimension, final File file) { + this.blockCollection = blockCollection; + this.schematicDimension = schematicDimension; + this.file = file; + } - public File getFile() { - return this.file; - } + public File getFile() { + return this.file; + } - public Dimension getSchematicDimension() { - return this.schematicDimension; - } + public Dimension getSchematicDimension() { + return this.schematicDimension; + } - public DataCollection[] getBlockCollection() { - return this.blockCollection; - } - } + public DataCollection[] getBlockCollection() { + return this.blockCollection; + } + } /** * Schematic Dimensions + * * @author Citymonstret */ - public static class Dimension { - private int x; - private int y; - private int z; + public static class Dimension { + private final int x; + private final int y; + private final int z; - public Dimension(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = 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 this.x; - } + public int getX() { + return this.x; + } - public int getY() { - return this.y; - } + public int getY() { + return this.y; + } + + public int getZ() { + return this.z; + } + } + + /** + * Saves a schematic to a file path + * + * @param tag + * to save + * @param path + * to save in + * @return true if succeeded + */ + public static boolean save(final CompoundTag tag, final String path) { + + if (tag == null) { + PlotMain.sendConsoleSenderMessage("&cCannot save empty tag"); + return false; + } - public int getZ() { - return this.z; - } - } - - /** - * Saves a schematic to a file path - * @param tag to save - * @param path to save in - * @return true if succeeded - */ - public static boolean save(CompoundTag tag, String path) { - - if (tag==null) { - PlotMain.sendConsoleSenderMessage("&cCannot save empty tag"); - return false; - } - try { - OutputStream stream = new FileOutputStream(path); - NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream)); + final OutputStream stream = new FileOutputStream(path); + final NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream)); output.writeTag(tag); output.close(); stream.close(); - } catch (IOException e) { + } + catch (final IOException e) { e.printStackTrace(); return false; } return true; - } - - /** - * Gets the schematic of a plot - * @param world to check - * @param id plot - * @return tag - */ - public static CompoundTag getCompoundTag(World world, PlotId id) { + } - if (!PlotMain.getPlots(world).containsKey(id)) { - return null; - // Plot is empty - } - - // loading chunks - final Location pos1 = PlotHelper.getPlotBottomLoc(world, id).add(1, 0, 1); + /** + * Gets the schematic of a plot + * + * @param world + * to check + * @param id + * plot + * @return tag + */ + public static CompoundTag getCompoundTag(final World world, final PlotId id) { + + if (!PlotMain.getPlots(world).containsKey(id)) { + return null; + // Plot is empty + } + + // loading chunks + final Location pos1 = PlotHelper.getPlotBottomLoc(world, id).add(1, 0, 1); final Location pos2 = PlotHelper.getPlotTopLoc(world, id); int i = 0; int j = 0; try { - for (i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { - for (j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) { - Chunk chunk = world.getChunkAt(i, j); - boolean result = chunk.load(false); - if (!result) { - - // Plot is not even generated - - return null; + for (i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { + for (j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) { + final Chunk chunk = world.getChunkAt(i, j); + final boolean result = chunk.load(false); + if (!result) { + + // Plot is not even generated + + return null; + } } } } - } - catch (Exception e) { - PlotMain.sendConsoleSenderMessage("&7 - Cannot save: corrupt chunk at "+(i/16)+", "+(j/16)); + catch (final Exception e) { + PlotMain.sendConsoleSenderMessage("&7 - Cannot save: corrupt chunk at " + (i / 16) + ", " + (j / 16)); return null; } - int width = pos2.getBlockX()-pos1.getBlockX()+1; - int height = 256; - int length = pos2.getBlockZ()-pos1.getBlockZ()+1; + final int width = (pos2.getBlockX() - pos1.getBlockX()) + 1; + final int height = 256; + final int length = (pos2.getBlockZ() - pos1.getBlockZ()) + 1; - HashMap schematic = new HashMap<>(); + final HashMap schematic = new HashMap<>(); schematic.put("Width", new ShortTag("Width", (short) width)); schematic.put("Length", new ShortTag("Length", (short) length)); schematic.put("Height", new ShortTag("Height", (short) height)); @@ -288,35 +358,33 @@ public class SchematicHandler { schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); - byte[] blocks = new byte[width * height * length]; + final byte[] blocks = new byte[width * height * length]; byte[] addBlocks = null; - byte[] blockData = new byte[width * height * length]; - + final byte[] blockData = new byte[width * height * length]; + for (int x = 0; x < width; x++) { for (int z = 0; z < length; z++) { for (int y = 0; y < height; y++) { - int index = y * width * length + z * width + x; + final int index = (y * width * length) + (z * width) + x; + + final Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z)); + + final int id2 = block.getTypeId(); - Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z)); - - int id2 = block.getTypeId(); - if (id2 > 255) { if (addBlocks == null) { addBlocks = new byte[(blocks.length >> 1) + 1]; } - addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? - addBlocks[index >> 1] & 0xF0 | (id2 >> 8) & 0xF - : addBlocks[index >> 1] & 0xF | ((id2 >> 8) & 0xF) << 4); + addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? (addBlocks[index >> 1] & 0xF0) | ((id2 >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((id2 >> 8) & 0xF) << 4)); } blocks[index] = (byte) id2; blockData[index] = block.getData(); - - + // We need worldedit to save tileentity data or entities - // - it uses NMS and CB internal code, which changes every update + // - it uses NMS and CB internal code, which changes every + // update } } } @@ -324,7 +392,7 @@ public class SchematicHandler { schematic.put("Data", new ByteArrayTag("Data", blockData)); schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, new ArrayList())); - + if (addBlocks != null) { schematic.put("AddBlocks", new ByteArrayTag("AddBlocks", addBlocks)); } @@ -334,51 +402,54 @@ public class SchematicHandler { /** * Schematic Data Collection + * * @author Citymonstret */ - public static class DataCollection { - private short block; - private byte data; + public static class DataCollection { + private final short block; + private final byte data; - public DataCollection(short block, byte data) { - this.block = block; - this.data = data; - } + // public CompoundTag tag; - public short getBlock() { - return this.block; - } + public DataCollection(final short block, final byte data) { + this.block = block; + this.data = data; + } - public byte getData() { - return this.data; - } - } + public short getBlock() { + return this.block; + } - public static boolean pastePart(World world, DataCollection[] blocks, Location l1, int x_offset, int z_offset, int i1, int i2, int WIDTH, int LENGTH) { + public byte getData() { + return this.data; + } + } + + public static boolean pastePart(final World world, final DataCollection[] blocks, final Location l1, final int x_offset, final int z_offset, final int i1, final int i2, final int WIDTH, final int LENGTH) { boolean result = false; - for (int i = i1; i<=i2 ;i++) { - short id = blocks[i].getBlock(); - byte data = blocks[i].getData(); - if (id==0) { - continue; - } - - int area = WIDTH*LENGTH; - int r = i%(area); + for (int i = i1; i <= i2; i++) { + final short id = blocks[i].getBlock(); + final byte data = blocks[i].getData(); + if (id == 0) { + continue; + } - int x = r%WIDTH; - int y = i/area; - int z = r/WIDTH; - - if (y>256) { + final int area = WIDTH * LENGTH; + final int r = i % (area); + + final int x = r % WIDTH; + final int y = i / area; + final int z = r / WIDTH; + + if (y > 256) { break; } - - Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset); - - PlotBlock plotblock = new PlotBlock(id, data); - - boolean set = PlotHelper.setBlock(block, plotblock); + + final Block block = world.getBlockAt(l1.getBlockX() + x + x_offset, l1.getBlockY() + y, l1.getBlockZ() + z + z_offset); + + final PlotBlock plotblock = new PlotBlock(id, data); + + final boolean set = PlotHelper.setBlock(block, plotblock); if (!result && set) { result = true; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/SetBlockFast.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/SetBlockFast.java index 525012444..3a0ec2b0e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/SetBlockFast.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/SetBlockFast.java @@ -13,38 +13,38 @@ import com.intellectualcrafters.plot.ReflectionUtils.RefMethod; */ public class SetBlockFast { - private static final RefClass classBlock = getRefClass("{nms}.Block"); - private static final RefClass classChunk = getRefClass("{nms}.Chunk"); - private static final RefClass classWorld = getRefClass("{nms}.World"); - private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); + private static final RefClass classBlock = getRefClass("{nms}.Block"); + private static final RefClass classChunk = getRefClass("{nms}.Chunk"); + private static final RefClass classWorld = getRefClass("{nms}.World"); + private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - private static RefMethod methodGetHandle; - private static RefMethod methodGetChunkAt; - private static RefMethod methodA; - private static RefMethod methodGetById; + private static RefMethod methodGetHandle; + private static RefMethod methodGetChunkAt; + private static RefMethod methodA; + private static RefMethod methodGetById; - public SetBlockFast() throws NoSuchMethodException { - methodGetHandle = classCraftWorld.getMethod("getHandle"); - methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); - methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class); - methodGetById = classBlock.getMethod("getById", int.class); - } + public SetBlockFast() throws NoSuchMethodException { + methodGetHandle = classCraftWorld.getMethod("getHandle"); + methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); + methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class); + methodGetById = classBlock.getMethod("getById", int.class); + } - public static boolean set(org.bukkit.World world, int x, int y, int z, int blockId, byte data) throws NoSuchMethodException { + public static boolean set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data) throws NoSuchMethodException { - Object w = methodGetHandle.of(world).call(); - Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4); - Object block = methodGetById.of(null).call(blockId); - methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data); - return true; - } + final Object w = methodGetHandle.of(world).call(); + final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4); + final Object block = methodGetById.of(null).call(blockId); + methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data); + return true; + } - public static void update(org.bukkit.entity.Player player) { - int distance = Bukkit.getViewDistance() + 1; - for (int cx = -distance; cx < distance; cx++) { - for (int cz = -distance; cz < distance; cz++) { - player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz); - } - } - } + public static void update(final org.bukkit.entity.Player player) { + final int distance = Bukkit.getViewDistance() + 1; + for (int cx = -distance; cx < distance; cx++) { + for (int cz = -distance; cz < distance; cz++) { + player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz); + } + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Settings.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Settings.java index 7c53c2e6a..e9bd3c4fc 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Settings.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Settings.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Settings.java >> Generated by: Citymonstret at 2014-08-09 01:44 */ @@ -15,118 +15,116 @@ package com.intellectualcrafters.plot; * @author Empire92 */ public class Settings { - public static boolean TITLES = true; + public static boolean TITLES = true; /** * Schematic Save Path */ - public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics"; + public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics"; /** * Max allowed plots */ - public static int MAX_PLOTS = 20; - /** - * WorldGuard region on claimed plots - */ - public static boolean WORLDGUARD = false; - /** - * metrics - */ - public static boolean METRICS = true; - /** - * plot specific resource pack - */ - public static String PLOT_SPECIFIC_RESOURCE_PACK = ""; - /** - * Kill road mobs? - */ - public static boolean KILL_ROAD_MOBS; - /** - * Default kill road mobs: true - */ - public static boolean KILL_ROAD_MOBS_DEFAULT = true; - /** - * mob pathfinding? - */ - public static boolean MOB_PATHFINDING; - /** - * Default mob pathfinding: true - */ - public static boolean MOB_PATHFINDING_DEFAULT = true; + public static int MAX_PLOTS = 20; + /** + * WorldGuard region on claimed plots + */ + public static boolean WORLDGUARD = false; + /** + * metrics + */ + public static boolean METRICS = true; + /** + * plot specific resource pack + */ + public static String PLOT_SPECIFIC_RESOURCE_PACK = ""; + /** + * Kill road mobs? + */ + public static boolean KILL_ROAD_MOBS; + /** + * Default kill road mobs: true + */ + public static boolean KILL_ROAD_MOBS_DEFAULT = true; + /** + * mob pathfinding? + */ + public static boolean MOB_PATHFINDING; + /** + * Default mob pathfinding: true + */ + public static boolean MOB_PATHFINDING_DEFAULT = true; /** * Delete plots on ban? */ - public static boolean DELETE_PLOTS_ON_BAN = false; + public static boolean DELETE_PLOTS_ON_BAN = false; /** * Verbose? */ - public static boolean DEBUG = true; + public static boolean DEBUG = true; /** * Auto clear enabled */ - public static boolean AUTO_CLEAR = false; + public static boolean AUTO_CLEAR = false; /** * Days until a plot gets cleared */ - public static int AUTO_CLEAR_DAYS = 365; + public static int AUTO_CLEAR_DAYS = 365; /** * API Location */ - public static String API_URL = "http://www.intellectualsites.com/minecraft.php"; + public static String API_URL = "http://www.intellectualsites.com/minecraft.php"; /** * Use the custom API */ - public static boolean CUSTOM_API = true; + public static boolean CUSTOM_API = true; - - /** - * Database settings - * - * @author Citymonstret - */ - public static class DB { + /** + * Database settings + * + * @author Citymonstret + */ + public static class DB { /** * MongoDB enabled? */ - public static boolean USE_MONGO = false; /* - * TODO: Implement Mongo - * - * @Brandon - */ + public static boolean USE_MONGO = false; /* + * TODO: Implement Mongo + * @Brandon + */ /** * SQLite enabled? */ - public static boolean USE_SQLITE = false; + public static boolean USE_SQLITE = false; /** * MySQL Enabled? */ - public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ + public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ /** * SQLite Database name */ - public static String SQLITE_DB = "storage"; + public static String SQLITE_DB = "storage"; /** * MySQL Host name */ - public static String HOST_NAME = "localhost"; + public static String HOST_NAME = "localhost"; /** * MySQL Port */ - public static String PORT = "3306"; + public static String PORT = "3306"; /** * MySQL DB */ - public static String DATABASE = "plot_db"; + public static String DATABASE = "plot_db"; /** * MySQL User */ - public static String USER = "root"; + public static String USER = "root"; /** * MySQL Password */ - public static String PASSWORD = "password"; + public static String PASSWORD = "password"; /** * MySQL Prefix */ - public static String PREFIX = ""; - } + public static String PREFIX = ""; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringComparsion.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringComparsion.java index b1c9e809e..e5aefa907 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringComparsion.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringComparsion.java @@ -5,6 +5,7 @@ import java.util.Collections; /** * String comparsion library + * * @author Citymonstret */ public class StringComparsion { @@ -12,12 +13,12 @@ public class StringComparsion { private String bestMatch; private double match; - public StringComparsion(String input, Object[] objects) { + public StringComparsion(final String input, final Object[] objects) { double c = 0; - for(Object o : objects) { - if((c = compare(input, o.toString())) > match) { - match = c; - bestMatch = o.toString(); + for (final Object o : objects) { + if ((c = compare(input, o.toString())) > this.match) { + this.match = c; + this.bestMatch = o.toString(); } } } @@ -27,19 +28,16 @@ public class StringComparsion { } public Object[] getBestMatchAdvanced() { - return new Object[] { - match, - bestMatch - }; + return new Object[] { this.match, this.bestMatch }; } - public static double compare(String s1, String s2) { - ArrayList p1 = wLetterPair(s1.toUpperCase()), - p2 = wLetterPair(s2.toUpperCase()); - int intersection = 0, union = p1.size() + p2.size(); - for (Object aP1 : p1) { - for(Object aP2 : p2) { - if(aP1.equals(aP2)) { + public static double compare(final String s1, final String s2) { + final ArrayList p1 = wLetterPair(s1.toUpperCase()), p2 = wLetterPair(s2.toUpperCase()); + int intersection = 0; + final int union = p1.size() + p2.size(); + for (final Object aP1 : p1) { + for (final Object aP2 : p2) { + if (aP1.equals(aP2)) { intersection++; p2.remove(aP2); break; @@ -49,21 +47,22 @@ public class StringComparsion { return (2.0 * intersection) / union; } - public static ArrayList wLetterPair(String s) { - ArrayList aPairs = new ArrayList<>(); - String[] wo = s.split("\\s"); - for (String aWo : wo) { - String[] po = sLetterPair(aWo); + public static ArrayList wLetterPair(final String s) { + final ArrayList aPairs = new ArrayList<>(); + final String[] wo = s.split("\\s"); + for (final String aWo : wo) { + final String[] po = sLetterPair(aWo); Collections.addAll(aPairs, po); } return aPairs; } - public static String[] sLetterPair(String s) { - int numPair = s.length() - 1; - String[] p = new String[numPair]; - for(int i = 0; i < numPair; i++) + public static String[] sLetterPair(final String s) { + final int numPair = s.length() - 1; + final String[] p = new String[numPair]; + for (int i = 0; i < numPair; i++) { p[i] = s.substring(i, i + 2); + } return p; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringWrapper.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringWrapper.java index 5bfe62c4e..8a84a0977 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringWrapper.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/StringWrapper.java @@ -8,19 +8,23 @@ public class StringWrapper { /** * Constructor - * @param value to wrap + * + * @param value + * to wrap */ - public StringWrapper(String value) { + public StringWrapper(final String value) { this.value = value; } /** * Check if a wrapped string equals another one - * @param obj to compare + * + * @param obj + * to compare * @return true if obj equals the stored value */ @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -30,12 +34,13 @@ public class StringWrapper { if (getClass() != obj.getClass()) { return false; } - StringWrapper other = (StringWrapper) obj; + final StringWrapper other = (StringWrapper) obj; return other.value.toLowerCase().equals(this.value.toLowerCase()); } /** * Get the string value + * * @return string value */ @Override @@ -45,6 +50,7 @@ public class StringWrapper { /** * Get the hash value + * * @return has value */ @Override diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Title.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Title.java index 9459b3a38..9de183261 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/Title.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/Title.java @@ -17,410 +17,399 @@ import org.bukkit.entity.Player; */ @SuppressWarnings("unused") public class Title { - /* Title packet */ - private Class packetTitle; - /* Title packet actions ENUM */ - private Class packetActions; - /* Chat serializer */ - private Class nmsChatSerializer; - /* Title text and color */ - private String title = ""; - private ChatColor titleColor = ChatColor.WHITE; - /* Subtitle text and color */ - private String subtitle = ""; - private ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ - private int fadeInTime = -1; - private int stayTime = -1; - private int fadeOutTime = -1; - private boolean ticks = false; + /* Title packet */ + private Class packetTitle; + /* Title packet actions ENUM */ + private Class packetActions; + /* Chat serializer */ + private Class nmsChatSerializer; + /* Title text and color */ + private String title = ""; + private ChatColor titleColor = ChatColor.WHITE; + /* Subtitle text and color */ + private String subtitle = ""; + private ChatColor subtitleColor = ChatColor.WHITE; + /* Title timings */ + private int fadeInTime = -1; + private int stayTime = -1; + private int fadeOutTime = -1; + private boolean ticks = false; - private static final Map, Class> CORRESPONDING_TYPES; + private static final Map, Class> CORRESPONDING_TYPES; - static { - CORRESPONDING_TYPES = new HashMap<>(); - } + static { + CORRESPONDING_TYPES = new HashMap<>(); + } - /** - * Create a new 1.8 title - * - * @param title - * Title - */ - public Title(String title) { - this.title = title; - loadClasses(); - } + /** + * Create a new 1.8 title + * + * @param title + * Title + */ + public Title(final String title) { + this.title = title; + loadClasses(); + } - /** - * Create a new 1.8 title - * - * @param title - * Title text - * @param subtitle - * Subtitle text - */ - public Title(String title, String subtitle) { - this.title = title; - this.subtitle = subtitle; - loadClasses(); - } + /** + * Create a new 1.8 title + * + * @param title + * Title text + * @param subtitle + * Subtitle text + */ + public Title(final String title, final String subtitle) { + this.title = title; + this.subtitle = subtitle; + loadClasses(); + } - /** - * Create a new 1.8 title - * - * @param title - * Title text - * @param subtitle - * Subtitle text - * @param fadeInTime - * Fade in time - * @param stayTime - * Stay on screen time - * @param fadeOutTime - * Fade out time - */ - public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { - this.title = title; - this.subtitle = subtitle; - this.fadeInTime = fadeInTime; - this.stayTime = stayTime; - this.fadeOutTime = fadeOutTime; - loadClasses(); - } + /** + * Create a new 1.8 title + * + * @param title + * Title text + * @param subtitle + * Subtitle text + * @param fadeInTime + * Fade in time + * @param stayTime + * Stay on screen time + * @param fadeOutTime + * Fade out time + */ + public Title(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) { + this.title = title; + this.subtitle = subtitle; + this.fadeInTime = fadeInTime; + this.stayTime = stayTime; + this.fadeOutTime = fadeOutTime; + loadClasses(); + } - /** - * Load spigot and NMS classes - */ - private void loadClasses() { - this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); - this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); - this.nmsChatSerializer = getNMSClass("ChatSerializer"); - } + /** + * Load spigot and NMS classes + */ + private void loadClasses() { + this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); + this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); + this.nmsChatSerializer = getNMSClass("ChatSerializer"); + } - /** - * Set the title color - * - * @param color - * Chat color - */ - public void setTitleColor(ChatColor color) { - this.titleColor = color; - } + /** + * Set the title color + * + * @param color + * Chat color + */ + public void setTitleColor(final ChatColor color) { + this.titleColor = color; + } - /** - * Set the subtitle color - * - * @param color - * Chat color - */ - public void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } + /** + * Set the subtitle color + * + * @param color + * Chat color + */ + public void setSubtitleColor(final ChatColor color) { + this.subtitleColor = color; + } - /** - * Set title fade in time - * - * @param time - * Time - */ - public void setFadeInTime(int time) { - this.fadeInTime = time; - } + /** + * Set title fade in time + * + * @param time + * Time + */ + public void setFadeInTime(final int time) { + this.fadeInTime = time; + } - /** - * Set title fade out time - * - * @param time - * Time - */ - public void setFadeOutTime(int time) { - this.fadeOutTime = time; - } + /** + * Set title fade out time + * + * @param time + * Time + */ + public void setFadeOutTime(final int time) { + this.fadeOutTime = time; + } - /** - * Set title stay time - * - * @param time - * Time - */ - public void setStayTime(int time) { - this.stayTime = time; - } + /** + * Set title stay time + * + * @param time + * Time + */ + public void setStayTime(final int time) { + this.stayTime = time; + } - /** - * Set timings to ticks - */ - public void setTimingsToTicks() { - this.ticks = true; - } + /** + * Set timings to ticks + */ + public void setTimingsToTicks() { + this.ticks = true; + } - /** - * Set timings to seconds - */ - public void setTimingsToSeconds() { - this.ticks = false; - } + /** + * Set timings to seconds + */ + public void setTimingsToSeconds() { + this.ticks = false; + } - /** - * Send the title to a player - * - * @param player - * Player - */ - public void send(Player player) { - if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { - // First reset previous settings - resetTitle(player); - try { - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = - this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime - * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime - * (this.ticks ? 1 : 20)); - // Send if set - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { - sendPacket.invoke(connection, packet); - } + /** + * Send the title to a player + * + * @param player + * Player + */ + public void send(final Player player) { + if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { + // First reset previous settings + resetTitle(player); + try { + // Send timings first + final Object handle = getHandle(player); + final Object connection = getField(handle.getClass(), "playerConnection").get(handle); + final Object[] actions = this.packetActions.getEnumConstants(); + final Method sendPacket = getMethod(connection.getClass(), "sendPacket"); + Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); + // Send if set + if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { + sendPacket.invoke(connection, packet); + } - // Send title - Object serialized = - getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" - + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" - + this.titleColor.name().toLowerCase() + "}"); - packet = - this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); - sendPacket.invoke(connection, packet); - if (!this.subtitle.equals("")) { - // Send subtitle if present - serialized = - getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" - + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" - + this.subtitleColor.name().toLowerCase() + "}"); - packet = - this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); - sendPacket.invoke(connection, packet); - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - } + // Send title + Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); + sendPacket.invoke(connection, packet); + if (!this.subtitle.equals("")) { + // Send subtitle if present + serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); + sendPacket.invoke(connection, packet); + } + } + catch (final Exception e) { + e.printStackTrace(); + } + } + } - /** - * Broadcast the title to all players - */ - public void broadcast() { - for (Player p : Bukkit.getOnlinePlayers()) { - send(p); - } - } + /** + * Broadcast the title to all players + */ + public void broadcast() { + for (final Player p : Bukkit.getOnlinePlayers()) { + send(p); + } + } - /** - * Clear the title - * - * @param player - * Player - */ - public void clearTitle(Player player) { - if ((getProtocolVersion(player) >= 47) && isSpigot()) { - try { - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); - sendPacket.invoke(connection, packet); - } - catch (Exception e) { - e.printStackTrace(); - } - } - } + /** + * Clear the title + * + * @param player + * Player + */ + public void clearTitle(final Player player) { + if ((getProtocolVersion(player) >= 47) && isSpigot()) { + try { + // Send timings first + final Object handle = getHandle(player); + final Object connection = getField(handle.getClass(), "playerConnection").get(handle); + final Object[] actions = this.packetActions.getEnumConstants(); + final Method sendPacket = getMethod(connection.getClass(), "sendPacket"); + final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); + sendPacket.invoke(connection, packet); + } + catch (final Exception e) { + e.printStackTrace(); + } + } + } - /** - * Reset the title settings - * - * @param player - * Player - */ - public void resetTitle(Player player) { - if ((getProtocolVersion(player) >= 47) && isSpigot()) { - try { - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); - sendPacket.invoke(connection, packet); - } - catch (Exception e) { - e.printStackTrace(); - } - } - } + /** + * Reset the title settings + * + * @param player + * Player + */ + public void resetTitle(final Player player) { + if ((getProtocolVersion(player) >= 47) && isSpigot()) { + try { + // Send timings first + final Object handle = getHandle(player); + final Object connection = getField(handle.getClass(), "playerConnection").get(handle); + final Object[] actions = this.packetActions.getEnumConstants(); + final Method sendPacket = getMethod(connection.getClass(), "sendPacket"); + final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); + sendPacket.invoke(connection, packet); + } + catch (final Exception e) { + e.printStackTrace(); + } + } + } - /** - * Get the protocol version of the player - * - * @param player - * Player - * @return Protocol version - */ - private int getProtocolVersion(Player player) { - int version = 0; - try { - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object networkManager = getValue("networkManager", connection); - version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); + /** + * Get the protocol version of the player + * + * @param player + * Player + * @return Protocol version + */ + private int getProtocolVersion(final Player player) { + int version = 0; + try { + final Object handle = getHandle(player); + final Object connection = getField(handle.getClass(), "playerConnection").get(handle); + final Object networkManager = getValue("networkManager", connection); + version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); - return version; - } - catch (Exception ex) { - // ex.printStackTrace(); <-- spammy console - } - return version; - } + return version; + } + catch (final Exception ex) { + // ex.printStackTrace(); <-- spammy console + } + return version; + } - /** - * Check if running spigot - * - * @return Spigot - */ - private boolean isSpigot() { - return Bukkit.getVersion().contains("Spigot"); - } + /** + * Check if running spigot + * + * @return Spigot + */ + private boolean isSpigot() { + return Bukkit.getVersion().contains("Spigot"); + } - /** - * Get class by url - * - * @param namespace - * Namespace url - * @return Class - */ - private Class getClass(String namespace) { - try { - return Class.forName(namespace); - } - catch (Exception e) { - return null; - } - } + /** + * Get class by url + * + * @param namespace + * Namespace url + * @return Class + */ + private Class getClass(final String namespace) { + try { + return Class.forName(namespace); + } + catch (final Exception e) { + return null; + } + } - private Field getField(String name, Class clazz) throws Exception { - return clazz.getDeclaredField(name); - } + private Field getField(final String name, final Class clazz) throws Exception { + return clazz.getDeclaredField(name); + } - private Object getValue(String name, Object obj) throws Exception { - Field f = getField(name, obj.getClass()); - f.setAccessible(true); - return f.get(obj); - } + private Object getValue(final String name, final Object obj) throws Exception { + final Field f = getField(name, obj.getClass()); + f.setAccessible(true); + return f.get(obj); + } - private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; - } + private Class getPrimitiveType(final Class clazz) { + return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; + } - private Class[] toPrimitiveTypeArray(Class[] classes) { - int a = classes != null ? classes.length : 0; - Class[] types = new Class[a]; - for (int i = 0; i < a; i++) { - types[i] = getPrimitiveType(classes[i]); - } - return types; - } + 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(Class[] a, Class[] o) { - if (a.length != o.length) { - return false; - } - for (int i = 0; i < a.length; i++) { - if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { - return false; - } - } - return true; - } + private static boolean equalsTypeArray(final Class[] a, final Class[] o) { + if (a.length != o.length) { + return false; + } + for (int i = 0; i < a.length; i++) { + if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { + return false; + } + } + return true; + } - private Object getHandle(Object obj) { - try { - return getMethod("getHandle", obj.getClass()).invoke(obj); - } - catch (Exception e) { - e.printStackTrace(); - return null; - } - } + private Object getHandle(final Object obj) { + try { + return getMethod("getHandle", obj.getClass()).invoke(obj); + } + catch (final Exception e) { + e.printStackTrace(); + return null; + } + } - private Method getMethod(String name, Class clazz, Class... paramTypes) { - Class[] t = toPrimitiveTypeArray(paramTypes); - for (Method m : clazz.getMethods()) { - Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); - if (m.getName().equals(name) && equalsTypeArray(types, t)) { - return m; - } - } - 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()) { + final Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); + if (m.getName().equals(name) && equalsTypeArray(types, t)) { + return m; + } + } + return null; + } - private String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - return name.substring(name.lastIndexOf('.') + 1) + "."; - } + private String getVersion() { + final String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf('.') + 1) + "."; + } - private Class getNMSClass(String className) { - String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } - catch (Exception e) { - e.printStackTrace(); - } - return clazz; - } + private Class getNMSClass(final String className) { + final String fullName = "net.minecraft.server." + getVersion() + className; + Class clazz = null; + try { + clazz = Class.forName(fullName); + } + catch (final Exception e) { + e.printStackTrace(); + } + return clazz; + } - private Field getField(Class clazz, String name) { - try { - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - return field; - } - catch (Exception e) { - e.printStackTrace(); - return null; - } - } + 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) { + e.printStackTrace(); + return null; + } + } - private Method getMethod(Class clazz, String name, Class... args) { - for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) { - m.setAccessible(true); - return m; - } - } - 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()))) { + m.setAccessible(true); + return m; + } + } + return null; + } - private boolean ClassListEqual(Class[] l1, Class[] l2) { - boolean equal = true; - if (l1.length != l2.length) { - return false; - } - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - equal = false; - break; - } - } - return equal; - } + private boolean ClassListEqual(final Class[] l1, final Class[] l2) { + boolean equal = true; + if (l1.length != l2.length) { + return false; + } + for (int i = 0; i < l1.length; i++) { + if (l1[i] != l2[i]) { + equal = false; + break; + } + } + return equal; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/UUIDHandler.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/UUIDHandler.java index 7e25e473d..2aaec3dae 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/UUIDHandler.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/UUIDHandler.java @@ -1,21 +1,23 @@ package com.intellectualcrafters.plot; +import java.util.Arrays; +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + import com.google.common.base.Charsets; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.intellectualcrafters.plot.uuid.NameFetcher; import com.intellectualcrafters.plot.uuid.UUIDFetcher; import com.intellectualcrafters.plot.uuid.UUIDSaver; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.UUID; /** - * This class can be used to efficiently translate UUIDs and names back and forth. + * This class can be used to efficiently translate UUIDs and names back and + * forth. * It uses three primary methods of achieving this: * - Read From Cache * - Read from OfflinePlayer objects @@ -23,30 +25,35 @@ import java.util.UUID; * All UUIDs/Usernames will be stored in a map (cache) until the server is * restarted. * - * You can use getUuidMap() to save the uuids/names to a file (SQLite db for example). - * Primary methods: getUUID(String name) & getName(UUID uuid) <-- You should ONLY use these. + * You can use getUuidMap() to save the uuids/names to a file (SQLite db for + * example). + * Primary methods: getUUID(String name) & getName(UUID uuid) <-- You should + * ONLY use these. * Call startFetch(JavaPlugin plugin) in your onEnable(). * * Originally created by: + * * @author Citymonstret * @author Empire92 - * for PlotSquared. + * for PlotSquared. */ public class UUIDHandler { /** * Online mode + * * @see org.bukkit.Server#getOnlineMode() */ - private static boolean online = Bukkit.getServer().getOnlineMode(); + private static boolean online = Bukkit.getServer().getOnlineMode(); /** * Map containing names and UUID's */ - private static BiMap uuidMap = HashBiMap.create(new HashMap()); + private static BiMap uuidMap = HashBiMap.create(new HashMap()); /** * Get the map containing all names/uuids + * * @return map with names + uuids */ public static BiMap getUuidMap() { @@ -55,222 +62,233 @@ public class UUIDHandler { /** * Check if a uuid is cached - * @param uuid to check + * + * @param uuid + * to check * @return true of the uuid is cached */ - public static boolean uuidExists(UUID uuid) { - return uuidMap.containsValue(uuid); - } + public static boolean uuidExists(final UUID uuid) { + return uuidMap.containsValue(uuid); + } /** * Check if a name is cached - * @param name to check + * + * @param name + * to check * @return true of the name is cached */ - public static boolean nameExists(StringWrapper name) { - return uuidMap.containsKey(name); - } + public static boolean nameExists(final StringWrapper name) { + return uuidMap.containsKey(name); + } /** * Add a set to the cache - * @param name to cache - * @param uuid to cache + * + * @param name + * to cache + * @param uuid + * to cache */ - public static void add(StringWrapper name, UUID uuid) { - if (!uuidMap.containsKey(name) && !uuidMap.inverse().containsKey(uuid)) { - uuidMap.put(name, uuid); - } - } + public static void add(final StringWrapper name, final UUID uuid) { + if (!uuidMap.containsKey(name) && !uuidMap.inverse().containsKey(uuid)) { + uuidMap.put(name, uuid); + } + } - /** - * @param name to use as key - * @return uuid - */ - public static UUID getUUID(String name) { - StringWrapper nameWrap = new StringWrapper(name); - if (uuidMap.containsKey(nameWrap)) { - return uuidMap.get(nameWrap); - } + /** + * @param name + * to use as key + * @return uuid + */ + public static UUID getUUID(final String name) { + final StringWrapper nameWrap = new StringWrapper(name); + if (uuidMap.containsKey(nameWrap)) { + return uuidMap.get(nameWrap); + } @SuppressWarnings("deprecation") - Player player = Bukkit.getPlayer(name); - if (player!=null) { - UUID uuid = player.getUniqueId(); - uuidMap.put(nameWrap, uuid); - return uuid; - } - UUID uuid; - if (online) { - if(Settings.CUSTOM_API) { + final Player player = Bukkit.getPlayer(name); + if (player != null) { + final UUID uuid = player.getUniqueId(); + uuidMap.put(nameWrap, uuid); + return uuid; + } + UUID uuid; + if (online) { + if (Settings.CUSTOM_API) { if ((uuid = getUuidOnlinePlayer(nameWrap)) != null) { return uuid; } try { return PlotMain.getUUIDSaver().mojangUUID(name); } - catch(Exception e) { + catch (final Exception e) { try { - UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); + final UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); uuid = fetcher.call().get(name); add(nameWrap, uuid); } - catch (Exception ex) { + catch (final Exception ex) { ex.printStackTrace(); } } - } else { + } + else { try { - UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); + final UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); uuid = fetcher.call().get(name); add(nameWrap, uuid); - } catch (Exception ex) { + } + catch (final Exception ex) { ex.printStackTrace(); } } - } - else { - return getUuidOfflineMode(nameWrap); - } + } + else { + return getUuidOfflineMode(nameWrap); + } return null; - } + } - /** - * @param uuid to use as key - * @return name (cache) - */ - private static StringWrapper loopSearch(UUID uuid) { - return uuidMap.inverse().get(uuid); - } + /** + * @param uuid + * to use as key + * @return name (cache) + */ + private static StringWrapper loopSearch(final UUID uuid) { + return uuidMap.inverse().get(uuid); + } - /** - * @param uuid to use as key - * @return Name - */ - public static String getName(UUID uuid) { - if (uuidExists(uuid)) { - return loopSearch(uuid).value; - } - String name; - if ((name = getNameOnlinePlayer(uuid)) != null) { - return name; - } - if ((name = getNameOfflinePlayer(uuid)) != null) { - return name; - } - if (online) { - if(!Settings.CUSTOM_API) { + /** + * @param uuid + * to use as key + * @return Name + */ + public static String getName(final UUID uuid) { + if (uuidExists(uuid)) { + return loopSearch(uuid).value; + } + String name; + if ((name = getNameOnlinePlayer(uuid)) != null) { + return name; + } + if ((name = getNameOfflinePlayer(uuid)) != null) { + return name; + } + if (online) { + if (!Settings.CUSTOM_API) { try { - NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); + final NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); name = fetcher.call().get(uuid); add(new StringWrapper(name), uuid); return name; - } catch (Exception ex) { + } + catch (final Exception ex) { ex.printStackTrace(); } - } else { + } + else { try { return PlotMain.getUUIDSaver().mojangName(uuid); - } catch(Exception e) { + } + catch (final Exception e) { try { - NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); + final NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); name = fetcher.call().get(uuid); add(new StringWrapper(name), uuid); return name; - } catch (Exception ex) { + } + catch (final Exception ex) { e.printStackTrace(); } } } try { return PlotMain.getUUIDSaver().mojangName(uuid); - } catch(Exception e) { + } + catch (final Exception e) { try { - NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); + final NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); name = fetcher.call().get(uuid); add(new StringWrapper(name), uuid); return name; - } catch (Exception ex) { + } + catch (final Exception ex) { ex.printStackTrace(); } } - } - else { - return "unknown"; - } + } + else { + return "unknown"; + } return ""; - } + } - /** - * @param name to use as key - * @return UUID (name hash) - */ - private static UUID getUuidOfflineMode(StringWrapper name) { - UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); - add(name, uuid); - return uuid; - } + /** + * @param name + * to use as key + * @return UUID (name hash) + */ + private static UUID getUuidOfflineMode(final StringWrapper name) { + final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); + add(name, uuid); + return uuid; + } - /** - * @param uuid to use as key - * @return String - name - */ - private static String getNameOnlinePlayer(UUID uuid) { - Player player = Bukkit.getPlayer(uuid); - if (player == null || !player.isOnline()) { - return null; - } - String name = player.getName(); - add(new StringWrapper(name), uuid); - return name; - } + /** + * @param uuid + * to use as key + * @return String - name + */ + private static String getNameOnlinePlayer(final UUID uuid) { + final Player player = Bukkit.getPlayer(uuid); + if ((player == null) || !player.isOnline()) { + return null; + } + final String name = player.getName(); + add(new StringWrapper(name), uuid); + return name; + } - /** - * @param uuid to use as key - * @return String - name - */ - private static String getNameOfflinePlayer(UUID uuid) { - OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); - if (player == null || !player.hasPlayedBefore()) { - return null; - } - String name = player.getName(); - add(new StringWrapper(name), uuid); - return name; - } + /** + * @param uuid + * to use as key + * @return String - name + */ + private static String getNameOfflinePlayer(final UUID uuid) { + final OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); + if ((player == null) || !player.hasPlayedBefore()) { + return null; + } + final String name = player.getName(); + add(new StringWrapper(name), uuid); + return name; + } - /** - * @param name to use as key - * @return UUID - */ - private static UUID getUuidOnlinePlayer(StringWrapper name) { + /** + * @param name + * to use as key + * @return UUID + */ + private static UUID getUuidOnlinePlayer(final StringWrapper name) { @SuppressWarnings("deprecation") - Player player = Bukkit.getPlayer(name.value); - if (player == null) { - return null; - } - UUID uuid = player.getUniqueId(); - add(name, uuid); - return uuid; - } - - /** - * @param name to use as key - * @return UUID (username hash) - */ - @SuppressWarnings("unused") - private static UUID getUuidOfflinePlayer(StringWrapper name) { - UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.value).getBytes(Charsets.UTF_8)); - add(name, uuid); - return uuid; - } - + final Player player = Bukkit.getPlayer(name.value); + if (player == null) { + return null; + } + final UUID uuid = player.getUniqueId(); + add(name, uuid); + return uuid; + } /** * Handle saving of uuids + * * @see com.intellectualcrafters.plot.uuid.UUIDSaver#globalSave(com.google.common.collect.BiMap) */ @SuppressWarnings("unused") public static void handleSaving() { - UUIDSaver saver = PlotMain.getUUIDSaver(); + final UUIDSaver saver = PlotMain.getUUIDSaver(); // Should it save per UUIDSet or all of them? TODO: Let Jesse decide xD saver.globalSave(getUuidMap()); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java index 145668c79..87597f48b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java @@ -2,15 +2,15 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlotAPI.java >> Generated by: Citymonstret at 2014-08-09 01:44 */ package com.intellectualcrafters.plot.api; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.SubCommand; +import java.util.ArrayList; +import java.util.Set; + import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; @@ -18,8 +18,19 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; -import java.util.ArrayList; -import java.util.Set; +import com.intellectualcrafters.plot.AbstractFlag; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.FlagManager; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotManager; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.SchematicHandler; +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.commands.SubCommand; /** * The plotMain api class. @@ -29,39 +40,40 @@ import java.util.Set; @SuppressWarnings({ "unused", "javadoc" }) public class PlotAPI { - private static PlotHelper plotHelper; - private static PlayerFunctions playerFunctions; - private static FlagManager flagManager; - private static SchematicHandler schematicHandler; - private static C c; + private static PlotHelper plotHelper; + private static PlayerFunctions playerFunctions; + private static FlagManager flagManager; + private static SchematicHandler schematicHandler; + private static C c; - // Methods/fields in PlotMain class + // Methods/fields in PlotMain class - // PlotMain.checkForExpiredPlots(); #Ignore - // PlotMain.killAllEntities(); #Ignore - // - // PlotMain.createConfiguration(plotworld); - // PlotMain.getPlots(player) - // PlotMain.getPlots(world) - // PlotMain.getPlots(world, player) - // PlotMain.getWorldPlots(world) - // PlotMain.getPlotWorlds() - // PlotMain.isPlotWorld(world) - // PlotMain.removePlot(world, id, callEvent) - // PlotMain.teleportPlayer(player, from, plot) - // PlotMain.updatePlot(plot); + // PlotMain.checkForExpiredPlots(); #Ignore + // PlotMain.killAllEntities(); #Ignore + // + // PlotMain.createConfiguration(plotworld); + // PlotMain.getPlots(player) + // PlotMain.getPlots(world) + // PlotMain.getPlots(world, player) + // PlotMain.getWorldPlots(world) + // PlotMain.getPlotWorlds() + // PlotMain.isPlotWorld(world) + // PlotMain.removePlot(world, id, callEvent) + // PlotMain.teleportPlayer(player, from, plot) + // PlotMain.updatePlot(plot); - // To access plotMain stuff. - private PlotMain plotMain; + // To access plotMain stuff. + private final PlotMain plotMain; - // Reference + // Reference /** * Admin Permission */ - public static final String ADMIN_PERMISSION = "plots.admin"; + public static final String ADMIN_PERMISSION = "plots.admin"; /** * Get all plots + * * @return all plots */ public Set getAllPlots() { @@ -70,21 +82,28 @@ public class PlotAPI { /** * Return all plots for a player + * * @param player * @return all plots that a player owns */ - public Set getPlayerPlots(Player player) { + public Set getPlayerPlots(final Player player) { return PlotMain.getPlots(player); } /** * Add a plotoworld - * @see com.intellectualcrafters.plot.PlotMain#addPlotWorld(String, com.intellectualcrafters.plot.PlotWorld, com.intellectualcrafters.plot.PlotManager) - * @param world World Name - * @param plotWorld Plot World Object - * @param manager World Manager + * + * @see com.intellectualcrafters.plot.PlotMain#addPlotWorld(String, + * com.intellectualcrafters.plot.PlotWorld, + * com.intellectualcrafters.plot.PlotManager) + * @param world + * World Name + * @param plotWorld + * Plot World Object + * @param manager + * World Manager */ - public void addPlotWorld(String world, PlotWorld plotWorld, PlotManager manager) { + public void addPlotWorld(final String world, final PlotWorld plotWorld, final PlotManager manager) { PlotMain.addPlotWorld(world, plotWorld, manager); } @@ -112,375 +131,376 @@ public class PlotAPI { return PlotMain.storage; } - /** - * Constructor. Insert any Plugin. - * (Optimally the plugin that is accessing the method) - * @param plugin Plugin used to access this method - */ - public PlotAPI(JavaPlugin plugin) { - this.plotMain = JavaPlugin.getPlugin(PlotMain.class); - } + /** + * Constructor. Insert any Plugin. + * (Optimally the plugin that is accessing the method) + * + * @param plugin + * Plugin used to access this method + */ + public PlotAPI(final JavaPlugin plugin) { + this.plotMain = JavaPlugin.getPlugin(PlotMain.class); + } - /** - * Get the main class for this plugin
    - * - Contains a lot of fields and methods - not very well organized - *
    - * Only use this if you really need it - * @return PlotMain PlotSquared Main Class - */ - public PlotMain getMain() { - return plotMain; - } + /** + * Get the main class for this plugin
    + * - Contains a lot of fields and methods - not very well organized
    + * Only use this if you really need it + * + * @return PlotMain PlotSquared Main Class + */ + public PlotMain getMain() { + return this.plotMain; + } - /** - * PlotHelper class contains useful methods relating to plots. - * - * @return PlotHelper - */ - public PlotHelper getPlotHelper() { - return plotHelper; - } + /** + * PlotHelper class contains useful methods relating to plots. + * + * @return PlotHelper + */ + public PlotHelper getPlotHelper() { + return plotHelper; + } - /** - * PlayerFunctions class contains useful methods relating to players - Some - * player/plot methods are here as well - * - * @return PlayerFunctions - */ - public PlayerFunctions getPlayerFunctions() { - return playerFunctions; - } + /** + * PlayerFunctions class contains useful methods relating to players - Some + * player/plot methods are here as well + * + * @return PlayerFunctions + */ + public PlayerFunctions getPlayerFunctions() { + return playerFunctions; + } - /** - * FlagManager class contains methods relating to plot flags - * - * @return FlagManager - */ - public FlagManager getFlagManager() { - return flagManager; - } + /** + * FlagManager class contains methods relating to plot flags + * + * @return FlagManager + */ + public FlagManager getFlagManager() { + return flagManager; + } - /** - * SchematicHandler class contains methods related to pasting schematics - * - * @return SchematicHandler - */ - public SchematicHandler getSchematicHandler() { - return schematicHandler; - } + /** + * SchematicHandler class contains methods related to pasting schematics + * + * @return SchematicHandler + */ + public SchematicHandler getSchematicHandler() { + return schematicHandler; + } - /** - * C class contains all the captions from the translations.yml file. - * - * @return C - */ - public C getCaptions() { - return c; - } + /** + * C class contains all the captions from the translations.yml file. + * + * @return C + */ + public C getCaptions() { + return c; + } - /** - * Get the plot manager for a world. - Most of these methods can be accessed - * through the PlotHelper - * - * @param world - * @return PlotManager - */ - public PlotManager getPlotManager(World world) { - return PlotMain.getPlotManager(world); - } + /** + * Get the plot manager for a world. - Most of these methods can be accessed + * through the PlotHelper + * + * @param world + * @return PlotManager + */ + public PlotManager getPlotManager(final World world) { + return PlotMain.getPlotManager(world); + } - /** - * Get the plot manager for a world. - Contains useful low level methods for - * plot merging, clearing, and tessellation - * - * @param world - * @return PlotManager - */ - public PlotManager getPlotManager(String world) { - return PlotMain.getPlotManager(world); - } + /** + * Get the plot manager for a world. - Contains useful low level methods for + * plot merging, clearing, and tessellation + * + * @param world + * @return PlotManager + */ + public PlotManager getPlotManager(final String world) { + return PlotMain.getPlotManager(world); + } - /** - * Get the settings for a world (settings bundled in PlotWorld class) - You - * will need to downcast for the specific settings a Generator has. e.g. - * DefaultPlotWorld class implements PlotWorld - * - * @param world - * (to get settings of) - * @return PlotWorld class for that world ! will return null if not a plot - * world world - */ - public PlotWorld getWorldSettings(World world) { - return PlotMain.getWorldSettings(world); - } + /** + * Get the settings for a world (settings bundled in PlotWorld class) - You + * will need to downcast for the specific settings a Generator has. e.g. + * DefaultPlotWorld class implements PlotWorld + * + * @param world + * (to get settings of) + * @return PlotWorld class for that world ! will return null if not a plot + * world world + */ + public PlotWorld getWorldSettings(final World world) { + return PlotMain.getWorldSettings(world); + } - /** - * Get the settings for a world (settings bundled in PlotWorld class) - * - * @param world - * (to get settings of) - * @return PlotWorld class for that world ! will return null if not a plot - * world world - */ - public PlotWorld getWorldSettings(String world) { - return PlotMain.getWorldSettings(world); - } + /** + * Get the settings for a world (settings bundled in PlotWorld class) + * + * @param world + * (to get settings of) + * @return PlotWorld class for that world ! will return null if not a plot + * world world + */ + public PlotWorld getWorldSettings(final String world) { + return PlotMain.getWorldSettings(world); + } - /** - * Send a message to a player. - * - * @param player - * @param c - * (Caption) - */ - public void sendMessage(Player player, C c) { - PlayerFunctions.sendMessage(player, c); - } + /** + * Send a message to a player. + * + * @param player + * @param c + * (Caption) + */ + public void sendMessage(final Player player, final C c) { + PlayerFunctions.sendMessage(player, c); + } - /** - * Send a message to a player. - Supports color codes - * - * @param player - * @param string - */ - public void sendMessage(Player player, String string) { - PlayerFunctions.sendMessage(player, string); - } + /** + * Send a message to a player. - Supports color codes + * + * @param player + * @param string + */ + public void sendMessage(final Player player, final String string) { + PlayerFunctions.sendMessage(player, string); + } - /** - * Send a message to the console. - Supports color codes - * - * @param msg - */ - public void sendConsoleMessage(String msg) { - PlotMain.sendConsoleSenderMessage(msg); - } + /** + * Send a message to the console. - Supports color codes + * + * @param msg + */ + public void sendConsoleMessage(final String msg) { + PlotMain.sendConsoleSenderMessage(msg); + } - /** - * Send a message to the console - * - * @param c - * (Caption) - */ - public void sendConsoleMessage(C c) { - sendConsoleMessage(c.s()); - } + /** + * Send a message to the console + * + * @param c + * (Caption) + */ + public void sendConsoleMessage(final C c) { + sendConsoleMessage(c.s()); + } - /** - * Register a flag for use in plots - * - * @param flag - */ - public void addFlag(AbstractFlag flag) { - FlagManager.addFlag(flag); - } + /** + * Register a flag for use in plots + * + * @param flag + */ + public void addFlag(final AbstractFlag flag) { + FlagManager.addFlag(flag); + } - /** - * get all the currently registered flags - * - * @return array of Flag[] - */ - public AbstractFlag[] getFlags() { - return FlagManager.getFlags().toArray(new AbstractFlag[0]); - } + /** + * get all the currently registered flags + * + * @return array of Flag[] + */ + public AbstractFlag[] getFlags() { + return FlagManager.getFlags().toArray(new AbstractFlag[0]); + } - /** - * Get a plot based on the ID - * - * @param world - * @param x - * @param z - * @return plot, null if ID is wrong - */ - public Plot getPlot(World world, int x, int z) { - return PlotHelper.getPlot(world, new PlotId(x, z)); - } + /** + * Get a plot based on the ID + * + * @param world + * @param x + * @param z + * @return plot, null if ID is wrong + */ + public Plot getPlot(final World world, final int x, final int z) { + return PlotHelper.getPlot(world, new PlotId(x, z)); + } - /** - * Get a plot based on the location - * - * @param l - * @return plot if found, otherwise it creates a temporary plot- - */ - public Plot getPlot(Location l) { - return PlotHelper.getCurrentPlot(l); - } + /** + * Get a plot based on the location + * + * @param l + * @return plot if found, otherwise it creates a temporary plot- + */ + public Plot getPlot(final Location l) { + return PlotHelper.getCurrentPlot(l); + } - /** - * Get a plot based on the player location - * - * @param player - * @return plot if found, otherwise it creates a temporary plot - */ - public Plot getPlot(Player player) { - return this.getPlot(player.getLocation()); - } + /** + * Get a plot based on the player location + * + * @param player + * @return plot if found, otherwise it creates a temporary plot + */ + public Plot getPlot(final Player player) { + return this.getPlot(player.getLocation()); + } - /** - * Check whether or not a player has a plot - * - * @param player - * @return true if player has a plot, false if not. - */ - public boolean hasPlot(World world, Player player) { - return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); - } + /** + * Check whether or not a player has a plot + * + * @param player + * @return true if player has a plot, false if not. + */ + public boolean hasPlot(final World world, final Player player) { + return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); + } - /** - * Get all plots for the player - * - * @param plr - * to search for - * @param just_owner - * should we just search for owner? Or with rights? - */ - public Plot[] getPlots(World world, Player plr, boolean just_owner) { - ArrayList pPlots = new ArrayList<>(); - for (Plot plot : PlotMain.getPlots(world).values()) { - if (just_owner) { - if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) { - pPlots.add(plot); - } - } - else { - if (plot.hasRights(plr)) { - pPlots.add(plot); - } - } - } - return (Plot[]) pPlots.toArray(); - } + /** + * Get all plots for the player + * + * @param plr + * to search for + * @param just_owner + * should we just search for owner? Or with rights? + */ + public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) { + final ArrayList pPlots = new ArrayList<>(); + for (final Plot plot : PlotMain.getPlots(world).values()) { + if (just_owner) { + if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) { + pPlots.add(plot); + } + } + else { + if (plot.hasRights(plr)) { + pPlots.add(plot); + } + } + } + return (Plot[]) pPlots.toArray(); + } - /** - * Get all plots for the world - * - * @param world - * to get plots of - * @return Plot[] - array of plot objects in world - */ - public Plot[] getPlots(World world) { - return PlotMain.getWorldPlots(world); - } + /** + * Get all plots for the world + * + * @param world + * to get plots of + * @return Plot[] - array of plot objects in world + */ + public Plot[] getPlots(final World world) { + return PlotMain.getWorldPlots(world); + } - /** - * Get all plot worlds - * - * @return World[] - array of plot worlds - */ - public String[] getPlotWorlds() { - return PlotMain.getPlotWorlds(); - } + /** + * Get all plot worlds + * + * @return World[] - array of plot worlds + */ + public String[] getPlotWorlds() { + return PlotMain.getPlotWorlds(); + } - /** - * Get if plot world - * - * @param world - * (to check if plot world) - * @return boolean (if plot world or not) - */ - public boolean isPlotWorld(World world) { - return PlotMain.isPlotWorld(world); - } + /** + * Get if plot world + * + * @param world + * (to check if plot world) + * @return boolean (if plot world or not) + */ + public boolean isPlotWorld(final World world) { + return PlotMain.isPlotWorld(world); + } - /** - * Get plot locations - * - * @param p - * @return [0] = bottomLc, [1] = topLoc, [2] = home - */ - public Location[] getLocations(Plot p) { - World world = Bukkit.getWorld(p.world); - return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), - PlotHelper.getPlotHome(world, p.id) }; - } + /** + * Get plot locations + * + * @param p + * @return [0] = bottomLc, [1] = topLoc, [2] = home + */ + public Location[] getLocations(final Plot p) { + final World world = Bukkit.getWorld(p.world); + return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), PlotHelper.getPlotHome(world, p.id) }; + } - /** - * Get home location - * - * @param p - * @return plot bottom location - */ - public Location getHomeLocation(Plot p) { - return PlotHelper.getPlotHome(p.getWorld(), p.id); - } + /** + * Get home location + * + * @param p + * @return plot bottom location + */ + public Location getHomeLocation(final Plot p) { + return PlotHelper.getPlotHome(p.getWorld(), p.id); + } - /** - * Get Bottom Location - * - * @param p - * @return plot bottom location - */ - public Location getBottomLocation(Plot p) { - World world = Bukkit.getWorld(p.world); - return PlotHelper.getPlotBottomLoc(world, p.id); - } + /** + * Get Bottom Location + * + * @param p + * @return plot bottom location + */ + public Location getBottomLocation(final Plot p) { + final World world = Bukkit.getWorld(p.world); + return PlotHelper.getPlotBottomLoc(world, p.id); + } - /** - * Get Top Location - * - * @param p - * @return plot top location - */ - public Location getTopLocation(Plot p) { - World world = Bukkit.getWorld(p.world); - return PlotHelper.getPlotTopLoc(world, p.id); - } + /** + * Get Top Location + * + * @param p + * @return plot top location + */ + public Location getTopLocation(final Plot p) { + final World world = Bukkit.getWorld(p.world); + return PlotHelper.getPlotTopLoc(world, p.id); + } - /** - * Check whether or not a player is in a plot - * - * @param player - * @return true if the player is in a plot, false if not- - */ - public boolean isInPlot(Player player) { - return PlayerFunctions.isInPlot(player); - } + /** + * Check whether or not a player is in a plot + * + * @param player + * @return true if the player is in a plot, false if not- + */ + public boolean isInPlot(final Player player) { + return PlayerFunctions.isInPlot(player); + } - /** - * Register a subcommand - * - * @param c - */ - public void registerCommand(SubCommand c) { - MainCommand.subCommands.add(c); - } + /** + * Register a subcommand + * + * @param c + */ + public void registerCommand(final SubCommand c) { + MainCommand.subCommands.add(c); + } - /** - * Get the plotMain class - * - * @return PlotMain Class - */ - public PlotMain getPlotMain() { - return this.plotMain; - } + /** + * Get the plotMain class + * + * @return PlotMain Class + */ + public PlotMain getPlotMain() { + return this.plotMain; + } - /** - * Get the player plot count - * - * @param player - * @return - */ - public int getPlayerPlotCount(World world, Player player) { - return PlayerFunctions.getPlayerPlotCount(world, player); - } + /** + * Get the player plot count + * + * @param player + * @return + */ + public int getPlayerPlotCount(final World world, final Player player) { + return PlayerFunctions.getPlayerPlotCount(world, player); + } - /** - * Get a players plots - * - * @param player - * @return a set containing the players plots - */ - public Set getPlayerPlots(World world, Player player) { - return PlayerFunctions.getPlayerPlots(world, player); - } + /** + * Get a players plots + * + * @param player + * @return a set containing the players plots + */ + public Set getPlayerPlots(final World world, final Player player) { + return PlayerFunctions.getPlayerPlots(world, player); + } - /** - * Get the allowed plot count for a player - * - * @param player - * @return the number of allowed plots - */ - public int getAllowedPlots(Player player) { - return PlayerFunctions.getAllowedPlots(player); - } + /** + * Get the allowed plot count for a player + * + * @param player + * @return the number of allowed plots + */ + public int getAllowedPlots(final Player player) { + return PlayerFunctions.getAllowedPlots(player); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java index ce4bac0b1..246312b1e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Auto.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Auto.java >> Generated by: Citymonstret at 2014-08-09 01:40 */ package com.intellectualcrafters.plot.commands; @@ -24,126 +24,126 @@ import com.intellectualcrafters.plot.PlotWorld; @SuppressWarnings("deprecation") public class Auto extends SubCommand { - public Auto() { - super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING, true); - } + public Auto() { + super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING, true); + } - public static PlotId lastPlot = new PlotId(0,0); - - // TODO auto claim a mega plot with schematic - @Override - public boolean execute(Player plr, String... args) { - World world; - int size_x = 1; - int size_z = 1; - String schematic = ""; - if (PlotMain.getPlotWorlds().length == 1) { - world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]); - } - else { - if (PlotMain.isPlotWorld(plr.getWorld())) { - world = plr.getWorld(); - } - else { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return false; - } - } - if (args.length > 0) { - if (PlotMain.hasPermission(plr, "plots.auto.mega")) { - try { - String[] split = args[0].split(","); - size_x = Integer.parseInt(split[0]); - size_z = Integer.parseInt(split[1]); - if ((size_x < 1) || (size_z < 1)) { - PlayerFunctions.sendMessage(plr, "&cError: size<=0"); - } - if ((size_x > 4) || (size_z > 4)) { - PlayerFunctions.sendMessage(plr, "&cError: size>4"); - } - if (args.length > 1) { - schematic = args[1]; - } - } - catch (Exception e) { - schematic = args[0]; - // PlayerFunctions.sendMessage(plr, - // "&cError: Invalid size (X,Y)"); - // return false; - } - } - else { - schematic = args[0]; - // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - // return false; - } - } - if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) { - PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); - return false; - } - PlotWorld pWorld = PlotMain.getWorldSettings(world); - if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { - double cost = pWorld.PLOT_PRICE; - cost = (size_x * size_z) * cost; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); - return true; - } - economy.withdrawPlayer(plr, cost); - sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } - if (!schematic.equals("")) { - if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { - if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); - return true; - } - if (!PlotMain.hasPermission(plr,"plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); - return true; - } - } - } - boolean br = false; - if ((size_x == 1) && (size_z == 1)) { - while (!br) { - Plot plot = PlotHelper.getPlot(world, Auto.lastPlot); - if (plot==null || plot.owner == null) { + public static PlotId lastPlot = new PlotId(0, 0); + + // TODO auto claim a mega plot with schematic + @Override + public boolean execute(final Player plr, final String... args) { + World world; + int size_x = 1; + int size_z = 1; + String schematic = ""; + if (PlotMain.getPlotWorlds().length == 1) { + world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]); + } + else { + if (PlotMain.isPlotWorld(plr.getWorld())) { + world = plr.getWorld(); + } + else { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return false; + } + } + if (args.length > 0) { + if (PlotMain.hasPermission(plr, "plots.auto.mega")) { + try { + final String[] split = args[0].split(","); + size_x = Integer.parseInt(split[0]); + size_z = Integer.parseInt(split[1]); + if ((size_x < 1) || (size_z < 1)) { + PlayerFunctions.sendMessage(plr, "&cError: size<=0"); + } + if ((size_x > 4) || (size_z > 4)) { + PlayerFunctions.sendMessage(plr, "&cError: size>4"); + } + if (args.length > 1) { + schematic = args[1]; + } + } + catch (final Exception e) { + schematic = args[0]; + // PlayerFunctions.sendMessage(plr, + // "&cError: Invalid size (X,Y)"); + // return false; + } + } + else { + schematic = args[0]; + // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + // return false; + } + } + if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) { + PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); + return false; + } + final PlotWorld pWorld = PlotMain.getWorldSettings(world); + if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { + double cost = pWorld.PLOT_PRICE; + cost = (size_x * size_z) * cost; + if (cost > 0d) { + final Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); + return true; + } + economy.withdrawPlayer(plr, cost); + sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } + if (!schematic.equals("")) { + if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { + if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); + return true; + } + if (!PlotMain.hasPermission(plr, "plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); + return true; + } + } + } + boolean br = false; + if ((size_x == 1) && (size_z == 1)) { + while (!br) { + Plot plot = PlotHelper.getPlot(world, Auto.lastPlot); + if ((plot == null) || (plot.owner == null)) { plot = PlotHelper.getPlot(world, Auto.lastPlot); Claim.claimPlot(plr, plot, true); br = true; - PlotWorld pw = PlotMain.getWorldSettings(world); - Plot plot2 = PlotMain.getPlots(world).get(plot.id); - if (pw.DEFAULT_FLAGS != null && pw.DEFAULT_FLAGS.size() > 0) { + final PlotWorld pw = PlotMain.getWorldSettings(world); + final Plot plot2 = PlotMain.getPlots(world).get(plot.id); + if ((pw.DEFAULT_FLAGS != null) && (pw.DEFAULT_FLAGS.size() > 0)) { plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS)); } } Auto.lastPlot = getNextPlot(Auto.lastPlot, 1); - } - } - else { - boolean claimed = true; - while (!br) { - PlotId start = getNextPlot(Auto.lastPlot, 1); + } + } + else { + final boolean claimed = true; + while (!br) { + final PlotId start = getNextPlot(Auto.lastPlot, 1); - //FIXME: Wtf is going on here? - if (claimed) { - if (PlotMain.getPlots(world).get(start) == null || PlotMain.getPlots(world).get(start).owner == null) { - Auto.lastPlot = start; - continue; - } - } - - PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1); + // FIXME: Wtf is going on here? + if (claimed) { + if ((PlotMain.getPlots(world).get(start) == null) || (PlotMain.getPlots(world).get(start).owner == null)) { + Auto.lastPlot = start; + continue; + } + } + + final PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1); if (isUnowned(world, start, end)) { for (int i = start.x; i <= end.x; i++) { for (int j = start.y; j <= end.y; j++) { - Plot plot = PlotHelper.getPlot(world, new PlotId(i, j)); - boolean teleport = ((i == end.x) && (j == end.y)); + final Plot plot = PlotHelper.getPlot(world, new PlotId(i, j)); + final boolean teleport = ((i == end.x) && (j == end.y)); Claim.claimPlot(plr, plot, teleport); } } @@ -151,20 +151,20 @@ public class Auto extends SubCommand { return false; } br = true; - PlotWorld pw = PlotMain.getWorldSettings(world); - Plot plot2 = PlotMain.getPlots(world).get(start); - if (pw.DEFAULT_FLAGS != null && pw.DEFAULT_FLAGS.size() > 0) { + final PlotWorld pw = PlotMain.getWorldSettings(world); + final Plot plot2 = PlotMain.getPlots(world).get(start); + if ((pw.DEFAULT_FLAGS != null) && (pw.DEFAULT_FLAGS.size() > 0)) { plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS)); } } - } - } - return true; - } - - public static PlotId getNextPlot(PlotId id, int step) { - int absX = Math.abs(id.x); - int absY = Math.abs(id.y); + } + } + return true; + } + + public static PlotId getNextPlot(final PlotId id, final int step) { + final int absX = Math.abs(id.x); + final int absY = Math.abs(id.y); if (absX > absY) { if (id.x > 0) { return new PlotId(id.x, id.y + 1); @@ -173,7 +173,7 @@ public class Auto extends SubCommand { return new PlotId(id.x, id.y - 1); } } - else if (absY > absX ){ + else if (absY > absX) { if (id.y > 0) { return new PlotId(id.x - 1, id.y); } @@ -182,10 +182,10 @@ public class Auto extends SubCommand { } } else { - if (id.x.equals(id.y) && id.x > 0) { + if (id.x.equals(id.y) && (id.x > 0)) { return new PlotId(id.x, id.y + step); } - if (id.x==absX) { + if (id.x == absX) { return new PlotId(id.x, id.y + 1); } if (id.y == absY) { @@ -194,19 +194,18 @@ public class Auto extends SubCommand { return new PlotId(id.x + 1, id.y); } } - - public boolean isUnowned(World world, PlotId pos1, PlotId pos2) { - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - PlotId id = new PlotId(x, y); - if (PlotMain.getPlots(world).get(id) != null) { - if (PlotMain.getPlots(world).get(id).owner != null) { - return false; - } - } - } - } - return true; - } + public boolean isUnowned(final World world, final PlotId pos1, final PlotId pos2) { + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { + final PlotId id = new PlotId(x, y); + if (PlotMain.getPlots(world).get(id) != null) { + if (PlotMain.getPlots(world).get(id).owner != null) { + return false; + } + } + } + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java index c36bf9710..dd995c330 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Claim.java @@ -2,121 +2,130 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; -import com.intellectualcrafters.plot.generator.DefaultPlotWorld; import net.milkbowl.vault.economy.Economy; + import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.FlagManager; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.SchematicHandler; +import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; +import com.intellectualcrafters.plot.generator.DefaultPlotWorld; + /** * @author Citymonstret */ public class Claim extends SubCommand { - public Claim() { - super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING, true); - } + public Claim() { + super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING, true); + } - @Override - public boolean execute(Player plr, String... args) { - String schematic = ""; - if (args.length >= 1) { - schematic = args[0]; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) { - PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (plot.hasOwner()) { - PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); - return false; - } - PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); - if (PlotMain.useEconomy && world.USE_ECONOMY) { - double cost = world.PLOT_PRICE; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); - return true; - } - economy.withdrawPlayer(plr, cost); - sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } - if (!schematic.equals("")) { - if (world.SCHEMATIC_CLAIM_SPECIFY) { - if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); - return true; - } - if (!PlotMain.hasPermission(plr,"plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); - return true; - } - } - } - boolean result = claimPlot(plr, plot, false, schematic); - if (result) { - PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED); - return false; - } - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + String schematic = ""; + if (args.length >= 1) { + schematic = args[0]; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) { + PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (plot.hasOwner()) { + PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); + return false; + } + final PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); + if (PlotMain.useEconomy && world.USE_ECONOMY) { + final double cost = world.PLOT_PRICE; + if (cost > 0d) { + final Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); + return true; + } + economy.withdrawPlayer(plr, cost); + sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } + if (!schematic.equals("")) { + if (world.SCHEMATIC_CLAIM_SPECIFY) { + if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); + return true; + } + if (!PlotMain.hasPermission(plr, "plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); + return true; + } + } + } + final boolean result = claimPlot(plr, plot, false, schematic); + if (result) { + PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED); + return false; + } + return true; + } - public static boolean claimPlot(Player player, Plot plot, boolean teleport) { - return claimPlot(player, plot, teleport, ""); - } + public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) { + return claimPlot(player, plot, teleport, ""); + } - public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) { - PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - PlotHelper.createPlot(player, plot); - PlotHelper.setSign(player, plot); - PlayerFunctions.sendMessage(player, C.CLAIMED); - if (teleport) { - PlotMain.teleportPlayer(player, player.getLocation(), plot); - } - PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); - - Plot plot2 = PlotMain.getPlots(player.getWorld()).get(plot.id); - - if (world.SCHEMATIC_ON_CLAIM) { - SchematicHandler.Schematic sch; - if (schematic.equals("")) { - sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE); - } - else { - sch = SchematicHandler.getSchematic(schematic); - if (sch == null) { - sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE); - } - } - SchematicHandler.paste(player.getLocation(), sch, plot2, 0, 0); - } - if (world.DEFAULT_FLAGS != null && world.DEFAULT_FLAGS.size() > 0) { - plot2.settings.setFlags(FlagManager.parseFlags(world.DEFAULT_FLAGS)); - } + public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport, final String schematic) { + final PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + PlotHelper.createPlot(player, plot); + PlotHelper.setSign(player, plot); + PlayerFunctions.sendMessage(player, C.CLAIMED); + if (teleport) { + PlotMain.teleportPlayer(player, player.getLocation(), plot); + } + final PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); + + final Plot plot2 = PlotMain.getPlots(player.getWorld()).get(plot.id); + + if (world.SCHEMATIC_ON_CLAIM) { + SchematicHandler.Schematic sch; + if (schematic.equals("")) { + sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE); + } + else { + sch = SchematicHandler.getSchematic(schematic); + if (sch == null) { + sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE); + } + } + SchematicHandler.paste(player.getLocation(), sch, plot2, 0, 0); + } + if ((world.DEFAULT_FLAGS != null) && (world.DEFAULT_FLAGS.size() > 0)) { + plot2.settings.setFlags(FlagManager.parseFlags(world.DEFAULT_FLAGS)); + } if (world instanceof DefaultPlotWorld) { - DefaultPlotWorld pW = (DefaultPlotWorld) world; - if(pW.CLAIMED_WALL_BLOCK != pW.WALL_BLOCK) { + final DefaultPlotWorld pW = (DefaultPlotWorld) world; + if (pW.CLAIMED_WALL_BLOCK != pW.WALL_BLOCK) { PlotMain.getPlotManager(plot.getWorld()).setWall(plot.getWorld(), world, plot.getId(), pW.CLAIMED_WALL_BLOCK); } } - } - return event.isCancelled(); - } + } + return event.isCancelled(); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java index 9407dd994..585e961fb 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clear.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -20,30 +20,29 @@ import com.intellectualcrafters.plot.PlotMain; */ public class Clear extends SubCommand { - public Clear() { - super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, true); - - // TODO console clear plot at location - - } + public Clear() { + super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, true); - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { + // TODO console clear plot at location + + } + + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); return false; } - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) - && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - plot.clear(plr); - return true; - } + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + plot.clear(plr); + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clipboard.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clipboard.java index 1ff68a6c1..f731439f4 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clipboard.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Clipboard.java @@ -1,12 +1,14 @@ package com.intellectualcrafters.plot.commands; +import static com.intellectualcrafters.plot.PlotSelection.currentSelection; + +import org.bukkit.entity.Player; + import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotSelection; -import org.bukkit.entity.Player; -import static com.intellectualcrafters.plot.PlotSelection.currentSelection; /** * Created by Citymonstret on 2014-10-13. */ @@ -17,16 +19,16 @@ public class Clipboard extends SubCommand { } @Override - public boolean execute(Player plr, String... args) { - if(!currentSelection.containsKey(plr.getName())) { + public boolean execute(final Player plr, final String... args) { + if (!currentSelection.containsKey(plr.getName())) { sendMessage(plr, C.NO_CLIPBOARD); return true; } - PlotSelection selection = currentSelection.get(plr.getName()); + final PlotSelection selection = currentSelection.get(plr.getName()); - PlotId plotId = selection.getPlot().getId(); - int width = selection.getWidth(); - int total = selection.getBlocks().length; + final PlotId plotId = selection.getPlot().getId(); + final int width = selection.getWidth(); + final int total = selection.getBlocks().length; String message = C.CLIPBOARD_INFO.s(); diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java index 608aff23f..be21e5d5a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Command.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Command.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -15,15 +15,15 @@ package com.intellectualcrafters.plot.commands; */ public enum Command { - // TODO new commands - // (economy) - // - /plot buy - // - /plot sell - // (Rating system) (ratings can be stored as the average, and number of - // ratings) - // - /plot rate - // - /plot list + // TODO new commands + // (economy) + // - /plot buy + // - /plot sell + // (Rating system) (ratings can be stored as the average, and number of + // ratings) + // - /plot rate + // - /plot list SWAP("swap"), /** * @@ -40,152 +40,152 @@ public enum Command { /** * */ - TRUSTED("trusted", "trust"), - /** - * - */ + TRUSTED("trusted", "trust"), + /** + * + */ PASTE("paste"), CLIPBOARD("clipboard", "cboard"), - COPY("copy"), - /** - * - */ - KICK("kick", "k"), - /** - * - */ - HELPERS("helpers", "hp"), - /** - * - */ - DENIED("denied", "dn"), - /** - * - */ - CLAIM("claim", "c"), - /** - * - */ - MERGE("merge", "m"), - /** - * - */ - UNLINK("unlink", "u"), - /** - * - */ - CLEAR("clear", "clear", new CommandPermission("plots.clear")), - /** - * - */ - DELETE("delete", "d", new CommandPermission("plots.delete")), - /** - * - */ - DEBUG("debug", "database", new CommandPermission("plots.admin")), - /** - * - */ + COPY("copy"), + /** + * + */ + KICK("kick", "k"), + /** + * + */ + HELPERS("helpers", "hp"), + /** + * + */ + DENIED("denied", "dn"), + /** + * + */ + CLAIM("claim", "c"), + /** + * + */ + MERGE("merge", "m"), + /** + * + */ + UNLINK("unlink", "u"), + /** + * + */ + CLEAR("clear", "clear", new CommandPermission("plots.clear")), + /** + * + */ + DELETE("delete", "d", new CommandPermission("plots.delete")), + /** + * + */ + DEBUG("debug", "database", new CommandPermission("plots.admin")), + /** + * + */ INTERFACE("interface", "int", new CommandPermission("plots.interface")), /** * */ - HOME("home", "h"), - /** - * - */ - INFO("info", "i"), - /** - * - */ - LIST("list", "l"), - /** - * - */ - SET("set", "s"), - /** - * - */ - PURGE("purge"), - /** - * - */ - SETUP("setup"), - /** - * - */ - TP("tp", "tp"); - /** - * - */ - private String command; - /** - * - */ - private String alias; - /** - * - */ - private CommandPermission permission; + HOME("home", "h"), + /** + * + */ + INFO("info", "i"), + /** + * + */ + LIST("list", "l"), + /** + * + */ + SET("set", "s"), + /** + * + */ + PURGE("purge"), + /** + * + */ + SETUP("setup"), + /** + * + */ + TP("tp", "tp"); + /** + * + */ + private String command; + /** + * + */ + private String alias; + /** + * + */ + private CommandPermission permission; - /** - * @param command - */ - Command(String command) { - this.command = command; - this.alias = command; - this.permission = new CommandPermission("plots." + command); - } + /** + * @param command + */ + Command(final String command) { + this.command = command; + this.alias = command; + this.permission = new CommandPermission("plots." + command); + } - /** - * @param command - * @param permission - */ - Command(String command, CommandPermission permission) { - this.command = command; - this.permission = permission; - this.alias = command; - } + /** + * @param command + * @param permission + */ + Command(final String command, final CommandPermission permission) { + this.command = command; + this.permission = permission; + this.alias = command; + } - /** - * @param command - * @param alias - */ - Command(String command, String alias) { - this.command = command; - this.alias = alias; - this.permission = new CommandPermission("plots." + command); - } + /** + * @param command + * @param alias + */ + Command(final String command, final String alias) { + this.command = command; + this.alias = alias; + this.permission = new CommandPermission("plots." + command); + } - /** - * @param Command - * @param alias - * @param permission - */ - Command(String command, String alias, CommandPermission permission) { - this.command = command; - this.alias = alias; - this.permission = permission; - } + /** + * @param Command + * @param alias + * @param permission + */ + Command(final String command, final String alias, final CommandPermission permission) { + this.command = command; + this.alias = alias; + this.permission = permission; + } - /** - * @return - */ - public String getCommand() { - return this.command; - } + /** + * @return + */ + public String getCommand() { + return this.command; + } - /** - * @return - */ - public String getAlias() { - return this.alias; - } + /** + * @return + */ + public String getAlias() { + return this.alias; + } - /** - * @return - */ - public CommandPermission getPermission() { - return this.permission; - } + /** + * @return + */ + public CommandPermission getPermission() { + return this.permission; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java index f33105782..5680475b6 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = CommandPermission.java >> Generated by: Citymonstret at 2014-08-09 * 01:41 */ @@ -20,23 +20,23 @@ import com.intellectualcrafters.plot.PlotMain; */ public class CommandPermission { - /** - * - */ - public String permission; + /** + * + */ + public String permission; - /** - * @param permission - */ - public CommandPermission(String permission) { - this.permission = permission.toLowerCase(); - } + /** + * @param permission + */ + public CommandPermission(final String permission) { + this.permission = permission.toLowerCase(); + } - /** - * @param player - * @return - */ - public boolean hasPermission(Player player) { - return PlotMain.hasPermission(player, this.permission) || PlotMain.hasPermission(player, "plots.admin"); - } + /** + * @param player + * @return + */ + public boolean hasPermission(final Player player) { + return PlotMain.hasPermission(player, this.permission) || PlotMain.hasPermission(player, "plots.admin"); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Comment.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Comment.java index a0cb39b4c..dc45307d2 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Comment.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Comment.java @@ -2,62 +2,65 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; +import java.util.Arrays; +import java.util.List; import org.apache.commons.lang.StringUtils; import org.bukkit.entity.Player; -import java.util.Arrays; -import java.util.List; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotComment; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.database.DBFunc; /** * Created by Citymonstret on 2014-08-01. */ public class Comment extends SubCommand { - public Comment() { - super(Command.COMMENT, "Comment on a plot", "comment", CommandCategory.ACTIONS, true); - } + public Comment() { + super(Command.COMMENT, "Comment on a plot", "comment", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!plot.hasOwner()) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); return false; - } - - List recipients = Arrays.asList(new String[] {"admin", "owner", "helper", "trusted", "everyone" }); - - if (args.length==2 && recipients.contains(args[0].toLowerCase())) { - - if (PlotMain.hasPermission(plr, "plots.comment."+args[0].toLowerCase())) { - String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); - PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase())); - plot.settings.addComment(comment); - - DBFunc.setComment(plr.getWorld().getName(), plot, comment); - - - return true; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment."+args[0].toLowerCase()); - return false; - } - } - PlayerFunctions.sendMessage(plr, C.COMMENT_SYNTAX); + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!plot.hasOwner()) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + + final List recipients = Arrays.asList(new String[] { "admin", "owner", "helper", "trusted", "everyone" }); + + if ((args.length == 2) && recipients.contains(args[0].toLowerCase())) { + + if (PlotMain.hasPermission(plr, "plots.comment." + args[0].toLowerCase())) { + final String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); + final PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase())); + plot.settings.addComment(comment); + + DBFunc.setComment(plr.getWorld().getName(), plot, comment); + + return true; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment." + args[0].toLowerCase()); + return false; + } + } + PlayerFunctions.sendMessage(plr, C.COMMENT_SYNTAX); return false; - } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java index 6f9becc57..4eeeac1d1 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Copy.java @@ -2,50 +2,55 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; - import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotSelection; + /** * Created by Citymonstret on 2014-08-01. */ public class Copy extends SubCommand { - public Copy() { - super(Command.COPY, "Copy a plot", "copy", CommandCategory.ACTIONS, true); - } + public Copy() { + super(Command.COPY, "Copy a plot", "copy", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) - && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (plot.settings.isMerged()) { + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (plot.settings.isMerged()) { PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); return false; } assert plot != null; - int size = (PlotHelper.getPlotTopLocAbs(plr.getWorld(), plot.getId()).getBlockX() - PlotHelper.getPlotBottomLocAbs(plr.getWorld(), plot.getId()).getBlockX()); - PlotSelection selection = new PlotSelection(size, plr.getWorld(), plot); - if(PlotSelection.currentSelection.containsKey(plr.getName())) { + final int size = (PlotHelper.getPlotTopLocAbs(plr.getWorld(), plot.getId()).getBlockX() - PlotHelper.getPlotBottomLocAbs(plr.getWorld(), plot.getId()).getBlockX()); + final PlotSelection selection = new PlotSelection(size, plr.getWorld(), plot); + if (PlotSelection.currentSelection.containsKey(plr.getName())) { PlotSelection.currentSelection.remove(plr.getName()); } PlotSelection.currentSelection.put(plr.getName(), selection); sendMessage(plr, C.CLIPBOARD_SET); - //section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs, new PlotId(plot.getId().x + 1, plot.getId().y))); - return true; - } + // section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs, + // new PlotId(plot.getId().x + 1, plot.getId().y))); + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java index c9200c881..b23c19c7f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Debug.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Debug.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -31,91 +31,91 @@ import com.intellectualcrafters.plot.RUtils; */ public class Debug extends SubCommand { - // private extends SubCommand^Implements {Command, Information} from - // >>\\S.txt6\\ - public Debug() { - super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.DEBUG, false); - { - /** - * This. - */ - } - } + // private extends SubCommand^Implements {Command, Information} from + // >>\\S.txt6\\ + public Debug() { + super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.DEBUG, false); + { + /** + * This. + */ + } + } - @Override - public boolean execute(Player plr, String... args) { - if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { - StringBuilder msg = new StringBuilder(); - for (C c : C.values()) { - msg.append(c.s() + "\n"); - } - PlayerFunctions.sendMessage(plr, msg.toString()); - return true; - } - StringBuilder information; - String header, line, section; - /** - * {$notnull || compile:: \\Debug:Captions\\} - */ - { - information = new StringBuilder(); - header = C.DEUBG_HEADER.s(); - line = C.DEBUG_LINE.s(); - section = C.DEBUG_SECTION.s(); - } - /** - * {||direct:: load: debug::I>Captions::trsl} \\ if(missing) - * set(default) -> this->(){} \\ echo line->line(Compiler.cpp -> - * lineCompiler); when finished: now = this(); - * now(getter)->setter(this())->{ "string" = getter(this); - * setter(string) = getter(this->setter); } when ^ finished compile; - * if(^compile failed -> |this->failed.|tests->failed.| ||run test - * {this->test}|on fail(action(){return FAILED})| - */ - { - StringBuilder worlds = new StringBuilder(""); - for (String world : PlotMain.getPlotWorlds()) { - worlds.append(world + " "); - } - information.append(header); - information.append(getSection(section, "Lag / TPS")); - information.append(getLine(line, "Ticks Per Second", Lag.getTPS())); - information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%")); - information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); - information.append(getSection(section, "PlotWorld")); - information.append(getLine(line, "Plot Worlds", worlds)); - information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size())); - // information.append(getLine(line, "PlotWorld Size", - // PlotHelper.getWorldFolderSize() + "MB")); - for (String worldname : PlotMain.getPlotWorlds()) { - World world = Bukkit.getWorld(worldname); - information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world))); - information.append(getLine(line, " - Entities", PlotHelper.getEntities(world))); - information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world))); - information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world))); - } - information.append(getSection(section, "RAM")); - information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB")); - information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB")); - information.append(getSection(section, "Messages")); - information.append(getLine(line, "Total Messages", C.values().length)); - information.append(getLine(line, "View all captions", "/plot debug msg")); - } - /** - * {function:: SEND_MESSAGE |local player -> plr|local string -> - * information.toString())} - */ - { - PlayerFunctions.sendMessage(plr, information.toString()); - } - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { + final StringBuilder msg = new StringBuilder(); + for (final C c : C.values()) { + msg.append(c.s() + "\n"); + } + PlayerFunctions.sendMessage(plr, msg.toString()); + return true; + } + StringBuilder information; + String header, line, section; + /** + * {$notnull || compile:: \\Debug:Captions\\} + */ + { + information = new StringBuilder(); + header = C.DEUBG_HEADER.s(); + line = C.DEBUG_LINE.s(); + section = C.DEBUG_SECTION.s(); + } + /** + * {||direct:: load: debug::I>Captions::trsl} \\ if(missing) + * set(default) -> this->(){} \\ echo line->line(Compiler.cpp -> + * lineCompiler); when finished: now = this(); + * now(getter)->setter(this())->{ "string" = getter(this); + * setter(string) = getter(this->setter); } when ^ finished compile; + * if(^compile failed -> |this->failed.|tests->failed.| ||run test + * {this->test}|on fail(action(){return FAILED})| + */ + { + final StringBuilder worlds = new StringBuilder(""); + for (final String world : PlotMain.getPlotWorlds()) { + worlds.append(world + " "); + } + information.append(header); + information.append(getSection(section, "Lag / TPS")); + information.append(getLine(line, "Ticks Per Second", Lag.getTPS())); + information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%")); + information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); + information.append(getSection(section, "PlotWorld")); + information.append(getLine(line, "Plot Worlds", worlds)); + information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size())); + // information.append(getLine(line, "PlotWorld Size", + // PlotHelper.getWorldFolderSize() + "MB")); + for (final String worldname : PlotMain.getPlotWorlds()) { + final World world = Bukkit.getWorld(worldname); + information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world))); + information.append(getLine(line, " - Entities", PlotHelper.getEntities(world))); + information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world))); + information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world))); + } + information.append(getSection(section, "RAM")); + information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB")); + information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB")); + information.append(getSection(section, "Messages")); + information.append(getLine(line, "Total Messages", C.values().length)); + information.append(getLine(line, "View all captions", "/plot debug msg")); + } + /** + * {function:: SEND_MESSAGE |local player -> plr|local string -> + * information.toString())} + */ + { + PlayerFunctions.sendMessage(plr, information.toString()); + } + return true; + } - private String getSection(String line, String val) { - return line.replaceAll("%val%", val) + "\n"; - } + private String getSection(final String line, final String val) { + return line.replaceAll("%val%", val) + "\n"; + } - private String getLine(String line, String var, Object val) { - return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; - } + private String getLine(final String line, final String var, final Object val) { + return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java index 62b0d75b8..707ab035e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -11,8 +11,6 @@ package com.intellectualcrafters.plot.commands; import java.util.ArrayList; import java.util.UUID; -import net.milkbowl.vault.economy.Economy; - import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; @@ -31,7 +29,6 @@ import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotManager; import com.intellectualcrafters.plot.PlotWorld; -import com.intellectualcrafters.plot.SchematicHandler; import com.intellectualcrafters.plot.StringWrapper; import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.database.DBFunc; @@ -42,141 +39,141 @@ import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; */ public class DebugClaimTest extends SubCommand { - public DebugClaimTest() { - super(Command.DEBUGCLAIMTEST, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. Execution time may vary", "claim", CommandCategory.DEBUG, false); - } + public DebugClaimTest() { + super(Command.DEBUGCLAIMTEST, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. Execution time may vary", "claim", CommandCategory.DEBUG, false); + } - @Override - public boolean execute(Player plr, String... args) { - if (plr==null) { - if (args.length<3) { - PlayerFunctions.sendMessage(plr, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); - return false; - } - World world = Bukkit.getWorld(args[0]); - if (world==null || !PlotMain.isPlotWorld(world)) { - PlayerFunctions.sendMessage(plr, "&cInvalid plot world!"); - return false; - } - - PlotId min, max; - - try { - String[] split1 = args[1].split(";"); - String[] split2 = args[2].split(";"); - - min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1])); - max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1])); - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X,Y are the plot coords\nThe conversion will only check the plots in the selected area."); - return false; - } - PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while..."); - PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); - - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - ArrayList plots = new ArrayList(); + @Override + public boolean execute(final Player plr, final String... args) { + if (plr == null) { + if (args.length < 3) { + PlayerFunctions.sendMessage(plr, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); + return false; + } + final World world = Bukkit.getWorld(args[0]); + if ((world == null) || !PlotMain.isPlotWorld(world)) { + PlayerFunctions.sendMessage(plr, "&cInvalid plot world!"); + return false; + } - for (PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) { - Plot plot = PlotHelper.getPlot(world, id); - boolean contains = PlotMain.getPlots(world).containsKey(plot.id); + PlotId min, max; + + try { + final String[] split1 = args[1].split(";"); + final String[] split2 = args[2].split(";"); + + min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1])); + max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1])); + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X,Y are the plot coords\nThe conversion will only check the plots in the selected area."); + return false; + } + PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while..."); + PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); + + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + + final ArrayList plots = new ArrayList(); + + for (final PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) { + final Plot plot = PlotHelper.getPlot(world, id); + final boolean contains = PlotMain.getPlots(world).containsKey(plot.id); if (contains) { - PlayerFunctions.sendMessage(plr, " - &cDB Already contains: "+plot.id); + PlayerFunctions.sendMessage(plr, " - &cDB Already contains: " + plot.id); continue; } - - Location loc = manager.getSignLoc(world, plotworld, plot); - - Chunk chunk = world.getChunkAt(loc); - + + final Location loc = manager.getSignLoc(world, plotworld, plot); + + final Chunk chunk = world.getChunkAt(loc); + if (!chunk.isLoaded()) { - boolean result = chunk.load(false); + final boolean result = chunk.load(false); if (!result) { continue; } } - - Block block = world.getBlockAt(loc); - if (block!=null) { + + final Block block = world.getBlockAt(loc); + if (block != null) { if (block.getState() instanceof Sign) { - Sign sign = (Sign) block.getState(); - if (sign!=null) { + final Sign sign = (Sign) block.getState(); + if (sign != null) { String line = sign.getLine(2); - if (line!=null && line.length() > 2) { + if ((line != null) && (line.length() > 2)) { line = line.substring(2); - - BiMap map = UUIDHandler.getUuidMap(); - + + final BiMap map = UUIDHandler.getUuidMap(); + UUID uuid = (map.get(new StringWrapper(line))); - - if (uuid==null) { - for (StringWrapper string : map.keySet()) { + + if (uuid == null) { + for (final StringWrapper string : map.keySet()) { if (string.value.toLowerCase().startsWith(line.toLowerCase())) { uuid = map.get(string); break; } } } - if (uuid==null) { + if (uuid == null) { uuid = UUIDHandler.getUUID(line); } - if (uuid!=null) { - PlayerFunctions.sendMessage(plr, " - &aFound plot: "+plot.id+" : "+line); + if (uuid != null) { + PlayerFunctions.sendMessage(plr, " - &aFound plot: " + plot.id + " : " + line); plot.owner = uuid; plot.hasChanged = true; plots.add(plot); } else { - PlayerFunctions.sendMessage(plr, " - &cInvalid playername: "+plot.id+" : "+line); + PlayerFunctions.sendMessage(plr, " - &cInvalid playername: " + plot.id + " : " + line); } } } } } - } - - if (plots.size()>0) { - PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '"+plots.size()+"' plots!"); - DBFunc.createPlots(plots); - DBFunc.createAllSettingsAndHelpers(plots); - - for (Plot plot : plots) { - PlotMain.updatePlot(plot); - } - - PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); - - } - else { - PlayerFunctions.sendMessage(plr, "No plots were found for the given search."); - } - - } - else { - PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); - } + } + + if (plots.size() > 0) { + PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!"); + DBFunc.createPlots(plots); + DBFunc.createAllSettingsAndHelpers(plots); + + for (final Plot plot : plots) { + PlotMain.updatePlot(plot); + } + + PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); + + } + else { + PlayerFunctions.sendMessage(plr, "No plots were found for the given search."); + } + + } + else { + PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); + } return true; - } + } - public static boolean claimPlot(Player player, Plot plot, boolean teleport) { - return claimPlot(player, plot, teleport, ""); - } + public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) { + return claimPlot(player, plot, teleport, ""); + } - public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) { - PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - PlotHelper.createPlot(player, plot); - PlotHelper.setSign(player, plot); - PlayerFunctions.sendMessage(player, C.CLAIMED); - if (teleport) { - PlotMain.teleportPlayer(player, player.getLocation(), plot); - } - plot.settings.setFlags(FlagManager.parseFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS)); - } - return event.isCancelled(); - } + public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport, final String schematic) { + final PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + PlotHelper.createPlot(player, plot); + PlotHelper.setSign(player, plot); + PlayerFunctions.sendMessage(player, C.CLAIMED); + if (teleport) { + PlotMain.teleportPlayer(player, player.getLocation(), plot); + } + plot.settings.setFlags(FlagManager.parseFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS)); + } + return event.isCancelled(); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java index 3dd2a0207..b6b69345b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java @@ -2,70 +2,46 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Set; -import java.util.UUID; -import net.milkbowl.vault.economy.Economy; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; import org.bukkit.entity.Player; -import com.google.common.collect.BiMap; -import com.intellectualcrafters.plot.C; -import com.intellectualcrafters.plot.FlagManager; import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotHelper; -import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotMain; -import com.intellectualcrafters.plot.PlotManager; -import com.intellectualcrafters.plot.PlotWorld; -import com.intellectualcrafters.plot.SchematicHandler; -import com.intellectualcrafters.plot.StringWrapper; -import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; -import com.worldcretornica.plotme.PlayerList; /** * @author Citymonstret */ public class DebugLoadTest extends SubCommand { - public DebugLoadTest() { - super(Command.DEBUGCLAIMTEST, "This debug command will force the reload of all plots in the DB", "claim", CommandCategory.DEBUG, false); - } + public DebugLoadTest() { + super(Command.DEBUGCLAIMTEST, "This debug command will force the reload of all plots in the DB", "claim", CommandCategory.DEBUG, false); + } - @Override - public boolean execute(Player plr, String... args) { - if (plr==null) { - try { - Field fPlots = PlotMain.class.getDeclaredField("plots"); - fPlots.setAccessible(true); - fPlots.set(null, DBFunc.getPlots()); - } - catch (Exception e) { - PlotMain.sendConsoleSenderMessage("&3===FAILED&3==="); - e.printStackTrace(); - PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE==="); - } - } - else { - PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); - } + @Override + public boolean execute(final Player plr, final String... args) { + if (plr == null) { + try { + final Field fPlots = PlotMain.class.getDeclaredField("plots"); + fPlots.setAccessible(true); + fPlots.set(null, DBFunc.getPlots()); + } + catch (final Exception e) { + PlotMain.sendConsoleSenderMessage("&3===FAILED&3==="); + e.printStackTrace(); + PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE==="); + } + } + else { + PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); + } return true; - } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java index d72364bd4..d4f1d230d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java @@ -2,62 +2,41 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; import java.util.ArrayList; -import java.util.Set; -import java.util.UUID; -import net.milkbowl.vault.economy.Economy; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; import org.bukkit.entity.Player; -import com.google.common.collect.BiMap; -import com.intellectualcrafters.plot.C; -import com.intellectualcrafters.plot.FlagManager; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotHelper; -import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotMain; -import com.intellectualcrafters.plot.PlotManager; -import com.intellectualcrafters.plot.PlotWorld; -import com.intellectualcrafters.plot.SchematicHandler; -import com.intellectualcrafters.plot.StringWrapper; -import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; /** * @author Citymonstret */ public class DebugSaveTest extends SubCommand { - public DebugSaveTest() { - super(Command.DEBUGCLAIMTEST, "This debug command will force the recreation of all plots in the DB", "claim", CommandCategory.DEBUG, false); - } + public DebugSaveTest() { + super(Command.DEBUGCLAIMTEST, "This debug command will force the recreation of all plots in the DB", "claim", CommandCategory.DEBUG, false); + } - @Override - public boolean execute(Player plr, String... args) { - if (plr==null) { - ArrayList plots = new ArrayList(); - plots.addAll(PlotMain.getPlots()); - DBFunc.createPlots(plots); - DBFunc.createAllSettingsAndHelpers(plots); - } - else { - PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); - } + @Override + public boolean execute(final Player plr, final String... args) { + if (plr == null) { + final ArrayList plots = new ArrayList(); + plots.addAll(PlotMain.getPlots()); + DBFunc.createPlots(plots); + DBFunc.createAllSettingsAndHelpers(plots); + } + else { + PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); + } return true; - } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java index 5822117a0..f47957ef7 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Delete.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Delete.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -15,7 +15,6 @@ import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.database.DBFunc; @@ -25,46 +24,45 @@ import com.intellectualcrafters.plot.database.DBFunc; */ public class Delete extends SubCommand { - public Delete() { - super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS, true); - } + public Delete() { + super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { - PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); - return false; - } - if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))) - && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); - if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { - double c = pWorld.SELL_PRICE; - if (c > 0d) { - Economy economy = PlotMain.economy; - economy.depositPlayer(plr, c); - sendMessage(plr, C.ADDED_BALANCE, c + ""); - } - } - boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true); - if (result) { - plot.clear(plr); - DBFunc.delete(plr.getWorld().getName(), plot); - if (Math.abs(plot.id.x)<=Math.abs(Auto.lastPlot.x) && Math.abs(plot.id.y)<=Math.abs(Auto.lastPlot.y)) { + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { + PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); + return false; + } + if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + final PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); + if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { + final double c = pWorld.SELL_PRICE; + if (c > 0d) { + final Economy economy = PlotMain.economy; + economy.depositPlayer(plr, c); + sendMessage(plr, C.ADDED_BALANCE, c + ""); + } + } + final boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true); + if (result) { + plot.clear(plr); + DBFunc.delete(plr.getWorld().getName(), plot); + if ((Math.abs(plot.id.x) <= Math.abs(Auto.lastPlot.x)) && (Math.abs(plot.id.y) <= Math.abs(Auto.lastPlot.y))) { Auto.lastPlot = plot.id; } - } - else { - PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); - } - return true; - } + } + else { + PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Denied.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Denied.java index 59a5527c1..97e0d849f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Denied.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Denied.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Denied.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -26,35 +26,35 @@ import com.intellectualcrafters.plot.events.PlayerPlotDeniedEvent; @SuppressWarnings("deprecated") public class Denied extends SubCommand { - public Denied() { - super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS, true); - } + public Denied() { + super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot.owner == null) || !plot.hasRights(plr)) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return true; - } - if (args[0].equalsIgnoreCase("add")) { - UUID uuid; - if (args[1].equalsIgnoreCase("*")) { - uuid = DBFunc.everyone; - - } - else { - uuid = UUIDHandler.getUUID(args[1]); - } - if (!plot.denied.contains(uuid)) { + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot.owner == null) || !plot.hasRights(plr)) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + UUID uuid; + if (args[1].equalsIgnoreCase("*")) { + uuid = DBFunc.everyone; + + } + else { + uuid = UUIDHandler.getUUID(args[1]); + } + if (!plot.denied.contains(uuid)) { if (plot.owner == uuid) { PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER); return false; @@ -69,59 +69,58 @@ public class Denied extends SubCommand { } plot.addDenied(uuid); DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true); + final PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true); Bukkit.getPluginManager().callEvent(event); } else { PlayerFunctions.sendMessage(plr, C.ALREADY_ADDED); return false; } - if (!uuid.equals(DBFunc.everyone) && (Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) { - Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid))); - if (pl!=null && pl.id.equals(plot.id)) { - PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED); - Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation()); - } - } - PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); + if (!uuid.equals(DBFunc.everyone) && (Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) { + final Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid))); + if ((pl != null) && pl.id.equals(plot.id)) { + PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED); + Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation()); + } + } + PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); return true; - } - else - if (args[0].equalsIgnoreCase("remove")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - if (!plot.denied.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); - return true; - } - plot.removeDenied(uuid); - DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); - return true; - } - /* - * if (!hasBeenOnServer(args[1])) { - * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - * return true; } UUID uuid = null; if - * (Bukkit.getPlayer(args[1])!=null) { uuid = - * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = - * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if - * (!plot.denied.contains(uuid)) { - * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return - * true; } if (uuid == null) { PlayerFunctions.sendMessage(plr, - * C.PLAYER_HAS_NOT_BEEN_ON); return true; } - */ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.removeDenied(uuid); - DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); - } - else { - PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); - return true; - } - return true; - } + } + else if (args[0].equalsIgnoreCase("remove")) { + if (args[1].equalsIgnoreCase("*")) { + final UUID uuid = DBFunc.everyone; + if (!plot.denied.contains(uuid)) { + PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); + return true; + } + plot.removeDenied(uuid); + DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { + * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); + * return true; } UUID uuid = null; if + * (Bukkit.getPlayer(args[1])!=null) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if + * (!plot.denied.contains(uuid)) { + * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return + * true; } if (uuid == null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } + */ + final UUID uuid = UUIDHandler.getUUID(args[1]); + plot.removeDenied(uuid); + DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); + final PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); + } + else { + PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); + return true; + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Help.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Help.java index 1ef66a699..5a48cb5c9 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Help.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Help.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Help.java >> Generated by: Citymonstret at 2014-08-11 17:32 */ @@ -14,12 +14,12 @@ import org.bukkit.entity.Player; * Created by Citymonstret on 2014-08-11. */ public class Help extends SubCommand { - public Help() { - super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO, false); - } + public Help() { + super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO, false); + } - @Override - public boolean execute(Player plr, String... args) { - return false; - } + @Override + public boolean execute(final Player plr, final String... args) { + return false; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Helpers.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Helpers.java index 707d7de2c..5573c4442 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Helpers.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Helpers.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Helpers.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -23,34 +23,34 @@ import com.intellectualcrafters.plot.events.PlayerPlotHelperEvent; @SuppressWarnings("deprecation") public class Helpers extends SubCommand { - public Helpers() { - super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS, true); - } + public Helpers() { + super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot.owner == null) || !plot.hasRights(plr)) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return true; - } - if (args[0].equalsIgnoreCase("add")) { - UUID uuid; - if (args[1].equalsIgnoreCase("*")) { - uuid = DBFunc.everyone; - } - else { - uuid = UUIDHandler.getUUID(args[1]); - } - if (!plot.helpers.contains(uuid)) { + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot.owner == null) || !plot.hasRights(plr)) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + UUID uuid; + if (args[1].equalsIgnoreCase("*")) { + uuid = DBFunc.everyone; + } + else { + uuid = UUIDHandler.getUUID(args[1]); + } + if (!plot.helpers.contains(uuid)) { if (plot.owner == uuid) { PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER); return false; @@ -65,7 +65,7 @@ public class Helpers extends SubCommand { } plot.addHelper(uuid); DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true); + final PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true); Bukkit.getPluginManager().callEvent(event); } else { @@ -74,44 +74,43 @@ public class Helpers extends SubCommand { } PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); return true; - } - else - if (args[0].equalsIgnoreCase("remove")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - if (!plot.helpers.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); - return true; - } - plot.removeHelper(uuid); - DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); - return true; - } - /* - * if (!hasBeenOnServer(args[1])) { - * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - * return true; } UUID uuid = null; if - * (Bukkit.getPlayer(args[1]) != null) { uuid = - * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = - * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == - * null) { PlayerFunctions.sendMessage(plr, - * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if - * (!plot.helpers.contains(uuid)) { - * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return - * true; } - */ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.removeHelper(uuid); - DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); - } - else { - PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); - return true; - } - return true; - } + } + else if (args[0].equalsIgnoreCase("remove")) { + if (args[1].equalsIgnoreCase("*")) { + final UUID uuid = DBFunc.everyone; + if (!plot.helpers.contains(uuid)) { + PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); + return true; + } + plot.removeHelper(uuid); + DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { + * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); + * return true; } UUID uuid = null; if + * (Bukkit.getPlayer(args[1]) != null) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if + * (!plot.helpers.contains(uuid)) { + * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return + * true; } + */ + final UUID uuid = UUIDHandler.getUUID(args[1]); + plot.removeHelper(uuid); + DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); + final PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); + } + else { + PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); + return true; + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java index fb6ec7bcc..4d89c3b5b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Home.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Home.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -20,60 +20,59 @@ import com.intellectualcrafters.plot.PlotMain; */ public class Home extends SubCommand { - public Home() { - super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT, true); - } + public Home() { + super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT, true); + } - private Plot isAlias(String a) { - for (Plot p : PlotMain.getPlots()) { - if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { - return p; - } - } - return null; - } + private Plot isAlias(final String a) { + for (final Plot p : PlotMain.getPlots()) { + if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { + return p; + } + } + return null; + } - @Override - public boolean execute(Player plr, String... args) { - Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); - if (plots.length == 1) { - PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]); - return true; - } - else - if (plots.length > 1) { - if (args.length < 1) { - args = new String[] { "1" }; - } - int id = 0; - try { - id = Integer.parseInt(args[0]); - } - catch (Exception e) { - Plot temp; - if ((temp = isAlias(args[0])) != null) { - if (temp.hasOwner()) { - if (temp.getOwner().equals(plr.getUniqueId())) { - PlotMain.teleportPlayer(plr, plr.getLocation(), temp); - return true; - } - } - PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT); - return false; - } - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return true; - } - if ((id > (plots.length)) || (id < 1)) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return false; - } - PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]); - return true; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PLOTS); - return true; - } - } + @Override + public boolean execute(final Player plr, String... args) { + final Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); + if (plots.length == 1) { + PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]); + return true; + } + else if (plots.length > 1) { + if (args.length < 1) { + args = new String[] { "1" }; + } + int id = 0; + try { + id = Integer.parseInt(args[0]); + } + catch (final Exception e) { + Plot temp; + if ((temp = isAlias(args[0])) != null) { + if (temp.hasOwner()) { + if (temp.getOwner().equals(plr.getUniqueId())) { + PlotMain.teleportPlayer(plr, plr.getLocation(), temp); + return true; + } + } + PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT); + return false; + } + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return true; + } + if ((id > (plots.length)) || (id < 1)) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return false; + } + PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]); + return true; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PLOTS); + return true; + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java index dd421a51a..acc3029e3 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -13,109 +13,112 @@ import java.util.Arrays; import java.util.List; import java.util.UUID; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; - -import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotComment; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.database.DBFunc; + /** * Created by Citymonstret on 2014-08-01. */ public class Inbox extends SubCommand { - public Inbox() { - super(Command.INBOX, "Review a the comments for a plot", "comment", CommandCategory.ACTIONS, true); - } + public Inbox() { + super(Command.INBOX, "Review a the comments for a plot", "comment", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(final Player plr, final String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return false; - } - final Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!plot.hasOwner()) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); return false; - } - - Integer tier = null; - UUID uuid = plr.getUniqueId(); - if (PlotMain.hasPermission(plr, "plots.admin")) { - tier = 0; - } - else if (plot.owner == uuid) { - tier = 1; - } - else if (plot.helpers.contains(uuid)) { + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!plot.hasOwner()) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + + Integer tier = null; + final UUID uuid = plr.getUniqueId(); + if (PlotMain.hasPermission(plr, "plots.admin")) { + tier = 0; + } + else if (plot.owner == uuid) { + tier = 1; + } + else if (plot.helpers.contains(uuid)) { tier = 2; } - else if (plot.trusted.contains(uuid)) { + else if (plot.trusted.contains(uuid)) { tier = 3; } - else { - tier = 4; - } - - if (args.length > 0) { - switch (args[0].toLowerCase()) { - case "admin": - if (tier<=0) { - tier = 0; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); - return false; - } - break; - case "owner": - if (tier<=1) { - tier = 1; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); - return false; - } - break; - case "helper": - if (tier<=2) { - tier = 2; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); - return false; - } - break; - case "trusted": - if (tier<=3) { - tier = 3; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); - return false; - } - break; - case "everyone": - if (tier<=4) { - tier = 4; - } - else { - PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); - return false; - } - break; - case "default": - PlayerFunctions.sendMessage(plr, C.INVALID_INBOX, Arrays.copyOfRange(new String[] {"admin", "owner", "helper", "trusted", "everyone" }, tier, 4)); - return false; - } - } - - final String world = plr.getWorld().getName(); - final int tier2 = tier; + else { + tier = 4; + } - Bukkit.getScheduler().runTaskAsynchronously(PlotMain.getMain(), new Runnable() { + if (args.length > 0) { + switch (args[0].toLowerCase()) { + case "admin": + if (tier <= 0) { + tier = 0; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); + return false; + } + break; + case "owner": + if (tier <= 1) { + tier = 1; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); + return false; + } + break; + case "helper": + if (tier <= 2) { + tier = 2; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); + return false; + } + break; + case "trusted": + if (tier <= 3) { + tier = 3; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); + return false; + } + break; + case "everyone": + if (tier <= 4) { + tier = 4; + } + else { + PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX); + return false; + } + break; + case "default": + PlayerFunctions.sendMessage(plr, C.INVALID_INBOX, Arrays.copyOfRange(new String[] { "admin", "owner", "helper", "trusted", "everyone" }, tier, 4)); + return false; + } + } + + final String world = plr.getWorld().getName(); + final int tier2 = tier; + + Bukkit.getScheduler().runTaskAsynchronously(PlotMain.getMain(), new Runnable() { @Override public void run() { ArrayList comments = plot.settings.getComments(tier2); @@ -123,49 +126,49 @@ public class Inbox extends SubCommand { comments = DBFunc.getCommenst(world, plot, tier2); plot.settings.setComments(comments); } - + if (args.length == 2) { - String[] split = args[1].toLowerCase().split(":"); + final String[] split = args[1].toLowerCase().split(":"); if (!split[0].equals("clear")) { PlayerFunctions.sendMessage(plr, "&c/plot inbox [tier] [clear][:#]"); return; } if (split.length > 1) { try { - int index = Integer.parseInt(split[1]); - PlotComment comment = comments.get(index-1); + final int index = Integer.parseInt(split[1]); + final PlotComment comment = comments.get(index - 1); DBFunc.removeComment(world, plot, comment); PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "1 comment"); return; } - catch (Exception e) { + catch (final Exception e) { PlayerFunctions.sendMessage(plr, "&cInvalid index:\n/plot inbox [tier] [clear][:#]"); return; } } - for (PlotComment comment : comments) { + for (final PlotComment comment : comments) { DBFunc.removeComment(world, plot, comment); } PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "all comments in that category"); return; } else { - final List recipients = Arrays.asList(new String[] {"A", "O", "H", "T", "E" }); + final List recipients = Arrays.asList(new String[] { "A", "O", "H", "T", "E" }); int count = 1; - StringBuilder message = new StringBuilder(); + final StringBuilder message = new StringBuilder(); String prefix = ""; - for (PlotComment comment : comments) { - message.append(prefix + "["+count+"]&6[&c" + recipients.get(tier2) + "&6] &7"+comment.senderName+"&f: "+comment.comment); + for (final PlotComment comment : comments) { + message.append(prefix + "[" + count + "]&6[&c" + recipients.get(tier2) + "&6] &7" + comment.senderName + "&f: " + comment.comment); prefix = "\n"; count++; } - if (comments.size()==0) { + if (comments.size() == 0) { message.append("&cNo messages."); } PlayerFunctions.sendMessage(plr, message.toString()); } } - }); - return true; - } + }); + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java index fb3189988..cc05810a4 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Info.java @@ -2,169 +2,111 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Info.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; +import java.util.ArrayList; +import java.util.UUID; import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.time.DateUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.UUID; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.UUIDHandler; +import com.intellectualcrafters.plot.database.DBFunc; /** * @author Citymonstret */ public class Info extends SubCommand { - public Info() { - super(Command.INFO, "Display plot info", "info", CommandCategory.INFO, false); - } + public Info() { + super(Command.INFO, "Display plot info", "info", CommandCategory.INFO, false); + } - @Override - public boolean execute(Player player, String... args) { - World world; - Plot plot; - if (player!=null) { - world = player.getWorld(); - if (!PlayerFunctions.isInPlot(player)) { - PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); - return false; - } - plot = PlayerFunctions.getCurrentPlot(player); - } - else { - if (args.length<2) { - PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE); - return false; - } - PlotWorld plotworld = PlotMain.getWorldSettings(args[0]); - if (plotworld==null) { - PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD); - return false; - } - try { - String[] split = args[1].split(";"); - PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); - plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id); - if (plot==null) { - PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID); - return false; - } - world = Bukkit.getWorld(args[0]); - if (args.length==3) { - args = new String[] {args[2]}; - } - else { - args = new String[0]; - } - } - catch (Exception e) { - PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE); - return false; - } - } - - boolean hasOwner = plot.hasOwner(); - boolean containsEveryone; - boolean trustedEveryone; - - // Wildcard player {added} - { - if (plot.helpers == null) { - containsEveryone = false; - } - else { - containsEveryone = plot.helpers.contains(DBFunc.everyone); - } - if (plot.trusted == null) { - trustedEveryone = false; - } - else { - trustedEveryone = plot.trusted.contains(DBFunc.everyone); - } - } - - // Unclaimed? - if (!hasOwner && !containsEveryone && !trustedEveryone) { - PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y)); - return true; - } - - String owner = "none"; - if (plot.owner != null) { - owner = Bukkit.getOfflinePlayer(plot.owner).getName(); - } - if (owner == null) { - owner = plot.owner.toString(); - } - String info = C.PLOT_INFO.s(); - - if (args.length==1) { - info = getCaption(args[0].toLowerCase()); - if (info==null) { - PlayerFunctions.sendMessage(player, "&6Categories&7: &ahelpers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating"); - return false; - } - } - - info = format(info, world, plot, player); - - PlayerFunctions.sendMessage(player, info); - return true; - } - - private String getCaption(String string) { - switch (string) { - case "helpers": - return C.PLOT_INFO_HELPERS.s(); - case "alias": - return C.PLOT_INFO_ALIAS.s(); - case "biome": - return C.PLOT_INFO_BIOME.s(); - case "denied": - return C.PLOT_INFO_DENIED.s(); - case "flags": - return C.PLOT_INFO_FLAGS.s(); - case "id": - return C.PLOT_INFO_ID.s(); - case "size": - return C.PLOT_INFO_SIZE.s(); - case "trusted": - return C.PLOT_INFO_TRUSTED.s(); - case "owner": - return C.PLOT_INFO_OWNER.s(); - case "rating": - return C.PLOT_INFO_RATING.s(); - default: - return null; + @Override + public boolean execute(final Player player, String... args) { + World world; + Plot plot; + if (player != null) { + world = player.getWorld(); + if (!PlayerFunctions.isInPlot(player)) { + PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); + return false; + } + plot = PlayerFunctions.getCurrentPlot(player); } - } - - private String format(String info, World world, Plot plot, Player player) { - - PlotId id = plot.id; - PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id; - int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size(); - String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none"; - String biome = getBiomeAt(plot).toString(); - String helpers = getPlayerList(plot.helpers); - String trusted = getPlayerList(plot.trusted); - String denied = getPlayerList(plot.denied); - String rating = String.format("%.1f", DBFunc.getRatings(plot)); - String flags = "&3"+ (StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), "&7, &3") : "none"); - boolean build = player==null ? true : plot.hasRights(player); - + else { + if (args.length < 2) { + PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE); + return false; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]); + if (plotworld == null) { + PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD); + return false; + } + try { + final String[] split = args[1].split(";"); + final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); + plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id); + if (plot == null) { + PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID); + return false; + } + world = Bukkit.getWorld(args[0]); + if (args.length == 3) { + args = new String[] { args[2] }; + } + else { + args = new String[0]; + } + } + catch (final Exception e) { + PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE); + return false; + } + } + + final boolean hasOwner = plot.hasOwner(); + boolean containsEveryone; + boolean trustedEveryone; + + // Wildcard player {added} + { + if (plot.helpers == null) { + containsEveryone = false; + } + else { + containsEveryone = plot.helpers.contains(DBFunc.everyone); + } + if (plot.trusted == null) { + trustedEveryone = false; + } + else { + trustedEveryone = plot.trusted.contains(DBFunc.everyone); + } + } + + // Unclaimed? + if (!hasOwner && !containsEveryone && !trustedEveryone) { + PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y)); + return true; + } + String owner = "none"; if (plot.owner != null) { owner = Bukkit.getOfflinePlayer(plot.owner).getName(); @@ -172,11 +114,75 @@ public class Info extends SubCommand { if (owner == null) { owner = plot.owner.toString(); } - + String info = C.PLOT_INFO.s(); + + if (args.length == 1) { + info = getCaption(args[0].toLowerCase()); + if (info == null) { + PlayerFunctions.sendMessage(player, "&6Categories&7: &ahelpers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating"); + return false; + } + } + + info = format(info, world, plot, player); + + PlayerFunctions.sendMessage(player, info); + return true; + } + + private String getCaption(final String string) { + switch (string) { + case "helpers": + return C.PLOT_INFO_HELPERS.s(); + case "alias": + return C.PLOT_INFO_ALIAS.s(); + case "biome": + return C.PLOT_INFO_BIOME.s(); + case "denied": + return C.PLOT_INFO_DENIED.s(); + case "flags": + return C.PLOT_INFO_FLAGS.s(); + case "id": + return C.PLOT_INFO_ID.s(); + case "size": + return C.PLOT_INFO_SIZE.s(); + case "trusted": + return C.PLOT_INFO_TRUSTED.s(); + case "owner": + return C.PLOT_INFO_OWNER.s(); + case "rating": + return C.PLOT_INFO_RATING.s(); + default: + return null; + } + } + + private String format(String info, final World world, final Plot plot, final Player player) { + + final PlotId id = plot.id; + final PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id; + final int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size(); + final String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none"; + final String biome = getBiomeAt(plot).toString(); + final String helpers = getPlayerList(plot.helpers); + final String trusted = getPlayerList(plot.trusted); + final String denied = getPlayerList(plot.denied); + final String rating = String.format("%.1f", DBFunc.getRatings(plot)); + final String flags = "&3" + (StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), "&7, &3") : "none"); + final boolean build = player == null ? true : plot.hasRights(player); + + String owner = "none"; + if (plot.owner != null) { + owner = Bukkit.getOfflinePlayer(plot.owner).getName(); + } + if (owner == null) { + owner = plot.owner.toString(); + } + info = info.replaceAll("%alias%", alias); info = info.replaceAll("%id%", id.toString()); info = info.replaceAll("%id2%", id2.toString()); - info = info.replaceAll("%num%", num+""); + info = info.replaceAll("%num%", num + ""); info = info.replaceAll("%biome%", biome); info = info.replaceAll("%owner%", owner); info = info.replaceAll("%helpers%", helpers); @@ -184,47 +190,46 @@ public class Info extends SubCommand { info = info.replaceAll("%denied%", denied); info = info.replaceAll("%rating%", rating); info = info.replaceAll("%flags%", flags); - info = info.replaceAll("%build%", build+""); + info = info.replaceAll("%build%", build + ""); info = info.replaceAll("%desc%", "No description set."); - return info; - } + } - private String getPlayerList(ArrayList l) { - if ((l == null) || (l.size() < 1)) { - return " none"; - } - String c = C.PLOT_USER_LIST.s(); - StringBuilder list = new StringBuilder(); - for (int x = 0; x < l.size(); x++) { - if ((x + 1) == l.size()) { - list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); - } - else { - list.append(c.replace("%user%", getPlayerName(l.get(x)))); - } - } - return list.toString(); - } + private String getPlayerList(final ArrayList l) { + if ((l == null) || (l.size() < 1)) { + return " none"; + } + 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()) { + list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); + } + else { + list.append(c.replace("%user%", getPlayerName(l.get(x)))); + } + } + return list.toString(); + } - private String getPlayerName(UUID uuid) { - if (uuid == null) { - return "unknown"; - } - if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { - return "everyone"; - } - /* - * OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName() - * == null) { return "unknown"; } return plr.getName(); - */ - return UUIDHandler.getName(uuid); - } + private String getPlayerName(final UUID uuid) { + if (uuid == null) { + return "unknown"; + } + if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { + return "everyone"; + } + /* + * OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName() + * == null) { return "unknown"; } return plr.getName(); + */ + return UUIDHandler.getName(uuid); + } - private Biome getBiomeAt(Plot plot) { - World w = Bukkit.getWorld(plot.world); - Location bl = PlotHelper.getPlotTopLoc(w, plot.id); - return bl.getBlock().getBiome(); - } + private Biome getBiomeAt(final Plot plot) { + final World w = Bukkit.getWorld(plot.world); + final Location bl = PlotHelper.getPlotTopLoc(w, plot.id); + return bl.getBlock().getBiome(); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inventory.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inventory.java index 2629d15cd..e92465612 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inventory.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Inventory.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Inventory.java >> Generated by: Citymonstret at 2014-08-10 13:57 */ @@ -19,42 +19,41 @@ import org.bukkit.inventory.meta.ItemMeta; public class Inventory extends SubCommand { - public Inventory() { - super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO, true); - } + public Inventory() { + super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO, true); + } - @Override - public boolean execute(final Player plr, String... args) { - ArrayList cmds = new ArrayList<>(); - for (SubCommand cmd : MainCommand.subCommands) { - if (cmd.permission.hasPermission(plr)) { - cmds.add(cmd); - } - } - int size = 9 * (int) Math.ceil(cmds.size() / 9.0); - org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); - for (SubCommand cmd : cmds) { - inventory.addItem(getItem(cmd)); - } - plr.openInventory(inventory); - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + final ArrayList cmds = new ArrayList<>(); + for (final SubCommand cmd : MainCommand.subCommands) { + if (cmd.permission.hasPermission(plr)) { + cmds.add(cmd); + } + } + final int size = 9 * (int) Math.ceil(cmds.size() / 9.0); + final org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); + for (final SubCommand cmd : cmds) { + inventory.addItem(getItem(cmd)); + } + plr.openInventory(inventory); + return true; + } - private ItemStack getItem(final SubCommand cmd) { - ItemStack stack = new ItemStack(Material.COMMAND); - ItemMeta meta = stack.getItemMeta(); - { - meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias - + ChatColor.DARK_GRAY + "]"); - meta.setLore(new ArrayList() { - { - add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString()); - add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description); - add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage); - } - }); - } - stack.setItemMeta(meta); - return stack; - } + private ItemStack getItem(final SubCommand cmd) { + final ItemStack stack = new ItemStack(Material.COMMAND); + final ItemMeta meta = stack.getItemMeta(); + { + meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]"); + meta.setLore(new ArrayList() { + { + add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString()); + add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description); + add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage); + } + }); + } + stack.setItemMeta(meta); + return stack; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Kick.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Kick.java index 7ea50291e..d4f4b1e2b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Kick.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Kick.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Kick.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -21,38 +21,35 @@ import com.intellectualcrafters.plot.PlotMain; */ public class Kick extends SubCommand { - public Kick() { - super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS, true); - } + public Kick() { + super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) - && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (args.length != 1) { - PlayerFunctions.sendMessage(plr, "&c/plot kick "); - return false; - } - if (Bukkit.getPlayer(args[0]) == null) { - PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); - return false; - } - Player player = Bukkit.getPlayer(args[0]); - if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) - || (PlayerFunctions.getCurrentPlot(player) == null) - || !PlayerFunctions.getCurrentPlot(player).equals(plot)) { - PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); - return false; - } - player.teleport(player.getWorld().getSpawnLocation()); - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (args.length != 1) { + PlayerFunctions.sendMessage(plr, "&c/plot kick "); + return false; + } + if (Bukkit.getPlayer(args[0]) == null) { + PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); + return false; + } + final Player player = Bukkit.getPlayer(args[0]); + if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) || (PlayerFunctions.getCurrentPlot(player) == null) || !PlayerFunctions.getCurrentPlot(player).equals(plot)) { + PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); + return false; + } + player.teleport(player.getWorld().getSpawnLocation()); + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index 70ae52586..839054a75 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -2,16 +2,15 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = MainCommand.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.C; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.PlotMain; -import com.intellectualcrafters.plot.StringComparsion; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; @@ -21,9 +20,10 @@ import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.util.ChatPaginator; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.StringComparsion; /** * PlotMain command class @@ -32,173 +32,170 @@ import java.util.List; */ public class MainCommand implements CommandExecutor, TabCompleter { - private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), new Paste(), new Copy(), new Clipboard(), new Auto(), new Home(), new Visit(), - new TP(), new Set(), new Clear(), new Delete(), new SetOwner(), new Denied(), new Helpers(), new Trusted(), - new Info(), new list(), new Help(), new Debug(), new Schematic(), new plugin(), new Inventory(), new Purge(), - new Reload(), new Merge(), new Unlink(), new Kick(), new Setup(), new DebugClaimTest(), new Inbox(), new Comment(), new Swap(), new MusicSubcommand() }; + private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), new Paste(), new Copy(), new Clipboard(), new Auto(), new Home(), new Visit(), new TP(), new Set(), new Clear(), new Delete(), new SetOwner(), new Denied(), new Helpers(), new Trusted(), new Info(), new list(), new Help(), new Debug(), new Schematic(), new plugin(), new Inventory(), new Purge(), new Reload(), new Merge(), new Unlink(), new Kick(), new Setup(), new DebugClaimTest(), new Inbox(), new Comment(), new Swap(), new MusicSubcommand() }; - public static ArrayList subCommands = new ArrayList() { - { - addAll(Arrays.asList(_subCommands)); - } - }; + public static ArrayList subCommands = new ArrayList() { + { + addAll(Arrays.asList(_subCommands)); + } + }; - public static boolean no_permission(Player player, String permission) { - PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission); - return false; - } + public static boolean no_permission(final Player player, final String permission) { + PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission); + return false; + } - @Override - public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { - Player player = (sender instanceof Player) ? (Player) sender : null; + @Override + public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { + final Player player = (sender instanceof Player) ? (Player) sender : null; - if (!PlotMain.hasPermission(player, "plots.use")) - return no_permission(player, "plots.use"); + if (!PlotMain.hasPermission(player, "plots.use")) { + return no_permission(player, "plots.use"); + } - if ((args.length < 1) - || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) { - if (args.length < 2) { - StringBuilder builder = new StringBuilder(); - builder.append(C.HELP_INFO.s()); - for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { - builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); - } - PlayerFunctions.sendMessage(player, builder.toString()); - return true; - } - String cat = args[1]; - SubCommand.CommandCategory cato = null; - for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { - if (cat.equalsIgnoreCase(category.toString())) { - cato = category; - break; - } - } - if (cato == null) { - StringBuilder builder = new StringBuilder(); - builder.append(C.HELP_INFO.s()); - for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { - builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); - } - PlayerFunctions.sendMessage(player, builder.toString()); - return true; - } - StringBuilder help = new StringBuilder(); + if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) { + if (args.length < 2) { + final StringBuilder builder = new StringBuilder(); + builder.append(C.HELP_INFO.s()); + for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { + builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); + } + PlayerFunctions.sendMessage(player, builder.toString()); + return true; + } + final String cat = args[1]; + SubCommand.CommandCategory cato = null; + for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { + if (cat.equalsIgnoreCase(category.toString())) { + cato = category; + break; + } + } + if (cato == null) { + final StringBuilder builder = new StringBuilder(); + builder.append(C.HELP_INFO.s()); + for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { + builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); + } + PlayerFunctions.sendMessage(player, builder.toString()); + return true; + } + final StringBuilder help = new StringBuilder(); int page = 0; boolean digit = true; - for(char c : args[2].toCharArray()) - if(!Character.isDigit(c)) { + for (final char c : args[2].toCharArray()) { + if (!Character.isDigit(c)) { digit = false; break; } - if(digit) { + } + if (digit) { page = Integer.parseInt(args[2]); - if(--page < 0) page = 0; + if (--page < 0) { + page = 0; + } } - for(String string : helpMenu(player, cato, page)) + for (final String string : helpMenu(player, cato, page)) { help.append(string).append("\n"); + } - PlayerFunctions.sendMessage(player, help.toString()); - return true; - } - else { - for (SubCommand command : subCommands) { - if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) { - String[] arguments = new String[args.length - 1]; + PlayerFunctions.sendMessage(player, help.toString()); + return true; + } + else { + for (final SubCommand command : subCommands) { + if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) { + final String[] arguments = new String[args.length - 1]; System.arraycopy(args, 1, arguments, 0, args.length - 1); - if (command.permission.hasPermission(player)) { - if (player!=null || !command.isPlayer ) { - return command.execute(player, arguments); - } - else { - PlayerFunctions.sendMessage(null, C.IS_CONSOLE); - return false; - } - } - else { - return no_permission(player, command.permission.permission.toLowerCase()); - } - } - } - PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); + if (command.permission.hasPermission(player)) { + if ((player != null) || !command.isPlayer) { + return command.execute(player, arguments); + } + else { + PlayerFunctions.sendMessage(null, C.IS_CONSOLE); + return false; + } + } + else { + return no_permission(player, command.permission.permission.toLowerCase()); + } + } + } + PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); - String[] commands = new String[subCommands.size()]; - for(int x = 0; x < subCommands.size(); x++) + final String[] commands = new String[subCommands.size()]; + for (int x = 0; x < subCommands.size(); x++) { commands[x] = subCommands.get(x).cmd; + } PlayerFunctions.sendMessage(player, C.DID_YOU_MEAN, new StringComparsion(args[0], commands).getBestMatch()); - } - return false; - } + } + return false; + } - - public static List getCommands(SubCommand.CommandCategory category, Player player) { - List cmds = new ArrayList<>(); - for(SubCommand c : subCommands) - if(c.category == category && c.permission.hasPermission(player)) + public static List getCommands(final SubCommand.CommandCategory category, final Player player) { + final List cmds = new ArrayList<>(); + for (final SubCommand c : subCommands) { + if ((c.category == category) && c.permission.hasPermission(player)) { cmds.add(c); + } + } return cmds; } /* - // Current page - int page = 0; - - //is a page specified? else use 0 - if(args.length > 1) { - try { - page = Integer.parseInt(args[1]); - } catch(Exception e) { - page = 0; - } - } - - //Get the total pages - int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size()) / 100)); - - if(page > totalPages) - page = totalPages; - - //Only display 12! - int max = (page * 12) + 12; - - if(max > PlotMain.getPlotsSorted().size()) - max = PlotMain.getPlotsSorted().size(); - - StringBuilder string = new StringBuilder(); - - string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") + "\n"); - Plot p; - - //This might work xD - for (int x = (page * 12); x < max; x++) { + * // Current page + * int page = 0; + * //is a page specified? else use 0 + * if(args.length > 1) { + * try { + * page = Integer.parseInt(args[1]); + * } catch(Exception e) { + * page = 0; + * } + * } + * //Get the total pages + * int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size()) + * / 100)); + * if(page > totalPages) + * page = totalPages; + * //Only display 12! + * int max = (page * 12) + 12; + * if(max > PlotMain.getPlotsSorted().size()) + * max = PlotMain.getPlotsSorted().size(); + * StringBuilder string = new StringBuilder(); + * string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 + + * "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") + + * "\n"); + * Plot p; + * //This might work xD + * for (int x = (page * 12); x < max; x++) { */ - public static ArrayList helpMenu(Player player, final SubCommand.CommandCategory category, int page) { - List commands = getCommands(category, player); - //final int totalPages = ((int) Math.ceil(12 * (commands.size()) / 100)); - int perPage = 5; - int totalPages = (int) Math.ceil(commands.size() / perPage); - if(page > totalPages) + public static ArrayList helpMenu(final Player player, final SubCommand.CommandCategory category, int page) { + final List commands = getCommands(category, player); + // final int totalPages = ((int) Math.ceil(12 * (commands.size()) / + // 100)); + final int perPage = 5; + final int totalPages = (int) Math.ceil(commands.size() / perPage); + if (page > totalPages) { page = totalPages; + } int max = (page * perPage) + perPage; - if(max > commands.size()) + if (max > commands.size()) { max = commands.size(); - ArrayList help = new ArrayList<>( - Arrays.asList( - t(C.HELP_HEADER.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "")), - t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString())) - )); + } + final ArrayList help = new ArrayList<>(Arrays.asList(t(C.HELP_HEADER.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "")), t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString())))); SubCommand cmd; String lines = ""; - for(int x = 0; x < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH * 0.75; x++) { + for (int x = 0; x < (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH * 0.75); x++) { lines += "-"; } - int start = page * perPage; - for(int x = start; x < max; x++) { + final int start = page * perPage; + for (int x = start; x < max; x++) { cmd = subCommands.get(x); String s = t(C.HELP_PAGE.s()); s = s.replaceAll("%alias%", cmd.alias); @@ -208,29 +205,31 @@ public class MainCommand implements CommandExecutor, TabCompleter { help.add(s); - if(x != start && x != max - 1) { + if ((x != start) && (x != (max - 1))) { help.add(t(C.HELP_ITEM_SEPARATOR.s().replaceAll("%lines", lines))); } } - if (help.size() < 2) { - help.add(t(C.NO_COMMANDS.s())); - } - return help; - } + if (help.size() < 2) { + help.add(t(C.NO_COMMANDS.s())); + } + return help; + } - private static String t(String s) { - return ChatColor.translateAlternateColorCodes('&', s); - } + private static String t(final String s) { + return ChatColor.translateAlternateColorCodes('&', s); + } @Override - public List onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) { - if(!(commandSender instanceof Player)) return null; - Player player = (Player) commandSender; - - if(strings.length < 1) { - if (strings.length==0 || "plots".startsWith(s)) { - return Arrays.asList(new String[] {"plots"}); + public List onTabComplete(final CommandSender commandSender, final Command command, final String s, final String[] strings) { + if (!(commandSender instanceof Player)) { + return null; + } + final Player player = (Player) commandSender; + + if (strings.length < 1) { + if ((strings.length == 0) || "plots".startsWith(s)) { + return Arrays.asList(new String[] { "plots" }); } } if (strings.length > 1) { @@ -239,9 +238,9 @@ public class MainCommand implements CommandExecutor, TabCompleter { if (!command.getLabel().equalsIgnoreCase("plots")) { return null; } - List tabOptions = new ArrayList(); - String arg = strings[0].toLowerCase(); - for (SubCommand cmd : subCommands) { + final List tabOptions = new ArrayList(); + final String arg = strings[0].toLowerCase(); + for (final SubCommand cmd : subCommands) { if (cmd.permission.hasPermission(player)) { if (cmd.cmd.startsWith(arg)) { tabOptions.add(cmd.cmd); @@ -251,7 +250,7 @@ public class MainCommand implements CommandExecutor, TabCompleter { } } } - if(tabOptions.size()>0) { + if (tabOptions.size() > 0) { return tabOptions; } return null; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java index 499470384..73d67ec14 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Merge.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Merge.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -32,129 +32,123 @@ import com.intellectualcrafters.plot.events.PlotMergeEvent; */ public class Merge extends SubCommand { - public static String[] values = new String[] { "north", "east", "south", "west" }; - public static String[] aliases = new String[] { "n", "e", "s", "w" }; + public static String[] values = new String[] { "north", "east", "south", "west" }; + public static String[] aliases = new String[] { "n", "e", "s", "w" }; - public Merge() { - super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS, true); - } + public Merge() { + super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS, true); + } - public static String direction(float yaw) { - yaw = yaw / 90; - int i = Math.round(yaw); - switch (i) { - case -4: - case 0: - case 4: - return "SOUTH"; - case -1: - case 3: - return "EAST"; - case -2: - case 2: - return "NORTH"; - case -3: - case 1: - return "WEST"; - default: - return ""; - } - } + public static String direction(float yaw) { + yaw = yaw / 90; + final int i = Math.round(yaw); + switch (i) { + case -4: + case 0: + case 4: + return "SOUTH"; + case -1: + case 3: + return "EAST"; + case -2: + case 2: + return "NORTH"; + case -3: + case 1: + return "WEST"; + default: + return ""; + } + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot == null) || !plot.hasOwner()) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (!plot.getOwner().equals(plr.getUniqueId())) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() - + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); - PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); - return false; - } - int direction = -1; - for (int i = 0; i < values.length; i++) { - if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { - direction = i; - break; - } - } - if (direction == -1) { - PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() - + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); - PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); - return false; - } - World world = plr.getWorld(); - PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; - PlotId top = PlayerFunctions.getTopPlot(world, plot).id; - ArrayList plots; - switch (direction) { - case 0: // north = -y - plots = - PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); - break; - case 1: // east = +x - plots = - PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); - break; - case 2: // south = +y - plots = - PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); - break; - case 3: // west = -x - plots = - PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); - break; - default: - return false; - } - for (PlotId myid : plots) { - Plot myplot = PlotMain.getPlots(world).get(myid); - if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) { - PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); - return false; - } - } + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot == null) || !plot.hasOwner()) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (!plot.getOwner().equals(plr.getUniqueId())) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); + PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); + return false; + } + int direction = -1; + for (int i = 0; i < values.length; i++) { + if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { + direction = i; + break; + } + } + if (direction == -1) { + PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); + PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); + return false; + } + final World world = plr.getWorld(); + final PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; + final PlotId top = PlayerFunctions.getTopPlot(world, plot).id; + ArrayList plots; + switch (direction) { + case 0: // north = -y + plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); + break; + case 1: // east = +x + plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); + break; + case 2: // south = +y + plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); + break; + case 3: // west = -x + plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); + break; + default: + return false; + } + for (final PlotId myid : plots) { + final Plot myplot = PlotMain.getPlots(world).get(myid); + if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) { + PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); + return false; + } + } - PlotWorld plotWorld = PlotMain.getWorldSettings(world); - if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) { - double cost = plotWorld.MERGE_PRICE; - cost = plots.size() * cost; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); - return false; - } - economy.withdrawPlayer(plr, cost); - sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } + final PlotWorld plotWorld = PlotMain.getWorldSettings(world); + if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) { + double cost = plotWorld.MERGE_PRICE; + cost = plots.size() * cost; + if (cost > 0d) { + final Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); + return false; + } + economy.withdrawPlayer(plr, cost); + sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } - PlotMergeEvent event = new PlotMergeEvent(world, plot, plots); + final PlotMergeEvent event = new PlotMergeEvent(world, plot, plots); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled"); - return false; - } - PlayerFunctions.sendMessage(plr, "&cPlots have been merged"); - PlotHelper.mergePlots(world, plots); - if (PlotHelper.canSetFast) { - SetBlockFast.update(plr); - } - return true; - } + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled"); + return false; + } + PlayerFunctions.sendMessage(plr, "&cPlots have been merged"); + PlotHelper.mergePlots(world, plots); + if (PlotHelper.canSetFast) { + SetBlockFast.update(plr); + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java index ddb7c4cc1..5ee4b4d92 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java @@ -1,35 +1,38 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.C; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.listeners.PlotPlusListener; +import java.util.Arrays; + import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import java.util.Arrays; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.listeners.PlotPlusListener; + public class MusicSubcommand extends SubCommand { public MusicSubcommand() { super("music", "plots.music", "Play music in plot", "music", "mus", CommandCategory.ACTIONS, true); } + @Override - public boolean execute(Player player, String... args) { - if(!PlayerFunctions.isInPlot(player)) { + public boolean execute(final Player player, final String... args) { + if (!PlayerFunctions.isInPlot(player)) { sendMessage(player, C.NOT_IN_PLOT); return true; } - Plot plot = PlayerFunctions.getCurrentPlot(player); - if(!plot.hasRights(player)) { + final Plot plot = PlayerFunctions.getCurrentPlot(player); + if (!plot.hasRights(player)) { sendMessage(player, C.NO_PLOT_PERMS); return true; } - org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.RED + "Plot Jukebox"); - for(PlotPlusListener.RecordMeta meta : PlotPlusListener.RecordMeta.metaList) { - ItemStack stack = new ItemStack(meta.getMaterial()); - ItemMeta itemMeta = stack.getItemMeta(); + final org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.RED + "Plot Jukebox"); + for (final PlotPlusListener.RecordMeta meta : PlotPlusListener.RecordMeta.metaList) { + final ItemStack stack = new ItemStack(meta.getMaterial()); + final ItemMeta itemMeta = stack.getItemMeta(); itemMeta.setDisplayName(ChatColor.GOLD + meta.toString()); itemMeta.setLore(Arrays.asList(ChatColor.GRAY + "Click to play the record")); stack.setItemMeta(itemMeta); @@ -38,4 +41,4 @@ public class MusicSubcommand extends SubCommand { player.openInventory(inventory); return true; } -} \ No newline at end of file +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Paste.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Paste.java index f92126236..9406cd9af 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Paste.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Paste.java @@ -1,9 +1,14 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; - import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotSelection; + /** * Created by Citymonstret on 2014-10-12. */ @@ -14,14 +19,13 @@ public class Paste extends SubCommand { } @Override - public boolean execute(Player plr, String... args) { + public boolean execute(final Player plr, final String... args) { if (!PlayerFunctions.isInPlot(plr)) { PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); return false; } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) - && !PlotMain.hasPermission(plr,"plots.admin")) { + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); return false; } @@ -30,17 +34,18 @@ public class Paste extends SubCommand { return false; } assert plot != null; - int size = (PlotHelper.getPlotTopLocAbs(plr.getWorld(), plot.getId()).getBlockX() - PlotHelper.getPlotBottomLocAbs(plr.getWorld(), plot.getId()).getBlockX()); + final int size = (PlotHelper.getPlotTopLocAbs(plr.getWorld(), plot.getId()).getBlockX() - PlotHelper.getPlotBottomLocAbs(plr.getWorld(), plot.getId()).getBlockX()); - if(PlotSelection.currentSelection.containsKey(plr.getName())) { - PlotSelection selection = PlotSelection.currentSelection.get(plr.getName()); - if(size != selection.getWidth()) { + if (PlotSelection.currentSelection.containsKey(plr.getName())) { + final PlotSelection selection = PlotSelection.currentSelection.get(plr.getName()); + if (size != selection.getWidth()) { sendMessage(plr, C.PASTE_FAILED, "The size of the current plot is not the same as the paste"); return false; } selection.paste(plr.getWorld(), plot); sendMessage(plr, C.PASTED); - } else { + } + else { sendMessage(plr, C.NO_CLIPBOARD); return false; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java index 3b03ae3b8..4daa5d157 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Purge.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Purge.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ @@ -22,61 +22,61 @@ import com.intellectualcrafters.plot.database.DBFunc; */ public class Purge extends SubCommand { - public Purge() { - super("purge", "plots.admin", "Purge all plots for a world", "purge", "", CommandCategory.DEBUG, false); - } + public Purge() { + super("purge", "plots.admin", "Purge all plots for a world", "purge", "", CommandCategory.DEBUG, false); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length!=2) { - if (args.length==1) { - try { - String[] split = args[0].split(";"); - String world = split[0]; - PlotId id = new PlotId(Integer.parseInt(split[1]), Integer.parseInt(split[2])); - - System.out.print("VALID ID"); - - if (plr!=null) { - PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE)); - return false; - } - - if (!PlotMain.isPlotWorld(world)) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); - return false; - } - PlotMain.getPlots(world).remove(id); - DBFunc.purge(world, id); - PlayerFunctions.sendMessage(plr, "&aPurge of '"+args[0]+"' was successful!"); - return true; - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); - } - } - PlayerFunctions.sendMessage(plr, C.PURGE_SYNTAX); - return false; - } - if (args[1].equals("-o")) { - PlotWorld plotworld = PlotMain.getWorldSettings(args[0]); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); - return false; - } - if (plr!=null) { - PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE)); - return false; - } - PlotMain.removePlotWorld(args[0]); - DBFunc.purge(args[0]); - PlayerFunctions.sendMessage(plr, (C.PURGE_SUCCESS)); - return true; - } - else { - PlayerFunctions.sendMessage(plr, "This is a dangerous command, if you are sure, use /plot purge {world} -o"); - return false; - } - } + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length != 2) { + if (args.length == 1) { + try { + final String[] split = args[0].split(";"); + final String world = split[0]; + final PlotId id = new PlotId(Integer.parseInt(split[1]), Integer.parseInt(split[2])); + + System.out.print("VALID ID"); + + if (plr != null) { + PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE)); + return false; + } + + if (!PlotMain.isPlotWorld(world)) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); + return false; + } + PlotMain.getPlots(world).remove(id); + DBFunc.purge(world, id); + PlayerFunctions.sendMessage(plr, "&aPurge of '" + args[0] + "' was successful!"); + return true; + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); + } + } + PlayerFunctions.sendMessage(plr, C.PURGE_SYNTAX); + return false; + } + if (args[1].equals("-o")) { + final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); + return false; + } + if (plr != null) { + PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE)); + return false; + } + PlotMain.removePlotWorld(args[0]); + DBFunc.purge(args[0]); + PlayerFunctions.sendMessage(plr, (C.PURGE_SUCCESS)); + return true; + } + else { + PlayerFunctions.sendMessage(plr, "This is a dangerous command, if you are sure, use /plot purge {world} -o"); + return false; + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index 9789b6ec0..8f2ac263c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -11,63 +11,63 @@ import com.intellectualcrafters.plot.Plot; */ public class Rate extends SubCommand { - /* - * String cmd, String permission, String description, String usage, String - * alias, CommandCategory category - */ + /* + * String cmd, String permission, String description, String usage, String + * alias, CommandCategory category + */ - public Rate() { - super("rate", "plots.rate", "Rate the plot", "rate {0-10}", "rt", CommandCategory.ACTIONS, true); - } + public Rate() { + super("rate", "plots.rate", "Rate the plot", "rate {0-10}", "rt", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - sendMessage(plr, C.RATING_NOT_VALID); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!plot.hasOwner()) { - sendMessage(plr, C.RATING_NOT_OWNED); - return true; - } - if (plot.getOwner().equals(plr.getUniqueId())) { - sendMessage(plr, C.RATING_NOT_YOUR_OWN); - return true; - } - String arg = args[0]; - boolean o = false; - for (char c : arg.toCharArray()) { - if (!Character.isDigit(c)) { - o = true; - break; - } - } - int rating = 0; - if (!o) { - rating = Integer.parseInt(arg); - } - if (o || ((rating < 0) || (rating > 10))) { - sendMessage(plr, C.RATING_NOT_VALID); - return true; - } - // TODO implement check for already rated - boolean rated = false; - if (rated) { - sendMessage(plr, C.RATING_ALREADY_EXISTS, plot.getId().toString()); - } - // TODO actually do something... - boolean success = false; - if (success) { - sendMessage(plr, C.RATING_APPLIED, plot.getId().toString()); - } - else { - sendMessage(plr, C.COMMAND_WENT_WRONG); - } - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 1) { + sendMessage(plr, C.RATING_NOT_VALID); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!plot.hasOwner()) { + sendMessage(plr, C.RATING_NOT_OWNED); + return true; + } + if (plot.getOwner().equals(plr.getUniqueId())) { + sendMessage(plr, C.RATING_NOT_YOUR_OWN); + return true; + } + final String arg = args[0]; + boolean o = false; + for (final char c : arg.toCharArray()) { + if (!Character.isDigit(c)) { + o = true; + break; + } + } + int rating = 0; + if (!o) { + rating = Integer.parseInt(arg); + } + if (o || ((rating < 0) || (rating > 10))) { + sendMessage(plr, C.RATING_NOT_VALID); + return true; + } + // TODO implement check for already rated + final boolean rated = false; + if (rated) { + sendMessage(plr, C.RATING_ALREADY_EXISTS, plot.getId().toString()); + } + // TODO actually do something... + final boolean success = false; + if (success) { + sendMessage(plr, C.RATING_APPLIED, plot.getId().toString()); + } + else { + sendMessage(plr, C.COMMAND_WENT_WRONG); + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java index 1cc0daa26..c0953b920 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Reload.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Reload.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ @@ -20,30 +20,31 @@ import com.intellectualcrafters.plot.PlotWorld; */ public class Reload extends SubCommand { - public Reload() { - super("reload", "plots.admin", "Reload configurations", "", "reload", CommandCategory.INFO, false); - - // TODO reload worlds as well - - } + public Reload() { + super("reload", "plots.admin", "Reload configurations", "", "reload", CommandCategory.INFO, false); - @Override - public boolean execute(Player plr, String... args) { - try { - PlotMain.reloadTranslations(); - - // The following won't affect world generation, as that has to be loaded during startup unfortunately. - PlotMain.config.load(PlotMain.configFile); - for (String pw: PlotMain.getPlotWorlds()) { - PlotWorld plotworld = PlotMain.getWorldSettings(pw); - plotworld.loadDefaultConfiguration(PlotMain.config.getConfigurationSection("worlds." + pw)); - } - PlotMain.BroadcastWithPerms(C.RELOADED_CONFIGS); - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.RELOAD_FAILED); - } - return true; - } + // TODO reload worlds as well + + } + + @Override + public boolean execute(final Player plr, final String... args) { + try { + PlotMain.reloadTranslations(); + + // The following won't affect world generation, as that has to be + // loaded during startup unfortunately. + PlotMain.config.load(PlotMain.configFile); + for (final String pw : PlotMain.getPlotWorlds()) { + final PlotWorld plotworld = PlotMain.getWorldSettings(pw); + plotworld.loadDefaultConfiguration(PlotMain.config.getConfigurationSection("worlds." + pw)); + } + PlotMain.BroadcastWithPerms(C.RELOADED_CONFIGS); + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.RELOAD_FAILED); + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Schematic.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Schematic.java index 014fbbd0f..0bdba3176 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Schematic.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Schematic.java @@ -1,9 +1,6 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.SchematicHandler.DataCollection; -import com.intellectualcrafters.plot.SchematicHandler.Dimension; +import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -11,317 +8,325 @@ import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import java.util.HashMap; +import com.intellectualcrafters.jnbt.CompoundTag; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.SchematicHandler; +import com.intellectualcrafters.plot.SchematicHandler.DataCollection; +import com.intellectualcrafters.plot.SchematicHandler.Dimension; +import com.intellectualcrafters.plot.SetBlockFast; +import com.intellectualcrafters.plot.Settings; +import com.intellectualcrafters.plot.UUIDHandler; public class Schematic extends SubCommand { public Schematic() { super("schematic", "plots.admin", "Schematic Command", "schematic {arg}", "sch", CommandCategory.ACTIONS, false); - + // TODO command to fetch schematic from worldedit directory } - - private int counter = 0; + + private int counter = 0; private boolean running = false; - private Plot[] plots; - private int task; - - + private Plot[] plots; + private int task; + @Override - public boolean execute(final Player plr, String... args) { + public boolean execute(final Player plr, final String... args) { if (args.length < 1) { sendMessage(plr, C.SCHEMATIC_MISSING_ARG); return true; } - String arg = args[0].toLowerCase(); + final String arg = args[0].toLowerCase(); final String file; final SchematicHandler.Schematic schematic; switch (arg) { - case "paste": - if (plr==null) { - PlotMain.sendConsoleSenderMessage(C.IS_CONSOLE); - return false; - } - if (!PlotMain.hasPermission(plr, "plots.schematic.paste")) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.paste"); - return false; - } - if (args.length < 2) { - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - break; - } - if (!PlayerFunctions.isInPlot(plr)) { - sendMessage(plr, C.NOT_IN_PLOT); - break; - } - if (running) { - PlayerFunctions.sendMessage(plr, "&cTask is already running."); - return false; - } - final String file2 = args[1]; - running = true; - this.counter = 0; - Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"), new Runnable() { - @Override - public void run() { - final SchematicHandler.Schematic schematic = SchematicHandler.getSchematic(file2); - if (schematic==null) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); - running = false; - return; - } - - - final int x; - final int z; - - final Plot plot2 = PlayerFunctions.getCurrentPlot(plr); - - Dimension dem = schematic.getSchematicDimension(); - Location bot = PlotHelper.getPlotBottomLoc(plr.getWorld(), plot2.id).add(1, 0, 1); - int length2 = PlotHelper.getPlotWidth(plr.getWorld(), plot2.id); - - if ((dem.getX() > length2) || (dem.getZ() > length2)) { - sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", dem.getX(), dem.getZ(), length2)); - running = false; - return; - } - - if (dem.getX() != length2 || dem.getZ() != length2) { - Location loc = plr.getLocation(); - x = Math.min(length2-dem.getX(),loc.getBlockX() - bot.getBlockX()); - z = Math.min(length2-dem.getZ(),loc.getBlockZ() - bot.getBlockZ()); - } - else { - x = 0; - z = 0; - } - - final World w = plot2.getWorld(); - final DataCollection[] b = schematic.getBlockCollection(); - int sy = w.getHighestBlockYAt(bot.getBlockX(), bot.getBlockZ()); - final Location l1 = bot.add(0, sy-1, 0); - final int WIDTH = schematic.getSchematicDimension().getX(); - final int LENGTH = schematic.getSchematicDimension().getZ(); - final int blen = b.length-1; - - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"); - task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { - boolean result = false; - while (!result) { - int start = counter*5000; - if (start>blen) { - sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); - if (PlotHelper.canSetFast) { - SetBlockFast.update(plr); - } - running = false; - Bukkit.getScheduler().cancelTask(task); - return; - } - int end = Math.min(start+5000,blen); - result = SchematicHandler.pastePart(w, b, l1, x, z, start, end, WIDTH, LENGTH); - counter++; - } - } - }, 1, 1); + case "paste": + if (plr == null) { + PlotMain.sendConsoleSenderMessage(C.IS_CONSOLE); + return false; } - }); - break; - case "test": - if (plr==null) { - PlotMain.sendConsoleSenderMessage(C.IS_CONSOLE); - return false; - } - if (!PlotMain.hasPermission(plr, "plots.schematic.test")) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.test"); - return false; - } - if (args.length < 2) { - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - break; - } - file = args[1]; - schematic = SchematicHandler.getSchematic(file); - if (schematic == null) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); - break; - } - - int l1 = schematic.getSchematicDimension().getX(); - int l2 = schematic.getSchematicDimension().getZ(); + if (!PlotMain.hasPermission(plr, "plots.schematic.paste")) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.paste"); + return false; + } + if (args.length < 2) { + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + break; + } + if (!PlayerFunctions.isInPlot(plr)) { + sendMessage(plr, C.NOT_IN_PLOT); + break; + } + if (this.running) { + PlayerFunctions.sendMessage(plr, "&cTask is already running."); + return false; + } + final String file2 = args[1]; + this.running = true; + this.counter = 0; + Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"), new Runnable() { + @Override + public void run() { + final SchematicHandler.Schematic schematic = SchematicHandler.getSchematic(file2); + if (schematic == null) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); + Schematic.this.running = false; + return; + } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - int length = PlotHelper.getPlotWidth(plr.getWorld(), plot.id); + final int x; + final int z; - if ((l1 < length) || (l2 < length)) { - sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); - break; - } - sendMessage(plr, C.SCHEMATIC_VALID); - break; - case "saveall": - case "exportall": - if (plr!=null) { - PlayerFunctions.sendMessage(plr, C.NOT_CONSOLE); - return false; - } - if (args.length!=2) { - PlayerFunctions.sendMessage(plr, "&cNeed world arg. Use &7/plots sch exportall "); - return false; - } - HashMap plotmap = PlotMain.getPlots(args[1]); - if (plotmap==null || plotmap.size()==0) { - PlayerFunctions.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall "); - return false; - } - if (running) { - PlayerFunctions.sendMessage(plr, "&cTask is already running."); - return false; - } - - PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); - PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &7Found &c"+plotmap.size()+"&7 plots..."); - final World worldObj = Bukkit.getWorld(args[1]); - final String worldname = Bukkit.getWorld(args[1]).getName(); - - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"); - - - this.plots = plotmap.values().toArray(new Plot[0]); - this.running = true; - this.counter = 0; - - task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { - if (counter>=plots.length) { - PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &aFinished!"); - running = false; - Bukkit.getScheduler().cancelTask(task); - return; - } - final Plot plot = plots[counter]; - final CompoundTag sch = SchematicHandler.getCompoundTag(worldObj, plot.id); - String o = UUIDHandler.getName(plot.owner); - final String owner = o==null ? "unknown" : o ; - if (sch==null) { - PlayerFunctions.sendMessage(plr, "&7 - Skipped plot &c"+plot.id); - } - else { - Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"), new Runnable() { + final Plot plot2 = PlayerFunctions.getCurrentPlot(plr); + + final Dimension dem = schematic.getSchematicDimension(); + final Location bot = PlotHelper.getPlotBottomLoc(plr.getWorld(), plot2.id).add(1, 0, 1); + final int length2 = PlotHelper.getPlotWidth(plr.getWorld(), plot2.id); + + if ((dem.getX() > length2) || (dem.getZ() > length2)) { + sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", dem.getX(), dem.getZ(), length2)); + Schematic.this.running = false; + return; + } + + if ((dem.getX() != length2) || (dem.getZ() != length2)) { + final Location loc = plr.getLocation(); + x = Math.min(length2 - dem.getX(), loc.getBlockX() - bot.getBlockX()); + z = Math.min(length2 - dem.getZ(), loc.getBlockZ() - bot.getBlockZ()); + } + else { + x = 0; + z = 0; + } + + final World w = plot2.getWorld(); + final DataCollection[] b = schematic.getBlockCollection(); + final int sy = w.getHighestBlockYAt(bot.getBlockX(), bot.getBlockZ()); + final Location l1 = bot.add(0, sy - 1, 0); + final int WIDTH = schematic.getSchematicDimension().getX(); + final int LENGTH = schematic.getSchematicDimension().getZ(); + final int blen = b.length - 1; + + final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"); + Schematic.this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { @Override public void run() { - PlayerFunctions.sendMessage(plr, "&6ID: "+plot.id); - boolean result = SchematicHandler.save(sch, Settings.SCHEMATIC_SAVE_PATH+"/"+plot.id.x+";"+plot.id.y+","+worldname+","+owner+".schematic"); + boolean result = false; + while (!result) { + final int start = Schematic.this.counter * 5000; + if (start > blen) { + sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); + if (PlotHelper.canSetFast) { + SetBlockFast.update(plr); + } + Schematic.this.running = false; + Bukkit.getScheduler().cancelTask(Schematic.this.task); + return; + } + final int end = Math.min(start + 5000, blen); + result = SchematicHandler.pastePart(w, b, l1, x, z, start, end, WIDTH, LENGTH); + Schematic.this.counter++; + } + } + }, 1, 1); + } + }); + break; + case "test": + if (plr == null) { + PlotMain.sendConsoleSenderMessage(C.IS_CONSOLE); + return false; + } + if (!PlotMain.hasPermission(plr, "plots.schematic.test")) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.test"); + return false; + } + if (args.length < 2) { + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + break; + } + file = args[1]; + schematic = SchematicHandler.getSchematic(file); + if (schematic == null) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); + break; + } + + final int l1 = schematic.getSchematicDimension().getX(); + final int l2 = schematic.getSchematicDimension().getZ(); + + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + final int length = PlotHelper.getPlotWidth(plr.getWorld(), plot.id); + + if ((l1 < length) || (l2 < length)) { + sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); + break; + } + sendMessage(plr, C.SCHEMATIC_VALID); + break; + case "saveall": + case "exportall": + if (plr != null) { + PlayerFunctions.sendMessage(plr, C.NOT_CONSOLE); + return false; + } + if (args.length != 2) { + PlayerFunctions.sendMessage(plr, "&cNeed world arg. Use &7/plots sch exportall "); + return false; + } + final HashMap plotmap = PlotMain.getPlots(args[1]); + if ((plotmap == null) || (plotmap.size() == 0)) { + PlayerFunctions.sendMessage(plr, "&cInvalid world. Use &7/plots sch exportall "); + return false; + } + if (this.running) { + PlayerFunctions.sendMessage(plr, "&cTask is already running."); + return false; + } + + PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &7Mass export has started. This may take a while."); + PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &7Found &c" + plotmap.size() + "&7 plots..."); + final World worldObj = Bukkit.getWorld(args[1]); + final String worldname = Bukkit.getWorld(args[1]).getName(); + + final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"); + + this.plots = plotmap.values().toArray(new Plot[0]); + this.running = true; + this.counter = 0; + + this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { + @Override + public void run() { + if (Schematic.this.counter >= Schematic.this.plots.length) { + PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &aFinished!"); + Schematic.this.running = false; + Bukkit.getScheduler().cancelTask(Schematic.this.task); + return; + } + final Plot plot = Schematic.this.plots[Schematic.this.counter]; + final CompoundTag sch = SchematicHandler.getCompoundTag(worldObj, plot.id); + final String o = UUIDHandler.getName(plot.owner); + final String owner = o == null ? "unknown" : o; + if (sch == null) { + PlayerFunctions.sendMessage(plr, "&7 - Skipped plot &c" + plot.id); + } + else { + Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"), new Runnable() { + @Override + public void run() { + PlayerFunctions.sendMessage(plr, "&6ID: " + plot.id); + final boolean result = SchematicHandler.save(sch, Settings.SCHEMATIC_SAVE_PATH + "/" + plot.id.x + ";" + plot.id.y + "," + worldname + "," + owner + ".schematic"); if (!result) { - PlayerFunctions.sendMessage(plr, "&7 - Failed to save &c"+plot.id); + PlayerFunctions.sendMessage(plr, "&7 - Failed to save &c" + plot.id); } else { - PlayerFunctions.sendMessage(plr, "&7 - &aExport success: "+plot.id); + PlayerFunctions.sendMessage(plr, "&7 - &aExport success: " + plot.id); } - } - }); + } + }); + } + Schematic.this.counter++; } - counter++; - } - }, 20, 20); - break; - case "export": - case "save": - if (!PlotMain.hasPermission(plr, "plots.schematic.save")) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.save"); - return false; - } - if (running) { - PlayerFunctions.sendMessage(plr, "&cTask is already running."); - return false; - } - final String world; - final Plot p2; - if (plr!=null) { - if(!PlayerFunctions.isInPlot(plr)) { - sendMessage(plr, C.NOT_IN_PLOT); + }, 20, 20); + break; + case "export": + case "save": + if (!PlotMain.hasPermission(plr, "plots.schematic.save")) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.save"); return false; } - Plot myplot = PlayerFunctions.getCurrentPlot(plr); - if(!myplot.hasRights(plr)) { - sendMessage(plr, C.NO_PLOT_PERMS); + if (this.running) { + PlayerFunctions.sendMessage(plr, "&cTask is already running."); return false; } - p2 = myplot; - world = plr.getWorld().getName(); - } - else { - if (args.length==3) { - try { - world = args[0]; - String[] split = args[2].split(";"); - PlotId i = new PlotId(Integer.parseInt(split[0]),Integer.parseInt(split[1])); - if (PlotMain.getPlots(world)==null || PlotMain.getPlots(world).get(i) == null) { + final String world; + final Plot p2; + if (plr != null) { + if (!PlayerFunctions.isInPlot(plr)) { + sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + final Plot myplot = PlayerFunctions.getCurrentPlot(plr); + if (!myplot.hasRights(plr)) { + sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + p2 = myplot; + world = plr.getWorld().getName(); + } + else { + if (args.length == 3) { + try { + world = args[0]; + final String[] split = args[2].split(";"); + final PlotId i = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); + if ((PlotMain.getPlots(world) == null) || (PlotMain.getPlots(world).get(i) == null)) { + PlayerFunctions.sendMessage(plr, "&cInvalid world or id. Use &7/plots sch save "); + return false; + } + p2 = PlotMain.getPlots(world).get(i); + } + catch (final Exception e) { PlayerFunctions.sendMessage(plr, "&cInvalid world or id. Use &7/plots sch save "); return false; } - p2 = PlotMain.getPlots(world).get(i); } - catch (Exception e) { + else { PlayerFunctions.sendMessage(plr, "&cInvalid world or id. Use &7/plots sch save "); return false; } } - else { - PlayerFunctions.sendMessage(plr, "&cInvalid world or id. Use &7/plots sch save "); - return false; - } - } - - final Plugin plugin2 = Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"); - - - this.plots = new Plot[] {p2} ; - this.running = true; - this.counter = 0; - - task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin2, new Runnable() { - @Override - public void run() { - if (counter>=plots.length) { - PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &aFinished!"); - running = false; - Bukkit.getScheduler().cancelTask(task); - return; - } - final Plot plot = plots[counter]; - final CompoundTag sch = SchematicHandler.getCompoundTag(Bukkit.getWorld(world), plot.id); - String o = UUIDHandler.getName(plot.owner); - final String owner = o==null ? "unknown" : o ; - if (sch==null) { - PlayerFunctions.sendMessage(plr, "&7 - Skipped plot &c"+plot.id); - } - else { - Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"), new Runnable() { - @Override - public void run() { - PlayerFunctions.sendMessage(plr, "&6ID: "+plot.id); - boolean result = SchematicHandler.save(sch, Settings.SCHEMATIC_SAVE_PATH+"/"+plot.id.x+";"+plot.id.y+","+world+","+owner.trim()+".schematic"); + + final Plugin plugin2 = Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"); + + this.plots = new Plot[] { p2 }; + this.running = true; + this.counter = 0; + + this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin2, new Runnable() { + @Override + public void run() { + if (Schematic.this.counter >= Schematic.this.plots.length) { + PlotMain.sendConsoleSenderMessage("&3PlotSquared&8->&3Schemaitc&8: &aFinished!"); + Schematic.this.running = false; + Bukkit.getScheduler().cancelTask(Schematic.this.task); + return; + } + final Plot plot = Schematic.this.plots[Schematic.this.counter]; + final CompoundTag sch = SchematicHandler.getCompoundTag(Bukkit.getWorld(world), plot.id); + final String o = UUIDHandler.getName(plot.owner); + final String owner = o == null ? "unknown" : o; + if (sch == null) { + PlayerFunctions.sendMessage(plr, "&7 - Skipped plot &c" + plot.id); + } + else { + Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getServer().getPluginManager().getPlugin("PlotSquared"), new Runnable() { + @Override + public void run() { + PlayerFunctions.sendMessage(plr, "&6ID: " + plot.id); + final boolean result = SchematicHandler.save(sch, Settings.SCHEMATIC_SAVE_PATH + "/" + plot.id.x + ";" + plot.id.y + "," + world + "," + owner.trim() + ".schematic"); if (!result) { - PlayerFunctions.sendMessage(plr, "&7 - Failed to save &c"+plot.id); + PlayerFunctions.sendMessage(plr, "&7 - Failed to save &c" + plot.id); } else { - PlayerFunctions.sendMessage(plr, "&7 - &aExport success: "+plot.id); + PlayerFunctions.sendMessage(plr, "&7 - &aExport success: " + plot.id); } - } - }); + } + }); + } + Schematic.this.counter++; } - counter++; - } - }, 20, 60); - break; - default: - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - break; + }, 20, 60); + break; + default: + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + break; } return true; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java index e53ed5781..1b22e7c63 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Set.java @@ -2,17 +2,15 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Set.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.events.PlotFlagAddEvent; -import com.intellectualcrafters.plot.events.PlotFlagRemoveEvent; -import com.intellectualcrafters.plot.listeners.PlayerEvents; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; @@ -21,424 +19,444 @@ import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import com.intellectualcrafters.plot.AbstractFlag; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.Flag; +import com.intellectualcrafters.plot.FlagManager; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotBlock; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotHomePosition; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.StringComparsion; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.events.PlotFlagAddEvent; +import com.intellectualcrafters.plot.events.PlotFlagRemoveEvent; +import com.intellectualcrafters.plot.listeners.PlotListener; /** * @author Citymonstret */ public class Set extends SubCommand { - public Set() { - super(Command.SET, "Set a plot value", "set {arg} {value...}", CommandCategory.ACTIONS, true); - } + public Set() { + super(Command.SET, "Set a plot value", "set {arg} {value...}", CommandCategory.ACTIONS, true); + } - public static String[] values = new String[] { "biome", "wall", "wall_filling", "floor", "alias", "home", - "flag" }; - public static String[] aliases = new String[] { "b", "w", "wf", "f", "a", "h", "fl" }; + public static String[] values = new String[] { "biome", "wall", "wall_filling", "floor", "alias", "home", "flag" }; + public static String[] aliases = new String[] { "b", "w", "wf", "f", "a", "h", "fl" }; - @SuppressWarnings("deprecation") - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if(!plot.hasOwner()) { + @SuppressWarnings("deprecation") + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!plot.hasOwner()) { sendMessage(plr, C.PLOT_NOT_CLAIMED); return false; } - if (!plot.hasRights(plr) && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (args.length < 1) { - StringBuilder builder = new StringBuilder(); - builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); - builder.append(getArgumentList(values)); - PlayerFunctions.sendMessage(plr, builder.toString()); - return false; - } - for (int i = 0; i < aliases.length; i++) { - if (aliases[i].equalsIgnoreCase(args[0])) { - args[0] = values[i]; - break; - } - } - /* TODO: Implement option */ - boolean advanced_permissions = true; - if (advanced_permissions) { - if (!PlotMain.hasPermission(plr,"plots.set." + args[0].toLowerCase())) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.set."+args[0].toLowerCase()); - return false; - } - } + if (!plot.hasRights(plr) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (args.length < 1) { + final StringBuilder builder = new StringBuilder(); + builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); + builder.append(getArgumentList(values)); + PlayerFunctions.sendMessage(plr, builder.toString()); + return false; + } + for (int i = 0; i < aliases.length; i++) { + if (aliases[i].equalsIgnoreCase(args[0])) { + args[0] = values[i]; + break; + } + } + /* TODO: Implement option */ + final boolean advanced_permissions = true; + if (advanced_permissions) { + if (!PlotMain.hasPermission(plr, "plots.set." + args[0].toLowerCase())) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.set." + args[0].toLowerCase()); + return false; + } + } - if (args[0].equalsIgnoreCase("flag")) { - if (args.length < 2) { - String message = StringUtils.join(FlagManager.getFlags(plr), "&c, &6"); - if (PlotMain.worldGuardListener != null) { - if (message.equals("")) { - message = StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); - } - else { - message += "," + StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); - } - } - PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", message)); - return false; - } - - AbstractFlag af; - - try { - af = FlagManager.getFlag(args[1].toLowerCase()); - } - catch (Exception e) { - af = new AbstractFlag(args[1].toLowerCase()); - } - - if (!FlagManager.getFlags().contains(af) && ((PlotMain.worldGuardListener == null) || !PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase()))) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG); - return false; - } - if (!PlotMain.hasPermission(plr, "plots.set.flag." + args[1].toLowerCase())) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - return false; - } - if (args.length == 2) { - if (plot.settings.getFlag(args[1].toLowerCase()) == null) { - if (PlotMain.worldGuardListener != null) { - if (PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) { - PlotMain.worldGuardListener.removeFlag(plr, plr.getWorld(), plot, args[1]); - return false; - } - } - PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT); - return false; - } - Flag flag = plot.settings.getFlag(args[1].toLowerCase()); - PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED); - event.setCancelled(true); - return false; - } - java.util.Set newflags = plot.settings.getFlags(); - Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase()); - if (oldFlag != null) { - newflags.remove(oldFlag); - } - plot.settings.setFlags(newflags.toArray(new Flag[0])); - DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[0])); - PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED); - PlayerEvents.plotEntry(plr, plot); - return true; - } - try { - String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); - value = af.parseValue(value); - if (value==null) { - PlayerFunctions.sendMessage(plr, af.getValueDesc()); - return false; - } - - if ((FlagManager.getFlag(args[1].toLowerCase()) == null) && (PlotMain.worldGuardListener != null)) { - PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(), plot, args[1], value); - return false; - } - - Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), value); - PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED); - event.setCancelled(true); - return false; - } - plot.settings.addFlag(flag); - DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings.getFlags().toArray(new Flag[0])); - PlayerFunctions.sendMessage(plr, C.FLAG_ADDED); - PlayerEvents.plotEntry(plr, plot); - return true; - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, "&c" + e.getMessage()); - return false; - } - } + if (args[0].equalsIgnoreCase("flag")) { + if (args.length < 2) { + String message = StringUtils.join(FlagManager.getFlags(plr), "&c, &6"); + if (PlotMain.worldGuardListener != null) { + if (message.equals("")) { + message = StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); + } + else { + message += "," + StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); + } + } + PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", message)); + return false; + } + AbstractFlag af; - if (args[0].equalsIgnoreCase("home")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.MISSING_POSITION); - return false; - } - PlotHomePosition position = null; - for (PlotHomePosition p : PlotHomePosition.values()) { - if (p.isMatching(args[1])) { - position = p; - } - } - if (position == null) { - PlayerFunctions.sendMessage(plr, C.INVALID_POSITION); - return false; - } - DBFunc.setPosition(plr.getWorld().getName(), plot, position.toString()); - PlayerFunctions.sendMessage(plr, C.POSITION_SET); - return true; - } + try { + af = FlagManager.getFlag(args[1].toLowerCase()); + } + catch (final Exception e) { + af = new AbstractFlag(args[1].toLowerCase()); + } - if (args[0].equalsIgnoreCase("alias")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS); - return false; - } - String alias = args[1]; - for (Plot p : PlotMain.getPlots(plr.getWorld()).values()) { - if (p.settings.getAlias().equalsIgnoreCase(alias)) { - PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); - return false; - } - if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) { - PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); - return false; - } - } - DBFunc.setAlias(plr.getWorld().getName(), plot, alias); - PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); - return true; - } - if (args[0].equalsIgnoreCase("biome")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BIOME); - return true; - } - if(args[1].length() < 2) { + if (!FlagManager.getFlags().contains(af) && ((PlotMain.worldGuardListener == null) || !PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase()))) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG); + return false; + } + if (!PlotMain.hasPermission(plr, "plots.set.flag." + args[1].toLowerCase())) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + return false; + } + if (args.length == 2) { + if (plot.settings.getFlag(args[1].toLowerCase()) == null) { + if (PlotMain.worldGuardListener != null) { + if (PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) { + PlotMain.worldGuardListener.removeFlag(plr, plr.getWorld(), plot, args[1]); + return false; + } + } + PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT); + return false; + } + final Flag flag = plot.settings.getFlag(args[1].toLowerCase()); + final PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED); + event.setCancelled(true); + return false; + } + final java.util.Set newflags = plot.settings.getFlags(); + final Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase()); + if (oldFlag != null) { + newflags.remove(oldFlag); + } + plot.settings.setFlags(newflags.toArray(new Flag[0])); + DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[0])); + PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED); + PlotListener.plotEntry(plr, plot); + return true; + } + try { + String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); + value = af.parseValue(value); + if (value == null) { + PlayerFunctions.sendMessage(plr, af.getValueDesc()); + return false; + } + + if ((FlagManager.getFlag(args[1].toLowerCase()) == null) && (PlotMain.worldGuardListener != null)) { + PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(), plot, args[1], value); + return false; + } + + final Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), value); + final PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED); + event.setCancelled(true); + return false; + } + plot.settings.addFlag(flag); + DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings.getFlags().toArray(new Flag[0])); + PlayerFunctions.sendMessage(plr, C.FLAG_ADDED); + PlotListener.plotEntry(plr, plot); + return true; + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, "&c" + e.getMessage()); + return false; + } + } + + if (args[0].equalsIgnoreCase("home")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.MISSING_POSITION); + return false; + } + PlotHomePosition position = null; + for (final PlotHomePosition p : PlotHomePosition.values()) { + if (p.isMatching(args[1])) { + position = p; + } + } + if (position == null) { + PlayerFunctions.sendMessage(plr, C.INVALID_POSITION); + return false; + } + DBFunc.setPosition(plr.getWorld().getName(), plot, position.toString()); + PlayerFunctions.sendMessage(plr, C.POSITION_SET); + return true; + } + + if (args[0].equalsIgnoreCase("alias")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS); + return false; + } + final String alias = args[1]; + for (final Plot p : PlotMain.getPlots(plr.getWorld()).values()) { + if (p.settings.getAlias().equalsIgnoreCase(alias)) { + PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); + return false; + } + if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) { + PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); + return false; + } + } + DBFunc.setAlias(plr.getWorld().getName(), plot, alias); + PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); + return true; + } + if (args[0].equalsIgnoreCase("biome")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BIOME); + return true; + } + if (args[1].length() < 2) { sendMessage(plr, C.NAME_LITTLE, "Biome", args[1].length() + "", "2"); return true; } - Biome biome = Biome.valueOf(new StringComparsion(args[1], Biome.values()).getBestMatch()); - /*for (Biome b : Biome.values()) { - if (b.toString().equalsIgnoreCase(args[1])) { - biome = b; - break; - } - }*/ + final Biome biome = Biome.valueOf(new StringComparsion(args[1], Biome.values()).getBestMatch()); + /* + * for (Biome b : Biome.values()) { + * if (b.toString().equalsIgnoreCase(args[1])) { + * biome = b; + * break; + * } + * } + */ - if (biome == null) { - PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values()))); - return true; - } - PlotHelper.setBiome(plr.getWorld(), plot, biome); - PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase()); - return true; - } - if (args[0].equalsIgnoreCase("wall")) { - PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return true; - } - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); - return true; - } - if(args[1].length() < 2) { + if (biome == null) { + PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values()))); + return true; + } + PlotHelper.setBiome(plr.getWorld(), plot, biome); + PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase()); + return true; + } + if (args[0].equalsIgnoreCase("wall")) { + final PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return true; + } + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); + return true; + } + if (args[1].length() < 2) { sendMessage(plr, C.NAME_LITTLE, "Material", args[1].length() + "", "2"); return true; } - Material material = getMaterial(args[1], PlotWorld.BLOCKS); - /*for (Material m : PlotWorld.BLOCKS) { - if (m.toString().equalsIgnoreCase(args[1])) { - material = m; - break; - } - }*/ - if (material == null) { - PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); - return true; - } - byte data = 0; + final Material material = getMaterial(args[1], PlotWorld.BLOCKS); + /* + * for (Material m : PlotWorld.BLOCKS) { + * if (m.toString().equalsIgnoreCase(args[1])) { + * material = m; + * break; + * } + * } + */ + if (material == null) { + PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); + return true; + } + byte data = 0; - if (args.length > 2) { - try { - data = (byte) Integer.parseInt(args[2]); - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); - return true; - } - } - PlayerFunctions.sendMessage(plr, C.GENERATING_WALL); - PlotHelper.adjustWall(plr, plot, new PlotBlock((short) material.getId(), data)); - return true; - } - if (args[0].equalsIgnoreCase("floor")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); - return true; - } - PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return true; - } - // - @SuppressWarnings("unchecked") - ArrayList materials = (ArrayList) PlotWorld.BLOCKS.clone(); - materials.add(Material.AIR); - // - String[] strings = args[1].split(","); - // - int index = 0; - // - byte b = (byte) 0; - Material m = null; - // - PlotBlock[] blocks = new PlotBlock[strings.length]; + if (args.length > 2) { + try { + data = (byte) Integer.parseInt(args[2]); + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); + return true; + } + } + PlayerFunctions.sendMessage(plr, C.GENERATING_WALL); + PlotHelper.adjustWall(plr, plot, new PlotBlock((short) material.getId(), data)); + return true; + } + if (args[0].equalsIgnoreCase("floor")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); + return true; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return true; + } + // + @SuppressWarnings("unchecked") + final ArrayList materials = (ArrayList) PlotWorld.BLOCKS.clone(); + materials.add(Material.AIR); + // + final String[] strings = args[1].split(","); + // + int index = 0; + // + byte b = (byte) 0; + Material m = null; + // + final PlotBlock[] blocks = new PlotBlock[strings.length]; - for (String s : strings) { - s = s.replaceAll(",", ""); - String[] ss = s.split(";"); - ss[0] = ss[0].replaceAll(";", ""); - if(ss[0].length() < 2) { + for (String s : strings) { + s = s.replaceAll(",", ""); + final String[] ss = s.split(";"); + ss[0] = ss[0].replaceAll(";", ""); + if (ss[0].length() < 2) { sendMessage(plr, C.NAME_LITTLE, "Material", ss[0].length() + "", "2"); return true; } m = getMaterial(ss[0], materials); - /*for (Material ma : materials) { - if (ma.toString().equalsIgnoreCase(ss[0])) { - m = ma; - } - }*/ - if (m == null) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK); - return true; - } - if (ss.length == 1) { + /* + * for (Material ma : materials) { + * if (ma.toString().equalsIgnoreCase(ss[0])) { + * m = ma; + * } + * } + */ + if (m == null) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK); + return true; + } + if (ss.length == 1) { - blocks[index] = new PlotBlock((short) m.getId(), (byte) 0); - } - else { - try { - b = (byte) Integer.parseInt(ss[1]); - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); - return true; - } - blocks[index] = new PlotBlock((short) m.getId(), b); - } - index++; - } - PlotHelper.setFloor(plr, plot, blocks); - return true; - } - if (args[0].equalsIgnoreCase("wall_filling")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); - return true; - } - PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return true; - } - if(args[1].length() < 2) { + blocks[index] = new PlotBlock((short) m.getId(), (byte) 0); + } + else { + try { + b = (byte) Integer.parseInt(ss[1]); + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); + return true; + } + blocks[index] = new PlotBlock((short) m.getId(), b); + } + index++; + } + PlotHelper.setFloor(plr, plot, blocks); + return true; + } + if (args[0].equalsIgnoreCase("wall_filling")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); + return true; + } + final PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return true; + } + if (args[1].length() < 2) { sendMessage(plr, C.NAME_LITTLE, "Material", args[1].length() + "", "2"); return true; } - Material material = getMaterial(args[1], PlotWorld.BLOCKS); - /*for (Material m : PlotWorld.BLOCKS) { - if (m.toString().equalsIgnoreCase(args[1])) { - material = m; - break; - } - }*/ + final Material material = getMaterial(args[1], PlotWorld.BLOCKS); + /* + * for (Material m : PlotWorld.BLOCKS) { + * if (m.toString().equalsIgnoreCase(args[1])) { + * material = m; + * break; + * } + * } + */ - if (material == null) { - PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); - return true; - } - byte data = 0; + if (material == null) { + PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); + return true; + } + byte data = 0; - if (args.length > 2) { - try { - data = (byte) Integer.parseInt(args[2]); - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); - return true; - } - } - PlotHelper.adjustWallFilling(plr, plot, new PlotBlock((short) material.getId(), data)); - return true; - } + if (args.length > 2) { + try { + data = (byte) Integer.parseInt(args[2]); + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); + return true; + } + } + PlotHelper.adjustWallFilling(plr, plot, new PlotBlock((short) material.getId(), data)); + return true; + } { AbstractFlag af = new AbstractFlag(""); try { af = new AbstractFlag(args[0].toLowerCase()); } - catch (Exception e) { + catch (final Exception e) { } if (FlagManager.getFlags().contains(af)) { - StringBuilder a = new StringBuilder(); - if(args.length > 1) { - for(int x = 1; x < args.length; x++) + final StringBuilder a = new StringBuilder(); + if (args.length > 1) { + for (int x = 1; x < args.length; x++) { a.append(" ").append(args[x]); + } } plr.performCommand("plot set flag " + args[0] + a.toString()); return true; } } PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(values)); - return false; - } + return false; + } - private String getMaterial(Material m) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", m.toString().toLowerCase())); - } + private String getMaterial(final Material m) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", m.toString().toLowerCase())); + } - private String getBiome(Biome b) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", b.toString().toLowerCase())); - } + private String getBiome(final Biome b) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", b.toString().toLowerCase())); + } - private String getString(String s) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); - } + private String getString(final String s) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); + } - private String getArgumentList(String[] strings) { - StringBuilder builder = new StringBuilder(); - for (String s : strings) { - builder.append(getString(s)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getArgumentList(final String[] strings) { + final StringBuilder builder = new StringBuilder(); + for (final String s : strings) { + builder.append(getString(s)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } - private String getBiomeList(List biomes) { - StringBuilder builder = new StringBuilder(); - builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); - for (Biome b : biomes) { - builder.append(getBiome(b)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getBiomeList(final List biomes) { + final StringBuilder builder = new StringBuilder(); + builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); + for (final Biome b : biomes) { + builder.append(getBiome(b)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } - private Material getMaterial(String input, List blocks) { + private Material getMaterial(final String input, final List blocks) { return Material.valueOf(new StringComparsion(input, blocks.toArray()).getBestMatch()); } - private String getBlockList(List blocks) { - StringBuilder builder = new StringBuilder(); - builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); - for (Material b : blocks) { - builder.append(getMaterial(b)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getBlockList(final List blocks) { + final StringBuilder builder = new StringBuilder(); + builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); + for (final Material b : blocks) { + builder.append(getMaterial(b)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java index 6b08e9f7c..24d7b2850 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SetOwner.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = SetOwner.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ @@ -22,40 +22,40 @@ import com.intellectualcrafters.plot.database.DBFunc; @SuppressWarnings("deprecation") public class SetOwner extends SubCommand { - public SetOwner() { - super("setowner", "plots.admin", "Set the plot owner", "setowner {player}", "so", CommandCategory.ACTIONS, true); - } + public SetOwner() { + super("setowner", "plots.admin", "Set the plot owner", "setowner {player}", "so", CommandCategory.ACTIONS, true); + } - /* - * private UUID getUUID(String string) { OfflinePlayer player = - * Bukkit.getOfflinePlayer(string); return ((player != null) && - * player.hasPlayedBefore()) ? player.getUniqueId() : null; } - */ + /* + * private UUID getUUID(String string) { OfflinePlayer player = + * Bukkit.getOfflinePlayer(string); return ((player != null) && + * player.hasPlayedBefore()) ? player.getUniqueId() : null; } + */ - private UUID getUUID(String string) { - return UUIDHandler.getUUID(string); - } + private UUID getUUID(final String string) { + return UUIDHandler.getUUID(string); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_USER); - return true; - } - plot.owner = getUUID(args[0]); - PlotMain.updatePlot(plot); - DBFunc.setOwner(plot, plot.owner); - PlayerFunctions.sendMessage(plr, C.SET_OWNER); - - if (PlotMain.worldGuardListener!=null) { - PlotMain.worldGuardListener.changeOwner(plr, plot.owner, plr.getWorld(), plot); - } - - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_USER); + return true; + } + plot.owner = getUUID(args[0]); + PlotMain.updatePlot(plot); + DBFunc.setOwner(plot, plot.owner); + PlayerFunctions.sendMessage(plr, C.SET_OWNER); + + if (PlotMain.worldGuardListener != null) { + PlotMain.worldGuardListener.changeOwner(plr, plot.owner, plr.getWorld(), plot); + } + + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Setup.java index 1d6c2efa3..e9150f44f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Setup.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Setup.java @@ -27,203 +27,191 @@ import com.intellectualcrafters.plot.generator.DefaultPlotWorld; */ public class Setup extends SubCommand implements Listener { - public static Map setupMap = new HashMap<>(); + public static Map setupMap = new HashMap<>(); - private class SetupObject { - String world; - String plugin; - int current = 0; + private class SetupObject { + String world; + String plugin; + int current = 0; - ConfigurationNode[] step; + ConfigurationNode[] step; - public SetupObject(String world, PlotWorld plotworld, String plugin) { - this.world = world; - this.step = plotworld.getSettingNodes(); - this.plugin = plugin; - } + public SetupObject(final String world, final PlotWorld plotworld, final String plugin) { + this.world = world; + this.step = plotworld.getSettingNodes(); + this.plugin = plugin; + } - public String getPlugin() { - return this.plugin; - } + public int getCurrent() { + return this.current; + } - public int getCurrent() { - return this.current; - } + public int getMax() { + return this.step.length; + } + } - public int getMax() { - return this.step.length; - } - } + public Setup() { + super("setup", "plots.admin", "Setup a PlotWorld", "setup {world} {generator}", "setup", CommandCategory.ACTIONS, false); + } - public Setup() { - super("setup", "plots.admin", "Setup a PlotWorld", "setup {world} {generator}", "setup", CommandCategory.ACTIONS, false); - } + @Override + public boolean execute(final Player plr, final String... args) { + String plrname; - @Override - public boolean execute(Player plr, String... args) { - String plrname; - - if (plr==null) { - plrname = ""; - } - else { - plrname = plr.getName(); - } - - if (setupMap.containsKey(plrname)) { - SetupObject object = setupMap.get(plrname); - if (object.getCurrent() == object.getMax()) { - ConfigurationNode[] steps = object.step; - String world = object.world; - for (ConfigurationNode step : steps) { - PlotMain.config.set("worlds." + world + "." + step.getConstant(), step.getValue()); - } - try { - PlotMain.config.save(PlotMain.configFile); - } - catch (IOException e) { - e.printStackTrace(); - } + if (plr == null) { + plrname = ""; + } + else { + plrname = plr.getName(); + } - // Creating the worlds - 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.plugin); - } - else { - if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world - + " plugin:" + object.plugin); - } - else { - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - if (plugin.isEnabled()) { - if (plugin.getDefaultWorldGenerator("world", "") != null) { - String name = plugin.getDescription().getName(); - if (object.plugin.equals(name)) { - ChunkGenerator generator = plugin.getDefaultWorldGenerator(world, ""); - World myworld = WorldCreator.name(world).generator(generator).createWorld(); - PlayerFunctions.sendMessage(plr, "&aLoaded world."); - plr.teleport(myworld.getSpawnLocation()); - break; - } - } + if (setupMap.containsKey(plrname)) { + final SetupObject object = setupMap.get(plrname); + if (object.getCurrent() == object.getMax()) { + final ConfigurationNode[] steps = object.step; + final String world = object.world; + for (final ConfigurationNode step : steps) { + PlotMain.config.set("worlds." + world + "." + step.getConstant(), step.getValue()); + } + try { + PlotMain.config.save(PlotMain.configFile); + } + catch (final IOException e) { + e.printStackTrace(); + } - } - } - } - } - sendMessage(plr, C.SETUP_FINISHED, object.world); + // Creating the worlds + 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.plugin); + } + else { + if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.plugin); + } + else { + for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + if (plugin.isEnabled()) { + if (plugin.getDefaultWorldGenerator("world", "") != null) { + final String name = plugin.getDescription().getName(); + if (object.plugin.equals(name)) { + final ChunkGenerator generator = plugin.getDefaultWorldGenerator(world, ""); + final World myworld = WorldCreator.name(world).generator(generator).createWorld(); + PlayerFunctions.sendMessage(plr, "&aLoaded world."); + plr.teleport(myworld.getSpawnLocation()); + break; + } + } - setupMap.remove(plrname); + } + } + } + } + sendMessage(plr, C.SETUP_FINISHED, object.world); - return true; - } - ConfigurationNode step = object.step[object.current]; - if (args.length < 1) { - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() - + ""); - return true; - } - else { - if (args[0].equalsIgnoreCase("cancel")) { - setupMap.remove(plrname); - PlayerFunctions.sendMessage(plr, "&cCancelled setup."); - return true; - } - if (args[0].equalsIgnoreCase("back")) { - if (object.current > 0) { - object.current--; - step = object.step[object.current]; - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() - + ""); - return true; - } - else { - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() - + ""); - return true; - } - } - boolean valid = step.isValid(args[0]); - if (valid) { - sendMessage(plr, C.SETUP_VALID_ARG, step.getConstant(), args[0]); - step.setValue(args[0]); - object.current++; - if (object.getCurrent() == object.getMax()) { - execute(plr, args); - return true; - } - step = object.step[object.current]; - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() - + ""); - return true; - } - else { - sendMessage(plr, C.SETUP_INVALID_ARG, args[0], step.getConstant()); - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() - + ""); - return true; - } - } - } - else { - if (args.length < 1) { - sendMessage(plr, C.SETUP_MISSING_WORLD); - return true; - } - if (args.length < 2) { - sendMessage(plr, C.SETUP_MISSING_GENERATOR); - return true; - } - String world = args[0]; - if (StringUtils.isNumeric(args[0])) { - sendMessage(plr, C.SETUP_WORLD_TAKEN, world); - return true; - } + setupMap.remove(plrname); - if (PlotMain.getWorldSettings(world) != null) { - sendMessage(plr, C.SETUP_WORLD_TAKEN, world); - return true; - } + return true; + } + ConfigurationNode step = object.step[object.current]; + if (args.length < 1) { + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + return true; + } + else { + if (args[0].equalsIgnoreCase("cancel")) { + setupMap.remove(plrname); + PlayerFunctions.sendMessage(plr, "&cCancelled setup."); + return true; + } + if (args[0].equalsIgnoreCase("back")) { + if (object.current > 0) { + object.current--; + step = object.step[object.current]; + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + return true; + } + else { + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + return true; + } + } + final boolean valid = step.isValid(args[0]); + if (valid) { + sendMessage(plr, C.SETUP_VALID_ARG, step.getConstant(), args[0]); + step.setValue(args[0]); + object.current++; + if (object.getCurrent() == object.getMax()) { + execute(plr, args); + return true; + } + step = object.step[object.current]; + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + return true; + } + else { + sendMessage(plr, C.SETUP_INVALID_ARG, args[0], step.getConstant()); + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + return true; + } + } + } + else { + if (args.length < 1) { + sendMessage(plr, C.SETUP_MISSING_WORLD); + return true; + } + if (args.length < 2) { + sendMessage(plr, C.SETUP_MISSING_GENERATOR); + return true; + } + final String world = args[0]; + if (StringUtils.isNumeric(args[0])) { + sendMessage(plr, C.SETUP_WORLD_TAKEN, world); + return true; + } - ArrayList generators = new ArrayList(); + if (PlotMain.getWorldSettings(world) != null) { + sendMessage(plr, C.SETUP_WORLD_TAKEN, world); + return true; + } - ChunkGenerator generator = null; + final ArrayList generators = new ArrayList(); - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - if (plugin.isEnabled()) { - if (plugin.getDefaultWorldGenerator("world", "") != null) { - String name = plugin.getDescription().getName(); - generators.add(name); - if (args[1].equals(name)) { - generator = plugin.getDefaultWorldGenerator(world, ""); - break; - } - } + ChunkGenerator generator = null; - } - } - if (generator == null) { - sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringUtils.join(generators, C.BLOCK_LIST_SEPARATER.s())); - return true; - } - PlotWorld plotworld; - if (generator instanceof PlotGenerator) { - plotworld = ((PlotGenerator) generator).getNewPlotWorld(world); - } - else { - plotworld = new DefaultPlotWorld(world); - } + for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + if (plugin.isEnabled()) { + if (plugin.getDefaultWorldGenerator("world", "") != null) { + final String name = plugin.getDescription().getName(); + generators.add(name); + if (args[1].equals(name)) { + generator = plugin.getDefaultWorldGenerator(world, ""); + break; + } + } - setupMap.put(plrname, new SetupObject(world, plotworld, args[1])); - sendMessage(plr, C.SETUP_INIT); - SetupObject object = setupMap.get(plrname); - ConfigurationNode step = object.step[object.current]; - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() - + ""); - return true; - } - } + } + } + if (generator == null) { + sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringUtils.join(generators, C.BLOCK_LIST_SEPARATER.s())); + return true; + } + PlotWorld plotworld; + if (generator instanceof PlotGenerator) { + plotworld = ((PlotGenerator) generator).getNewPlotWorld(world); + } + else { + plotworld = new DefaultPlotWorld(world); + } + + setupMap.put(plrname, new SetupObject(world, plotworld, args[1])); + sendMessage(plr, C.SETUP_INIT); + final SetupObject object = setupMap.get(plrname); + final ConfigurationNode step = object.step[object.current]; + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType().getType(), step.getDefaultValue() + ""); + return true; + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java index 4d953f694..afd01bd43 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java @@ -2,13 +2,12 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = SubCommand.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ package com.intellectualcrafters.plot.commands; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; @@ -20,117 +19,116 @@ import com.intellectualcrafters.plot.PlayerFunctions; * @author Citymonstret */ public abstract class SubCommand { - public boolean isPlayer; - /** - * Command - */ - public String cmd; - /** - * Permission node - */ - public CommandPermission permission; - /** - * Simple description - */ - public String description; - /** - * Alias - */ - public String alias; + public boolean isPlayer; + /** + * Command + */ + public String cmd; + /** + * Permission node + */ + public CommandPermission permission; + /** + * Simple description + */ + public String description; + /** + * Alias + */ + public String alias; - /** - * Command usage - */ - public String usage; + /** + * Command usage + */ + public String usage; - public CommandCategory category; + public CommandCategory category; - /** - * @param cmd - * Command /plot {cmd} <-- That! - * @param permission - * Permission Node - * @param description - * Simple description - * @param usage - * Usage description: /plot command {args...} - * @param alias - * Command alias - * @param category - * CommandCategory. Pick whichever closests to what you want. - */ - public SubCommand(String cmd, String permission, String description, String usage, String alias, - CommandCategory category, boolean isPlayer) { - this.cmd = cmd; - this.permission = new CommandPermission(permission); - this.description = description; - this.alias = alias; - this.usage = usage; - this.category = category; - this.isPlayer = isPlayer; - } + /** + * @param cmd + * Command /plot {cmd} <-- That! + * @param permission + * Permission Node + * @param description + * Simple description + * @param usage + * Usage description: /plot command {args...} + * @param alias + * Command alias + * @param category + * CommandCategory. Pick whichever closests to what you want. + */ + public SubCommand(final String cmd, final String permission, final String description, final String usage, final String alias, final CommandCategory category, final boolean isPlayer) { + this.cmd = cmd; + this.permission = new CommandPermission(permission); + this.description = description; + this.alias = alias; + this.usage = usage; + this.category = category; + this.isPlayer = isPlayer; + } - /** - * @param command - * Command /plot {cmd} <-- That! - * @param description - * Simple description - * @param usage - * Usage description: /plot command {args...} - * @param category - * CommandCategory. Pick whichever closests to what you want. - */ - public SubCommand(Command command, String description, String usage, CommandCategory category, boolean isPlayer) { - this.cmd = command.getCommand(); - this.permission = command.getPermission(); - this.alias = command.getAlias(); - this.description = description; - this.usage = usage; - this.category = category; - this.isPlayer = isPlayer; - } + /** + * @param command + * Command /plot {cmd} <-- That! + * @param description + * Simple description + * @param usage + * Usage description: /plot command {args...} + * @param category + * CommandCategory. Pick whichever closests to what you want. + */ + public SubCommand(final Command command, final String description, final String usage, final CommandCategory category, final boolean isPlayer) { + this.cmd = command.getCommand(); + this.permission = command.getPermission(); + this.alias = command.getAlias(); + this.description = description; + this.usage = usage; + this.category = category; + this.isPlayer = isPlayer; + } - /** - * Execute. - * - * @param plr - * executor - * @param args - * arguments - * @return true on success, false on failure - */ - public abstract boolean execute(Player plr, String... args); + /** + * Execute. + * + * @param plr + * executor + * @param args + * arguments + * @return true on success, false on failure + */ + public abstract boolean execute(final Player plr, final String... args); - public void executeConsole(String... args) { - this.execute(null, args); - } + public void executeConsole(final String... args) { + this.execute(null, args); + } - /** - * Send a message - * - * @param plr - * @param c - * @param args - */ - public void sendMessage(Player plr, C c, String... args) { - PlayerFunctions.sendMessage(plr, c, args); - } + /** + * Send a message + * + * @param plr + * @param c + * @param args + */ + public void sendMessage(final Player plr, final C c, final String... args) { + PlayerFunctions.sendMessage(plr, c, args); + } - public enum CommandCategory { - CLAIMING("Claiming"), - TELEPORT("Teleportation"), - ACTIONS("Actions"), - INFO("Information"), - DEBUG("Debug"); - private String name; + public enum CommandCategory { + CLAIMING("Claiming"), + TELEPORT("Teleportation"), + ACTIONS("Actions"), + INFO("Information"), + DEBUG("Debug"); + private String name; - CommandCategory(String name) { - this.name = name; - } + CommandCategory(final String name) { + this.name = name; + } - @Override - public String toString() { - return this.name; - } - } + @Override + public String toString() { + return this.name; + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Swap.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Swap.java index 59f563d9c..e8b706cd3 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Swap.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Swap.java @@ -2,75 +2,81 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; - import org.bukkit.World; import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotSelection; +import com.intellectualcrafters.plot.SetBlockFast; + /** * Created by Citymonstret on 2014-08-01. */ public class Swap extends SubCommand { - public Swap() { - super(Command.SWAP, "Swap two plots", "copy", CommandCategory.ACTIONS, true); - } + public Swap() { + super(Command.SWAP, "Swap two plots", "copy", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); - PlayerFunctions.sendMessage(plr, C.SWAP_SYNTAX); + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); + PlayerFunctions.sendMessage(plr, C.SWAP_SYNTAX); return false; } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) - && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (plot!=null && plot.settings.isMerged()) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if ((plot != null) && plot.settings.isMerged()) { PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); return false; } - String id = args[0]; - PlotId plotid; - World world = plr.getWorld(); - try { + final String id = args[0]; + PlotId plotid; + final World world = plr.getWorld(); + try { plotid = new PlotId(Integer.parseInt(id.split(";")[0]), Integer.parseInt(id.split(";")[1])); - Plot plot2 = PlotMain.getPlots(world).get(plotid); - if ((plot2==null || !plot2.hasOwner() || plot2.owner!=plr.getUniqueId()) && !PlotMain.hasPermission(plr,"plots.admin")) { + final Plot plot2 = PlotMain.getPlots(world).get(plotid); + if (((plot2 == null) || !plot2.hasOwner() || (plot2.owner != plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE, plotid.toString()); return false; } } - catch (Exception e) { + catch (final Exception e) { PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); PlayerFunctions.sendMessage(plr, C.SWAP_SYNTAX); return false; } - if (plot.id.equals(plotid)) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); + if (plot.id.equals(plotid)) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); PlayerFunctions.sendMessage(plr, C.SWAP_SYNTAX); return false; - } + } PlotSelection.swap(world, plot.id, plotid); PlayerFunctions.sendMessage(plr, C.SWAP_SUCCESS); - + if (PlotHelper.canSetFast) { SetBlockFast.update(plr); } - - return true; - } + + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java index 64ec17666..0794e2265 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/TP.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = TP.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ @@ -25,68 +25,67 @@ import com.intellectualcrafters.plot.PlotMain; */ public class TP extends SubCommand { - public TP() { - super(Command.TP, "Teleport to a plot", "tp {alias|id}", CommandCategory.TELEPORT, true); - } + public TP() { + super(Command.TP, "Teleport to a plot", "tp {alias|id}", CommandCategory.TELEPORT, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); - return false; - } - String id = args[0]; - PlotId plotid; - World world = plr.getWorld(); - if (args.length == 2) { - if (Bukkit.getWorld(args[1]) != null) { - world = Bukkit.getWorld(args[1]); - } - } - if (!PlotMain.isPlotWorld(world)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return false; - } - Plot temp; - if ((temp = isAlias(world, id)) != null) { - PlotMain.teleportPlayer(plr, plr.getLocation(), temp); - return true; - } + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); + return false; + } + final String id = args[0]; + PlotId plotid; + World world = plr.getWorld(); + if (args.length == 2) { + if (Bukkit.getWorld(args[1]) != null) { + world = Bukkit.getWorld(args[1]); + } + } + if (!PlotMain.isPlotWorld(world)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return false; + } + Plot temp; + if ((temp = isAlias(world, id)) != null) { + PlotMain.teleportPlayer(plr, plr.getLocation(), temp); + return true; + } + try { + plotid = new PlotId(Integer.parseInt(id.split(";")[0]), Integer.parseInt(id.split(";")[1])); + PlotMain.teleportPlayer(plr, plr.getLocation(), PlotHelper.getPlot(world, plotid)); + return true; + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); + } + return false; + } - try { - plotid = new PlotId(Integer.parseInt(id.split(";")[0]), Integer.parseInt(id.split(";")[1])); - PlotMain.teleportPlayer(plr, plr.getLocation(), PlotHelper.getPlot(world, plotid)); - return true; - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); - } - return false; - } - - private Plot isAlias(World world, String a) { - int index = 0; - if (a.contains(";")) { - String[] split = a.split(";"); - if ((split[1].length() > 0) && StringUtils.isNumeric(split[1])) { - index = Integer.parseInt(split[1]); - } - a = split[0]; - } - Player player = Bukkit.getPlayer(a); - if (player != null) { - Plot[] plots = PlotMain.getPlots(world, player).toArray(new Plot[0]); - if (plots.length > index) { - return plots[index]; - } - return null; - } - for (Plot p : PlotMain.getPlots(world).values()) { - if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { - return p; - } - } - return null; - } + private Plot isAlias(final World world, String a) { + int index = 0; + if (a.contains(";")) { + final String[] split = a.split(";"); + if ((split[1].length() > 0) && StringUtils.isNumeric(split[1])) { + index = Integer.parseInt(split[1]); + } + a = split[0]; + } + final Player player = Bukkit.getPlayer(a); + if (player != null) { + final Plot[] plots = PlotMain.getPlots(world, player).toArray(new Plot[0]); + if (plots.length > index) { + return plots[index]; + } + return null; + } + for (final Plot p : PlotMain.getPlots(world).values()) { + if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { + return p; + } + } + return null; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Trusted.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Trusted.java index abf53854a..78fdb203d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Trusted.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Trusted.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Trusted.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -23,35 +23,35 @@ import com.intellectualcrafters.plot.events.PlayerPlotTrustedEvent; @SuppressWarnings("deprecation") public class Trusted extends SubCommand { - public Trusted() { - super(Command.TRUSTED, "Manage trusted users for a plot", "trusted {add|remove} {player}", CommandCategory.ACTIONS, true); - } + public Trusted() { + super(Command.TRUSTED, "Manage trusted users for a plot", "trusted {add|remove} {player}", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot.owner == null) || !plot.hasRights(plr)) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return true; - } - if (args[0].equalsIgnoreCase("add")) { - UUID uuid; - if (args[1].equalsIgnoreCase("*")) { - uuid = DBFunc.everyone; - - } - else { - uuid = UUIDHandler.getUUID(args[1]); - } - if (!plot.trusted.contains(uuid)) { + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot.owner == null) || !plot.hasRights(plr)) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + UUID uuid; + if (args[1].equalsIgnoreCase("*")) { + uuid = DBFunc.everyone; + + } + else { + uuid = UUIDHandler.getUUID(args[1]); + } + if (!plot.trusted.contains(uuid)) { if (plot.owner == uuid) { PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER); return false; @@ -66,7 +66,7 @@ public class Trusted extends SubCommand { } plot.addTrusted(uuid); DBFunc.setTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, true); + final PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, true); Bukkit.getPluginManager().callEvent(event); } else { @@ -75,44 +75,43 @@ public class Trusted extends SubCommand { } PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); return true; - } - else - if (args[0].equalsIgnoreCase("remove")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - if (!plot.trusted.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); - return true; - } - plot.removeTrusted(uuid); - DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); - return true; - } - /* - * if (!hasBeenOnServer(args[1])) { - * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - * return true; } UUID uuid = null; if - * (Bukkit.getPlayer(args[1]) != null) { uuid = - * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = - * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == - * null) { PlayerFunctions.sendMessage(plr, - * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if - * (!plot.trusted.contains(uuid)) { - * PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); return - * true; } - */ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.removeTrusted(uuid); - DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, false); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); - } - else { - PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); - return true; - } - return true; - } + } + else if (args[0].equalsIgnoreCase("remove")) { + if (args[1].equalsIgnoreCase("*")) { + final UUID uuid = DBFunc.everyone; + if (!plot.trusted.contains(uuid)) { + PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); + return true; + } + plot.removeTrusted(uuid); + DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { + * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); + * return true; } UUID uuid = null; if + * (Bukkit.getPlayer(args[1]) != null) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if + * (!plot.trusted.contains(uuid)) { + * PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); return + * true; } + */ + final UUID uuid = UUIDHandler.getUUID(args[1]); + plot.removeTrusted(uuid); + DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); + final PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, false); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); + } + else { + PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); + return true; + } + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java index fa7831265..c1da665cd 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Unlink.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ @@ -31,92 +31,91 @@ import com.intellectualcrafters.plot.events.PlotUnlinkEvent; */ public class Unlink extends SubCommand { - public Unlink() { - super(Command.UNLINK, "Unlink a mega-plot", "unlink", CommandCategory.ACTIONS, true); - } + public Unlink() { + super(Command.UNLINK, "Unlink a mega-plot", "unlink", CommandCategory.ACTIONS, true); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) - && !PlotMain.hasPermission(plr,"plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return true; - } - if (PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { - PlayerFunctions.sendMessage(plr, C.UNLINK_IMPOSSIBLE); - return true; - } - World world = plr.getWorld(); - PlotId pos1 = PlayerFunctions.getBottomPlot(world, plot).id; - PlotId pos2 = PlayerFunctions.getTopPlot(world, plot).id; - ArrayList ids = PlayerFunctions.getPlotSelectionIds(world, pos1, pos2); + @Override + public boolean execute(final Player plr, final String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return true; + } + final Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return true; + } + if (PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { + PlayerFunctions.sendMessage(plr, C.UNLINK_IMPOSSIBLE); + return true; + } + final World world = plr.getWorld(); + final PlotId pos1 = PlayerFunctions.getBottomPlot(world, plot).id; + final PlotId pos2 = PlayerFunctions.getTopPlot(world, plot).id; + final ArrayList ids = PlayerFunctions.getPlotSelectionIds(world, pos1, pos2); - PlotUnlinkEvent event = new PlotUnlinkEvent(world, ids); + final PlotUnlinkEvent event = new PlotUnlinkEvent(world, ids); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - PlayerFunctions.sendMessage(plr, "&cUnlink has been cancelled"); - return false; - } + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + PlayerFunctions.sendMessage(plr, "&cUnlink has been cancelled"); + return false; + } - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - manager.startPlotUnlink(world, plotworld, ids); - - for (PlotId id : ids) { - Plot myplot = PlotMain.getPlots(world).get(id); + final PlotManager manager = PlotMain.getPlotManager(world); + final PlotWorld plotworld = PlotMain.getWorldSettings(world); - if (plot.helpers != null) { - myplot.helpers = plot.helpers; - } - if (plot.denied != null) { - myplot.denied = plot.denied; - } - myplot.deny_entry = plot.deny_entry; - myplot.settings.setMerged(new boolean[] { false, false, false, false }); - DBFunc.setMerged(world.getName(), myplot, myplot.settings.getMerged()); - } - - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - boolean lx = x < pos2.x; - boolean ly = y < pos2.y; + manager.startPlotUnlink(world, plotworld, ids); - Plot p = PlotHelper.getPlot(world, new PlotId(x, y)); + for (final PlotId id : ids) { + final Plot myplot = PlotMain.getPlots(world).get(id); - if (lx) { - manager.createRoadEast(plotworld, p); - if (ly) { - manager.createRoadSouthEast(plotworld, p); - } + if (plot.helpers != null) { + myplot.helpers = plot.helpers; + } + if (plot.denied != null) { + myplot.denied = plot.denied; + } + myplot.deny_entry = plot.deny_entry; + myplot.settings.setMerged(new boolean[] { false, false, false, false }); + DBFunc.setMerged(world.getName(), myplot, myplot.settings.getMerged()); + } - } + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { + final boolean lx = x < pos2.x; + final boolean ly = y < pos2.y; - if (ly) { - manager.createRoadSouth(plotworld, p); - } + final Plot p = PlotHelper.getPlot(world, new PlotId(x, y)); - } - } - try { - if (PlotHelper.canSetFast) { - SetBlockFast.update(plr); - } - } - catch (Exception e) { + if (lx) { + manager.createRoadEast(plotworld, p); + if (ly) { + manager.createRoadSouthEast(plotworld, p); + } - } - - manager.finishPlotUnlink(world, plotworld, ids); + } - PlayerFunctions.sendMessage(plr, "&6Plots unlinked successfully!"); - return true; - } + if (ly) { + manager.createRoadSouth(plotworld, p); + } + + } + } + try { + if (PlotHelper.canSetFast) { + SetBlockFast.update(plr); + } + } + catch (final Exception e) { + + } + + manager.finishPlotUnlink(world, plotworld, ids); + + PlayerFunctions.sendMessage(plr, "&6Plots unlinked successfully!"); + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Visit.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Visit.java index 54d1f495c..b49b27288 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Visit.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/Visit.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = Visit.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ @@ -12,7 +12,6 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; @@ -22,57 +21,57 @@ import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.UUIDHandler; public class Visit extends SubCommand { - public Visit() { - super("visit", "plots.visit", "Visit someones plot", "visit {player} [#]", "v", CommandCategory.TELEPORT, true); - } + public Visit() { + super("visit", "plots.visit", "Visit someones plot", "visit {player} [#]", "v", CommandCategory.TELEPORT, true); + } - public List getPlots(UUID uuid) { - List plots = new ArrayList<>(); - for (Plot p : PlotMain.getPlots()) { - if (p.owner.equals(uuid)) { - plots.add(p); - } - } - return plots; - } + public List getPlots(final UUID uuid) { + final List plots = new ArrayList<>(); + for (final Plot p : PlotMain.getPlots()) { + if (p.owner.equals(uuid)) { + plots.add(p); + } + } + return plots; + } - @SuppressWarnings("deprecation") - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_USER); - return true; - } - String username = args[0]; - - UUID uuid = UUIDHandler.getUUID(username); - List plots = null; - if (uuid!=null) { - plots = getPlots(uuid); - } - if (uuid==null || plots.isEmpty()) { - PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS); - return true; - } - if (args.length < 2) { - Plot plot = plots.get(0); - PlotMain.teleportPlayer(plr, plr.getLocation(), plot); - return true; - } - int i; - try { - i = Integer.parseInt(args[1]); - } - catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return true; - } - if ((i < 0) || (i >= plots.size())) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return true; - } - Plot plot = plots.get(i); - PlotMain.teleportPlayer(plr, plr.getLocation(), plot); - return true; - } + @SuppressWarnings("deprecation") + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_USER); + return true; + } + final String username = args[0]; + + final UUID uuid = UUIDHandler.getUUID(username); + List plots = null; + if (uuid != null) { + plots = getPlots(uuid); + } + if ((uuid == null) || plots.isEmpty()) { + PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS); + return true; + } + if (args.length < 2) { + final Plot plot = plots.get(0); + PlotMain.teleportPlayer(plr, plr.getLocation(), plot); + return true; + } + int i; + try { + i = Integer.parseInt(args[1]); + } + catch (final Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return true; + } + if ((i < 0) || (i >= plots.size())) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return true; + } + final Plot plot = plots.get(i); + PlotMain.teleportPlayer(plr, plr.getLocation(), plot); + return true; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/list.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/list.java index 5d0aaf139..7f5e79ce5 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/list.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/list.java @@ -2,159 +2,165 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = list.java >> Generated by: Citymonstret at 2014-08-09 01:41 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; +import java.util.HashMap; +import java.util.UUID; + import org.bukkit.ChatColor; import org.bukkit.entity.Player; -import java.util.HashMap; -import java.util.UUID; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.StringComparsion; +import com.intellectualcrafters.plot.UUIDHandler; /** * @author Citymonstret */ public class list extends SubCommand { - public list() { - super(Command.LIST, "List all plots", "list {mine|shared|all|world}", CommandCategory.INFO, false); - } + public list() { + super(Command.LIST, "List all plots", "list {mine|shared|all|world}", CommandCategory.INFO, false); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - StringBuilder builder = new StringBuilder(); - builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); - if (plr!=null) { - builder.append(getArgumentList(new String[] { "mine", "shared", "world", "all" })); - } - else { - builder.append(getArgumentList(new String[] { "all" })); - } - PlayerFunctions.sendMessage(plr, builder.toString()); - return true; - } - if (args[0].equalsIgnoreCase("mine") && plr!=null) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + "\n"); - int idx = 0; - for (Plot p : PlotMain.getPlots(plr)) { + @Override + public boolean execute(final Player plr, final String... args) { + if (args.length < 1) { + final StringBuilder builder = new StringBuilder(); + builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); + if (plr != null) { + builder.append(getArgumentList(new String[] { "mine", "shared", "world", "all" })); + } + else { + builder.append(getArgumentList(new String[] { "all" })); + } + PlayerFunctions.sendMessage(plr, builder.toString()); + return true; + } + if (args[0].equalsIgnoreCase("mine") && (plr != null)) { + final StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + "\n"); + int idx = 0; + for (final Plot p : PlotMain.getPlots(plr)) { string.append(C.PLOT_LIST_ITEM_ORDERED.s().replaceAll("%in", idx + 1 + "").replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); - idx++; - } - if (idx == 0) { - PlayerFunctions.sendMessage(plr, C.NO_PLOTS); - return true; - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "You have").replaceAll("%num%", idx + "").replaceAll("%plot%", idx == 1 - ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } - else - if (args[0].equalsIgnoreCase("shared") && plr!=null) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); - for (Plot p : PlotMain.getPlotsSorted()) { - if (p.helpers.contains(plr.getUniqueId())) { - string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); - } - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There are").replaceAll("%num%", PlotMain.getPlotsSorted().size() - + "").replaceAll("%plot%", PlotMain.getPlotsSorted().size() == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } - else - if (args[0].equalsIgnoreCase("all")) { - // Current page - int page = 0; + idx++; + } + if (idx == 0) { + PlayerFunctions.sendMessage(plr, C.NO_PLOTS); + return true; + } + string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "You have").replaceAll("%num%", idx + "").replaceAll("%plot%", idx == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } + else if (args[0].equalsIgnoreCase("shared") && (plr != null)) { + final StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); + for (final Plot p : PlotMain.getPlotsSorted()) { + if (p.helpers.contains(plr.getUniqueId())) { + string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); + } + } + string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There are").replaceAll("%num%", PlotMain.getPlotsSorted().size() + "").replaceAll("%plot%", PlotMain.getPlotsSorted().size() == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } + else if (args[0].equalsIgnoreCase("all")) { + // Current page + int page = 0; - //is a page specified? else use 0 - if(args.length > 1) { - try { - page = Integer.parseInt(args[1]); - --page; - if(page < 0) page = 0; - } catch(Exception e) { - page = 0; - } + // is a page specified? else use 0 + if (args.length > 1) { + try { + page = Integer.parseInt(args[1]); + --page; + if (page < 0) { + page = 0; } + } + catch (final Exception e) { + page = 0; + } + } - //Get the total pages - //int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size()) / 100)); - int totalPages = (int) Math.ceil(PlotMain.getPlotsSorted().size() / 12); + // Get the total pages + // int totalPages = ((int) Math.ceil(12 * + // (PlotMain.getPlotsSorted().size()) / 100)); + final int totalPages = (int) Math.ceil(PlotMain.getPlotsSorted().size() / 12); - if(page > totalPages) - page = totalPages; + if (page > totalPages) { + page = totalPages; + } - //Only display 12! - int max = (page * 12) + 12; + // Only display 12! + int max = (page * 12) + 12; - if(max > PlotMain.getPlotsSorted().size()) - max = PlotMain.getPlotsSorted().size(); + if (max > PlotMain.getPlotsSorted().size()) { + max = PlotMain.getPlotsSorted().size(); + } - StringBuilder string = new StringBuilder(); + final StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") + "\n"); - Plot p; + string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") + "\n"); + Plot p; - //This might work xD - for (int x = (page * 12); x < max; x++) { - p = (Plot) PlotMain.getPlotsSorted().toArray()[x]; - string.append(C.PLOT_LIST_ITEM_ORDERED.s().replaceAll("%in", x + 1 + "").replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); - } + // This might work xD + for (int x = (page * 12); x < max; x++) { + p = (Plot) PlotMain.getPlotsSorted().toArray()[x]; + string.append(C.PLOT_LIST_ITEM_ORDERED.s().replaceAll("%in", x + 1 + "").replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); + } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", PlotMain.getPlotsSorted().size() - + "").replaceAll("%plot%", PlotMain.getPlotsSorted().size() == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } - else - if (args[0].equalsIgnoreCase("world") && plr!=null) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); - HashMap plots = PlotMain.getPlots(plr.getWorld()); - for (Plot p : plots.values()) { - string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", plots.values().size() - + "").replaceAll("%plot%", plots.values().size() == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } - else { - //execute(plr); - sendMessage(plr, C.DID_YOU_MEAN, new StringComparsion(args[0], new String[] { "mine", "shared", "world", "all" }).getBestMatch()); - return false; - } - } + string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", PlotMain.getPlotsSorted().size() + "").replaceAll("%plot%", PlotMain.getPlotsSorted().size() == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } + else if (args[0].equalsIgnoreCase("world") && (plr != null)) { + final StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); + final HashMap plots = PlotMain.getPlots(plr.getWorld()); + for (final Plot p : plots.values()) { + string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id", p.id.toString()).replaceAll("%world", p.world).replaceAll("%owner", getName(p.owner))).append("\n"); + } + string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", plots.values().size() + "").replaceAll("%plot%", plots.values().size() == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } + else { + // execute(plr); + sendMessage(plr, C.DID_YOU_MEAN, new StringComparsion(args[0], new String[] { "mine", "shared", "world", "all" }).getBestMatch()); + return false; + } + } - private static String getName(UUID id) { - if (id == null) { - return "none"; - } - /* - * String name = Bukkit.getOfflinePlayer(id).getName(); if (name == - * null) { return "none"; } return name; - */ - return UUIDHandler.getName(id); - } + private static String getName(final UUID id) { + if (id == null) { + return "none"; + } + /* + * String name = Bukkit.getOfflinePlayer(id).getName(); if (name == + * null) { return "none"; } return name; + */ + return UUIDHandler.getName(id); + } - private String getArgumentList(String[] strings) { - StringBuilder builder = new StringBuilder(); - for (String s : strings) { - builder.append(getString(s)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getArgumentList(final String[] strings) { + final StringBuilder builder = new StringBuilder(); + for (final String s : strings) { + builder.append(getString(s)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } - private String getString(String s) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); - } + private String getString(final String s) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/plugin.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/plugin.java index ea3006116..2719472a5 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/plugin.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/commands/plugin.java @@ -2,43 +2,41 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = plugin.java >> Generated by: Citymonstret at 2014-08-09 01:42 */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.PlotMain; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.PlotMain; + public class plugin extends SubCommand { - public plugin() { - super("plugin", "plots.use", "Show plugin information", "plugin", "pl", CommandCategory.INFO, false); - } + public plugin() { + super("plugin", "plots.use", "Show plugin information", "plugin", "pl", CommandCategory.INFO, false); + } - public static String - downloads, - version; + public static String downloads, version; - - public static void setup(JavaPlugin plugin) { + public static void setup(final JavaPlugin plugin) { plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() { @Override public void run() { try { - downloads = - convertToNumericString(getInfo("https://intellectualsites.com/spigot_api.php?method=downloads&url=http://www.spigotmc.org/resources/plotsquared.1177/"), false); - } catch (Exception e) { + downloads = convertToNumericString(getInfo("https://intellectualsites.com/spigot_api.php?method=downloads&url=http://www.spigotmc.org/resources/plotsquared.1177/"), false); + } + catch (final Exception e) { downloads = "unknown"; } } @@ -47,10 +45,10 @@ public class plugin extends SubCommand { @Override public void run() { try { - version = - convertToNumericString(getInfo("https://intellectualsites.com/spigot_api.php?method=version&resource=1177"), true); - } catch(Exception e) { - //Let's just ignore this, most likely error 500... + version = convertToNumericString(getInfo("https://intellectualsites.com/spigot_api.php?method=version&resource=1177"), true); + } + catch (final Exception e) { + // Let's just ignore this, most likely error 500... version = "unknown"; } } @@ -58,52 +56,54 @@ public class plugin extends SubCommand { } @Override - public boolean execute(final Player plr, String... args) { - Bukkit.getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(PlotMain.class), new Runnable() { - @Override - public void run() { - ArrayList strings = new ArrayList() { - { - add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion())); - add(String.format("&c>> &6Made by Citymonstret and Empire92")); - add(String.format("&c>> &6Download at &lhttp://i-s.link/ps")); - add(String.format("&c>> &cNewest Version (Spigot): %s", version)); - add(String.format("&c>> &cTotal Downloads (Spigot): %s", downloads)); - } - }; - for (String s : strings) { - PlayerFunctions.sendMessage(plr, s); - } - } - }); - return true; - } + public boolean execute(final Player plr, final String... args) { + Bukkit.getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(PlotMain.class), new Runnable() { + @Override + public void run() { + final ArrayList strings = new ArrayList() { + { + add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion())); + add(String.format("&c>> &6Made by Citymonstret and Empire92")); + add(String.format("&c>> &6Download at &lhttp://i-s.link/ps")); + add(String.format("&c>> &cNewest Version (Spigot): %s", version)); + add(String.format("&c>> &cTotal Downloads (Spigot): %s", downloads)); + } + }; + for (final String s : strings) { + PlayerFunctions.sendMessage(plr, s); + } + } + }); + return true; + } - private static String convertToNumericString(String str, boolean dividers) { - StringBuilder builder = new StringBuilder(); - for(char c : str.toCharArray()) { - if(Character.isDigit(c)) + private static String convertToNumericString(final String str, final boolean dividers) { + final StringBuilder builder = new StringBuilder(); + for (final char c : str.toCharArray()) { + if (Character.isDigit(c)) { builder.append(c); - else if(dividers && (c == ',' || c == '.' || c == '-' || c == '_')) + } + else if (dividers && ((c == ',') || (c == '.') || (c == '-') || (c == '_'))) { builder.append(c); + } } return builder.toString(); } - /** - * @param link - * @return - */ - private static String getInfo(String link) throws Exception { - URLConnection connection = new URL(link).openConnection(); + /** + * @param link + * @return + */ + private static String getInfo(final String link) throws Exception { + final URLConnection connection = new URL(link).openConnection(); connection.addRequestProperty("User-Agent", "Mozilla/4.0"); - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String document = "", line; while ((line = reader.readLine()) != null) { document += (line + "\n"); } reader.close(); return document; - } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java index 70d6a7154..edbd6e09f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java @@ -2,24 +2,25 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = DBFunc.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot.database; -import com.intellectualcrafters.plot.Flag; -import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotComment; -import com.intellectualcrafters.plot.PlotId; -import org.bukkit.OfflinePlayer; - import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.UUID; +import org.bukkit.OfflinePlayer; + +import com.intellectualcrafters.plot.Flag; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotComment; +import com.intellectualcrafters.plot.PlotId; + /** * @author Citymonstret */ @@ -29,58 +30,57 @@ public abstract class AbstractDB { /** * Set Plot owner - * + * * @param plot * @param uuid */ public abstract void setOwner(final Plot plot, final UUID uuid); - public abstract void createAllSettingsAndHelpers(ArrayList plots); + public abstract void createAllSettingsAndHelpers(final ArrayList plots); /** * Create a plot - * + * * @param plots */ - public abstract void createPlots(ArrayList plots); + public abstract void createPlots(final ArrayList plots); /** * Create a plot - * + * * @param plot */ - public abstract void createPlot(Plot plot); + public abstract void createPlot(final Plot plot); /** * Create tables - * + * * @throws SQLException */ - public abstract void createTables(String database, boolean add_constraint) throws Exception; + public abstract void createTables(final String database, final boolean add_constraint) throws Exception; /** * Delete a plot - * + * * @param plot */ public abstract void delete(final String world, final Plot plot); /** * Create plot settings - * + * * @param id * @param plot */ public abstract void createPlotSettings(final int id, final Plot plot); - public abstract int getId(String world, PlotId id2); + public abstract int getId(final String world, final PlotId id2); /** * @return */ public abstract LinkedHashMap> getPlots(); - public abstract void setMerged(final String world, final Plot plot, final boolean[] merged); public abstract void setFlags(final String world, final Plot plot, final Flag[] flags); @@ -94,7 +94,7 @@ public abstract class AbstractDB { public abstract void purge(final String world, final PlotId id); public abstract void purge(final String world); - + /** * @param plot * @param position @@ -105,14 +105,13 @@ public abstract class AbstractDB { * @param id * @return */ - public abstract HashMap getSettings(int id); + public abstract HashMap getSettings(final int id); /** * */ public UUID everyone = UUID.fromString("1-1-3-3-7"); - /** * @param plot * @param player @@ -151,9 +150,9 @@ public abstract class AbstractDB { public abstract double getRatings(final Plot plot); - public abstract void removeComment(String world, Plot plot, PlotComment comment); + public abstract void removeComment(final String world, final Plot plot, final PlotComment comment); - public abstract void setComment(String world, Plot plot, PlotComment comment); + public abstract void setComment(final String world, final Plot plot, final PlotComment comment); - public abstract ArrayList getComments(String world, Plot plot, int tier); + public abstract ArrayList getComments(final String world, final Plot plot, final int tier); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java index f25a333bf..8c71f812a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java @@ -2,173 +2,174 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = DBFunc.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot.database; -import com.intellectualcrafters.plot.Flag; -import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotComment; -import com.intellectualcrafters.plot.PlotId; -import org.bukkit.OfflinePlayer; - import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.UUID; +import org.bukkit.OfflinePlayer; + +import com.intellectualcrafters.plot.Flag; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotComment; +import com.intellectualcrafters.plot.PlotId; + /** * @author Citymonstret */ public class DBFunc { - + public static AbstractDB dbManager; - - // TODO MongoDB @Brandon - /** - * Set Plot owner - * - * @param plot - * @param uuid - */ - public static void setOwner(final Plot plot, final UUID uuid) { - dbManager.setOwner(plot, uuid); - } + // TODO MongoDB @Brandon - public static void createAllSettingsAndHelpers(ArrayList plots) { - dbManager.createAllSettingsAndHelpers(plots); - } + /** + * Set Plot owner + * + * @param plot + * @param uuid + */ + public static void setOwner(final Plot plot, final UUID uuid) { + dbManager.setOwner(plot, uuid); + } - /** - * Create a plot - * - * @param plots - */ - public static void createPlots(ArrayList plots) { - dbManager.createPlots(plots); - } + public static void createAllSettingsAndHelpers(final ArrayList plots) { + dbManager.createAllSettingsAndHelpers(plots); + } - /** - * Create a plot - * - * @param plot - */ - public static void createPlot(Plot plot) { - dbManager.createPlot(plot); - } + /** + * Create a plot + * + * @param plots + */ + public static void createPlots(final ArrayList plots) { + dbManager.createPlots(plots); + } - /** - * Create tables - * @throws Exception - */ - public static void createTables(String database, boolean add_constraint) throws Exception { - dbManager.createTables(database, add_constraint); - } + /** + * Create a plot + * + * @param plot + */ + public static void createPlot(final Plot plot) { + dbManager.createPlot(plot); + } - /** - * Delete a plot - * - * @param plot - */ - public static void delete(final String world, final Plot plot) { - dbManager.delete(world, plot); - } + /** + * Create tables + * + * @throws Exception + */ + public static void createTables(final String database, final boolean add_constraint) throws Exception { + dbManager.createTables(database, add_constraint); + } - /** - * Create plot settings - * - * @param id - * @param plot - */ - public static void createPlotSettings(final int id, final Plot plot) { - dbManager.createPlotSettings(id, plot); - } + /** + * Delete a plot + * + * @param plot + */ + public static void delete(final String world, final Plot plot) { + dbManager.delete(world, plot); + } - public static int getId(String world, PlotId id2) { - return dbManager.getId(world, id2); - } + /** + * Create plot settings + * + * @param id + * @param plot + */ + public static void createPlotSettings(final int id, final Plot plot) { + dbManager.createPlotSettings(id, plot); + } - /** - * Get a plot id - * - * @param plot_id - * @return - */ - /* - * public static int getId(String world, PlotId id2) { Statement stmt = - * null; try { stmt = connection.createStatement(); ResultSet r = - * stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x - * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + - * "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE; - * while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; } - * catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE; - * } - */ + public static int getId(final String world, final PlotId id2) { + return dbManager.getId(world, id2); + } - /** - * @return - */ - public static LinkedHashMap> getPlots() { - return dbManager.getPlots(); - } + /** + * Get a plot id + * + * @param plot_id + * @return + */ + /* + * public static int getId(String world, PlotId id2) { Statement stmt = + * null; try { stmt = connection.createStatement(); ResultSet r = + * stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x + * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + + * "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE; + * while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; } + * catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE; + * } + */ + /** + * @return + */ + public static LinkedHashMap> getPlots() { + return dbManager.getPlots(); + } - public static void setMerged(final String world, final Plot plot, final boolean[] merged) { - dbManager.setMerged(world, plot, merged); - } + public static void setMerged(final String world, final Plot plot, final boolean[] merged) { + dbManager.setMerged(world, plot, merged); + } - public static void setFlags(final String world, final Plot plot, final Flag[] flags) { - dbManager.setFlags(world, plot, flags); - } + public static void setFlags(final String world, final Plot plot, final Flag[] flags) { + dbManager.setFlags(world, plot, flags); + } - /** - * @param plot - * @param alias - */ - public static void setAlias(final String world, final Plot plot, final String alias) { - dbManager.setAlias(world, plot, alias); - } + /** + * @param plot + * @param alias + */ + public static void setAlias(final String world, final Plot plot, final String alias) { + dbManager.setAlias(world, plot, alias); + } - public static void purge(final String world, final PlotId id) { - dbManager.purge(world, id); - } + public static void purge(final String world, final PlotId id) { + dbManager.purge(world, id); + } - public static void purge(final String world) { - dbManager.purge(world); - } - - /** - * @param plot - * @param position - */ - public static void setPosition(final String world, final Plot plot, final String position) { - dbManager.setPosition(world, plot, position); - } + public static void purge(final String world) { + dbManager.purge(world); + } - /** - * @param id - * @return - */ - public static HashMap getSettings(int id) { - return dbManager.getSettings(id); - } + /** + * @param plot + * @param position + */ + public static void setPosition(final String world, final Plot plot, final String position) { + dbManager.setPosition(world, plot, position); + } - /** - * - */ - public static UUID everyone = UUID.fromString("1-1-3-3-7"); + /** + * @param id + * @return + */ + public static HashMap getSettings(final int id) { + return dbManager.getSettings(id); + } - /** + /** + * + */ + public static UUID everyone = UUID.fromString("1-1-3-3-7"); + + /** * @param plot * @param comment */ public static void removeComment(final String world, final Plot plot, final PlotComment comment) { dbManager.removeComment(world, plot, comment); } - + /** * @param plot * @param comment @@ -176,7 +177,7 @@ public class DBFunc { public static void setComment(final String world, final Plot plot, final PlotComment comment) { dbManager.setComment(world, plot, comment); } - + /** * @param plot * @param comment @@ -184,56 +185,56 @@ public class DBFunc { public static ArrayList getCommenst(final String world, final Plot plot, final int tier) { return dbManager.getComments(world, plot, tier); } - - /** - * @param plot - * @param player - */ - public static void removeHelper(final String world, final Plot plot, final OfflinePlayer player) { - dbManager.removeHelper(world, plot, player); - } - /** - * @param plot - * @param player - */ - public static void removeTrusted(final String world, final Plot plot, final OfflinePlayer player) { - dbManager.removeTrusted(world, plot, player); - } + /** + * @param plot + * @param player + */ + public static void removeHelper(final String world, final Plot plot, final OfflinePlayer player) { + dbManager.removeHelper(world, plot, player); + } - /** - * @param plot - * @param player - */ - public static void setHelper(final String world, final Plot plot, final OfflinePlayer player) { - dbManager.setHelper(world, plot, player); - } + /** + * @param plot + * @param player + */ + public static void removeTrusted(final String world, final Plot plot, final OfflinePlayer player) { + dbManager.removeTrusted(world, plot, player); + } - /** - * @param plot - * @param player - */ - public static void setTrusted(final String world, final Plot plot, final OfflinePlayer player) { - dbManager.setTrusted(world, plot, player); - } + /** + * @param plot + * @param player + */ + public static void setHelper(final String world, final Plot plot, final OfflinePlayer player) { + dbManager.setHelper(world, plot, player); + } - /** - * @param plot - * @param player - */ - public static void removeDenied(final String world, final Plot plot, final OfflinePlayer player) { - dbManager.removeDenied(world, plot, player); - } + /** + * @param plot + * @param player + */ + public static void setTrusted(final String world, final Plot plot, final OfflinePlayer player) { + dbManager.setTrusted(world, plot, player); + } - /** - * @param plot - * @param player - */ - public static void setDenied(final String world, final Plot plot, final OfflinePlayer player) { - dbManager.setDenied(world, plot, player); - } + /** + * @param plot + * @param player + */ + public static void removeDenied(final String world, final Plot plot, final OfflinePlayer player) { + dbManager.removeDenied(world, plot, player); + } - public static double getRatings(final Plot plot) { - return dbManager.getRatings(plot); - } + /** + * @param plot + * @param player + */ + public static void setDenied(final String world, final Plot plot, final OfflinePlayer player) { + dbManager.setDenied(world, plot, player); + } + + public static double getRatings(final Plot plot) { + return dbManager.getRatings(plot); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/Database.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/Database.java index 206ac256e..482974faf 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/Database.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/Database.java @@ -15,83 +15,83 @@ import org.bukkit.plugin.Plugin; */ public abstract class Database { - /** - * Plugin instance, use for plugin.getDataFolder() - */ - protected Plugin plugin; + /** + * Plugin instance, use for plugin.getDataFolder() + */ + protected Plugin plugin; - /** - * Creates a new Database - * - * @param plugin - * Plugin instance - */ - protected Database(Plugin plugin) { - this.plugin = plugin; - } + /** + * Creates a new Database + * + * @param plugin + * Plugin instance + */ + protected Database(final Plugin plugin) { + this.plugin = plugin; + } - /** - * Opens a connection with the database - * - * @return Opened connection - * @throws SQLException - * if the connection can not be opened - * @throws ClassNotFoundException - * if the driver cannot be found - */ - public abstract Connection openConnection() throws SQLException, ClassNotFoundException; + /** + * Opens a connection with the database + * + * @return Opened connection + * @throws SQLException + * if the connection can not be opened + * @throws ClassNotFoundException + * if the driver cannot be found + */ + public abstract Connection openConnection() throws SQLException, ClassNotFoundException; - /** - * Checks if a connection is open with the database - * - * @return true if the connection is open - * @throws SQLException - * if the connection cannot be checked - */ - public abstract boolean checkConnection() throws SQLException; + /** + * Checks if a connection is open with the database + * + * @return true if the connection is open + * @throws SQLException + * if the connection cannot be checked + */ + public abstract boolean checkConnection() throws SQLException; - /** - * Gets the connection with the database - * - * @return Connection with the database, null if none - */ - public abstract Connection getConnection(); + /** + * Gets the connection with the database + * + * @return Connection with the database, null if none + */ + public abstract Connection getConnection(); - /** - * Closes the connection with the database - * - * @return true if successful - * @throws SQLException - * if the connection cannot be closed - */ - public abstract boolean closeConnection() throws SQLException; + /** + * Closes the connection with the database + * + * @return true if successful + * @throws SQLException + * if the connection cannot be closed + */ + public abstract boolean closeConnection() throws SQLException; - /** - * Executes a SQL Query
    - * If the connection is closed, it will be opened - * - * @param query - * Query to be run - * @return the results of the query - * @throws SQLException - * If the query cannot be executed - * @throws ClassNotFoundException - * If the driver cannot be found; see {@link #openConnection()} - */ - public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; + /** + * Executes a SQL Query
    + * If the connection is closed, it will be opened + * + * @param query + * Query to be run + * @return the results of the query + * @throws SQLException + * If the query cannot be executed + * @throws ClassNotFoundException + * If the driver cannot be found; see {@link #openConnection()} + */ + public abstract ResultSet querySQL(final String query) throws SQLException, ClassNotFoundException; - /** - * Executes an Update SQL Query
    - * See {@link java.sql.Statement#executeUpdate(String)}
    - * If the connection is closed, it will be opened - * - * @param query - * Query to be run - * @return Result Code, see {@link java.sql.Statement#executeUpdate(String)} - * @throws SQLException - * If the query cannot be executed - * @throws ClassNotFoundException - * If the driver cannot be found; see {@link #openConnection()} - */ - public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException; + /** + * Executes an Update SQL Query
    + * See {@link java.sql.Statement#executeUpdate(String)}
    + * If the connection is closed, it will be opened + * + * @param query + * Query to be run + * @return Result Code, see {@link java.sql.Statement#executeUpdate(String)} + * @throws SQLException + * If the query cannot be executed + * @throws ClassNotFoundException + * If the driver cannot be found; see {@link #openConnection()} + */ + public abstract int updateSQL(final String query) throws SQLException, ClassNotFoundException; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/MySQL.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/MySQL.java index 9393b6cfd..1baee3e3a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/MySQL.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/MySQL.java @@ -15,94 +15,93 @@ import org.bukkit.plugin.Plugin; * @author tips48 */ public class MySQL extends Database { - private final String user; - private final String database; - private final String password; - private final String port; - private final String hostname; + private final String user; + private final String database; + private final String password; + private final String port; + private final String hostname; - private Connection connection; + private Connection connection; - /** - * Creates a new MySQL instance - * - * @param plugin - * Plugin instance - * @param hostname - * Name of the host - * @param port - * Port number - * @param database - * Database name - * @param username - * Username - * @param password - * Password - */ - public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { - super(plugin); - this.hostname = hostname; - this.port = port; - this.database = database; - this.user = username; - this.password = password; - this.connection = null; - } + /** + * Creates a new MySQL instance + * + * @param plugin + * Plugin instance + * @param hostname + * Name of the host + * @param port + * Port number + * @param database + * Database name + * @param username + * Username + * @param password + * Password + */ + public MySQL(final Plugin plugin, final String hostname, final String port, final String database, final String username, final String password) { + super(plugin); + this.hostname = hostname; + this.port = port; + this.database = database; + this.user = username; + this.password = password; + this.connection = null; + } - @Override - public Connection openConnection() throws SQLException, ClassNotFoundException { - if (checkConnection()) { - return this.connection; - } - Class.forName("com.mysql.jdbc.Driver"); - this.connection = - DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); - return this.connection; - } + @Override + public Connection openConnection() throws SQLException, ClassNotFoundException { + if (checkConnection()) { + return this.connection; + } + Class.forName("com.mysql.jdbc.Driver"); + this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); + return this.connection; + } - @Override - public boolean checkConnection() throws SQLException { - return (this.connection != null) && !this.connection.isClosed(); - } + @Override + public boolean checkConnection() throws SQLException { + return (this.connection != null) && !this.connection.isClosed(); + } - @Override - public Connection getConnection() { - return this.connection; - } + @Override + public Connection getConnection() { + return this.connection; + } - @Override - public boolean closeConnection() throws SQLException { - if (this.connection == null) { - return false; - } - this.connection.close(); - return true; - } + @Override + public boolean closeConnection() throws SQLException { + if (this.connection == null) { + return false; + } + this.connection.close(); + return true; + } - @Override - public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public ResultSet querySQL(final String query) throws SQLException, ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + final Statement statement = this.connection.createStatement(); - ResultSet result = statement.executeQuery(query); + final ResultSet result = statement.executeQuery(query); - return result; - } + return result; + } - @Override - public int updateSQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public int updateSQL(final String query) throws SQLException, ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + final Statement statement = this.connection.createStatement(); - int result = statement.executeUpdate(query); + final int result = statement.executeUpdate(query); - return result; - } + return result; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/PlotMeConverter.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/PlotMeConverter.java index 51d3de69f..7ef109d0a 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/PlotMeConverter.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/PlotMeConverter.java @@ -1,299 +1,268 @@ package com.intellectualcrafters.plot.database; -import com.google.common.base.Charsets; -import com.intellectualcrafters.plot.Configuration; -import com.intellectualcrafters.plot.ConfigurationNode; -import com.intellectualcrafters.plot.PlotBlock; -import com.intellectualcrafters.plot.PlotHomePosition; -import com.intellectualcrafters.plot.PlotId; -import com.intellectualcrafters.plot.PlotMain; -import com.intellectualcrafters.plot.generator.DefaultPlotWorld; -import com.intellectualcrafters.plot.generator.WorldGenerator; -import com.worldcretornica.plotme.PlayerList; -import com.worldcretornica.plotme.Plot; -import com.worldcretornica.plotme.PlotManager; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.WorldCreator; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.Plugin; - import java.io.IOException; -import java.io.PrintStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.Plugin; + +import com.google.common.base.Charsets; +import com.intellectualcrafters.plot.PlotHomePosition; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.generator.WorldGenerator; +import com.worldcretornica.plotme.PlayerList; +import com.worldcretornica.plotme.Plot; +import com.worldcretornica.plotme.PlotManager; + /** * Created by Citymonstret on 2014-08-17. */ public class PlotMeConverter { - private PlotMain plugin; + private final PlotMain plugin; - public PlotMeConverter(PlotMain plugin) { - this.plugin = plugin; - } + public PlotMeConverter(final PlotMain plugin) { + this.plugin = plugin; + } - public void runAsync() throws Exception { - Bukkit.getScheduler().runTaskLater(this.plugin, new Runnable() { + public void runAsync() throws Exception { + Bukkit.getScheduler().runTaskLater(this.plugin, new Runnable() { @Override public void run() { - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has started"); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Caching playerdata..."); - ArrayList createdPlots = - new ArrayList(); - boolean online = Bukkit.getServer().getOnlineMode(); - - Plugin plotMePlugin = Bukkit.getPluginManager().getPlugin("PlotMe"); - FileConfiguration plotConfig = plotMePlugin.getConfig(); - - Set worlds = new HashSet(); - - for (World world : Bukkit.getWorlds()) { - int duplicate = 0; - HashMap plots = PlotManager.getPlots(world); - if (plots != null) { - - worlds.add(world.getName()); - - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Converting configuration for world '"+world.getName()+"'..."); - - try { - - Integer pathwidth = plotConfig.getInt("worlds."+world.getName()+".PathWidth"); // - PlotMain.config.set("worlds."+world.getName()+".road.width", pathwidth); - - Integer plotsize = plotConfig.getInt("worlds."+world.getName()+".PlotSize"); // - PlotMain.config.set("worlds."+world.getName()+".plot.size", plotsize); - - String wallblock = plotConfig.getString("worlds."+world.getName()+".WallBlockId"); // - PlotMain.config.set("worlds."+world.getName()+".wall.block", wallblock); - - String floor = plotConfig.getString("worlds."+world.getName()+".PlotFloorBlockId"); // - PlotMain.config.set("worlds."+world.getName()+".plot.floor", Arrays.asList(new String[] {floor})); - - String filling = plotConfig.getString("worlds."+world.getName()+".PlotFillingBlockId"); // - PlotMain.config.set("worlds."+world.getName()+".plot.filling", Arrays.asList(new String[] {filling})); - - String road = plotConfig.getString("worlds."+world.getName()+".RoadMainBlockId"); - PlotMain.config.set("worlds."+world.getName()+".road.block", road); - - String road_stripe = plotConfig.getString("worlds."+world.getName()+".RoadStripeBlockId"); - PlotMain.config.set("worlds."+world.getName()+".road.stripes", road_stripe); - - Integer height = plotConfig.getInt("worlds."+world.getName()+".RoadHeight"); // - PlotMain.config.set("worlds."+world.getName()+".road.height", height); - - Boolean auto_link = plotConfig.getBoolean("worlds."+world.getName()+".AutoLinkPlots"); // - PlotMain.config.set("worlds."+world.getName()+".plot.auto_merge", auto_link); - - } - catch (Exception e) { - PlotMain.sendConsoleSenderMessage(" - Failed to save configuration for world '"+world.getName()+"'. This will need to be done using the setup command or manually."); - } - - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Processing '" + plots.size() + "' plots for world '" + world.getName() + "'"); - - for (Plot plot : plots.values()) { - ArrayList psAdded = new ArrayList<>(); - ArrayList psTrusted = new ArrayList<>(); - ArrayList psDenied = new ArrayList<>(); - if (world == null) { - world = Bukkit.getWorld("world"); - } - long eR3040bl230 = 22392948l; - try { - if (online) { - PlayerList denied = null; - PlayerList added = null; - Field fAdded = plot.getClass().getDeclaredField("allowed"); - Field fDenied = plot.getClass().getDeclaredField("denied"); - fAdded.setAccessible(true); - fDenied.setAccessible(true); - added = (PlayerList) fAdded.get(plot); - denied = (PlayerList) fDenied.get(plot); - for (Map.Entry set : added.getAllPlayers().entrySet()) { - if ((set.getValue() != null) || set.getKey().equals("*")) { - if (set.getKey().equalsIgnoreCase("*") - || set.getValue().toString().equals("*")) { - psAdded.add(DBFunc.everyone); - continue; - } - } - if (set.getValue() != null) { - psAdded.add(set.getValue()); - } - } - for (Map.Entry set : denied.getAllPlayers().entrySet()) { - if ((set.getValue() != null) || set.getKey().equals("*")) { - if (set.getKey().equals("*") || set.getValue().toString().equals("*")) { - psDenied.add(DBFunc.everyone); - continue; - } - } - if (set.getValue() != null) { - psDenied.add(set.getValue()); - } - } - } - else { - for (String user : plot.getAllowed().split(",")) { - if (user.equals("*")) { - psAdded.add(DBFunc.everyone); - } - else { - UUID uuid = - UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); - psAdded.add(uuid); - } - } - try { - for (String user : plot.getDenied().split(",")) { - if (user.equals("*")) { - psDenied.add(DBFunc.everyone); - } - else { - UUID uuid = - UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); - psDenied.add(uuid); - } - } - } - catch (Throwable e) { - - } - } - } - catch (Throwable e) { - e.printStackTrace(); - eR3040bl230 = 232000499888388747l; - } - finally { - eR3040bl230 = 232999304998392004l; - } - PlotId id = - new PlotId(Integer.parseInt(plot.id.split(";")[0]), Integer.parseInt(plot.id.split(";")[1])); - com.intellectualcrafters.plot.Plot pl = null; - if (online) { - pl = new com.intellectualcrafters.plot.Plot( - id, - plot.getOwnerId(), - plot.getBiome(), - psAdded, psTrusted, - psDenied, - - "", - PlotHomePosition.DEFAULT, - null, - world.getName(), - new boolean[] { false, false, false, false }); - } - else { - String owner = plot.getOwner(); - pl = new com.intellectualcrafters.plot.Plot( - id, - UUID.nameUUIDFromBytes(("OfflinePlayer:" + owner).getBytes(Charsets.UTF_8)), - plot.getBiome(), - psAdded, - psTrusted, - psDenied, - - "", - PlotHomePosition.DEFAULT, - null, - world.getName(), - new boolean[] { false, false, false, false }); - } - - if (pl != null) { - if (!PlotMain.getPlots(world).containsKey(id)) { - createdPlots.add(pl); - } - else { - duplicate++; - } - } - } - if (duplicate>0) { - PlotMain.sendConsoleSenderMessage("&c[WARNING] Found "+duplicate+" duplicate plots already in DB for world: '"+world.getName()+"'. Have you run the converter already?"); - } - } - } - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating plot DB"); - DBFunc.createPlots(createdPlots); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating settings/helpers DB"); - - // TODO createPlot doesn't add denied users - DBFunc.createAllSettingsAndHelpers(createdPlots); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Saving configuration..."); - try { + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has started"); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Caching playerdata..."); + final ArrayList createdPlots = new ArrayList(); + final boolean online = Bukkit.getServer().getOnlineMode(); + + final Plugin plotMePlugin = Bukkit.getPluginManager().getPlugin("PlotMe"); + final FileConfiguration plotConfig = plotMePlugin.getConfig(); + + final Set worlds = new HashSet(); + + for (World world : Bukkit.getWorlds()) { + int duplicate = 0; + final HashMap plots = PlotManager.getPlots(world); + if (plots != null) { + + worlds.add(world.getName()); + + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Converting configuration for world '" + world.getName() + "'..."); + + try { + + final Integer pathwidth = plotConfig.getInt("worlds." + world.getName() + ".PathWidth"); // + PlotMain.config.set("worlds." + world.getName() + ".road.width", pathwidth); + + final Integer plotsize = plotConfig.getInt("worlds." + world.getName() + ".PlotSize"); // + PlotMain.config.set("worlds." + world.getName() + ".plot.size", plotsize); + + final String wallblock = plotConfig.getString("worlds." + world.getName() + ".WallBlockId"); // + PlotMain.config.set("worlds." + world.getName() + ".wall.block", wallblock); + + final String floor = plotConfig.getString("worlds." + world.getName() + ".PlotFloorBlockId"); // + PlotMain.config.set("worlds." + world.getName() + ".plot.floor", Arrays.asList(new String[] { floor })); + + final String filling = plotConfig.getString("worlds." + world.getName() + ".PlotFillingBlockId"); // + PlotMain.config.set("worlds." + world.getName() + ".plot.filling", Arrays.asList(new String[] { filling })); + + final String road = plotConfig.getString("worlds." + world.getName() + ".RoadMainBlockId"); + PlotMain.config.set("worlds." + world.getName() + ".road.block", road); + + final String road_stripe = plotConfig.getString("worlds." + world.getName() + ".RoadStripeBlockId"); + PlotMain.config.set("worlds." + world.getName() + ".road.stripes", road_stripe); + + final Integer height = plotConfig.getInt("worlds." + world.getName() + ".RoadHeight"); // + PlotMain.config.set("worlds." + world.getName() + ".road.height", height); + + final Boolean auto_link = plotConfig.getBoolean("worlds." + world.getName() + ".AutoLinkPlots"); // + PlotMain.config.set("worlds." + world.getName() + ".plot.auto_merge", auto_link); + + } + catch (final Exception e) { + PlotMain.sendConsoleSenderMessage(" - Failed to save configuration for world '" + world.getName() + "'. This will need to be done using the setup command or manually."); + } + + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Processing '" + plots.size() + "' plots for world '" + world.getName() + "'"); + + for (final Plot plot : plots.values()) { + final ArrayList psAdded = new ArrayList<>(); + final ArrayList psTrusted = new ArrayList<>(); + final ArrayList psDenied = new ArrayList<>(); + if (world == null) { + world = Bukkit.getWorld("world"); + } + try { + if (online) { + PlayerList denied = null; + PlayerList added = null; + final Field fAdded = plot.getClass().getDeclaredField("allowed"); + final Field fDenied = plot.getClass().getDeclaredField("denied"); + fAdded.setAccessible(true); + fDenied.setAccessible(true); + added = (PlayerList) fAdded.get(plot); + denied = (PlayerList) fDenied.get(plot); + for (final Map.Entry set : added.getAllPlayers().entrySet()) { + if ((set.getValue() != null) || set.getKey().equals("*")) { + if (set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equals("*")) { + psAdded.add(DBFunc.everyone); + continue; + } + } + if (set.getValue() != null) { + psAdded.add(set.getValue()); + } + } + for (final Map.Entry set : denied.getAllPlayers().entrySet()) { + if ((set.getValue() != null) || set.getKey().equals("*")) { + if (set.getKey().equals("*") || set.getValue().toString().equals("*")) { + psDenied.add(DBFunc.everyone); + continue; + } + } + if (set.getValue() != null) { + psDenied.add(set.getValue()); + } + } + } + else { + for (final String user : plot.getAllowed().split(",")) { + if (user.equals("*")) { + psAdded.add(DBFunc.everyone); + } + else { + final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); + psAdded.add(uuid); + } + } + try { + for (final String user : plot.getDenied().split(",")) { + if (user.equals("*")) { + psDenied.add(DBFunc.everyone); + } + else { + final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); + psDenied.add(uuid); + } + } + } + catch (final Throwable e) { + + } + } + } + catch (final Throwable e) { + e.printStackTrace(); + } + finally { + } + final PlotId id = new PlotId(Integer.parseInt(plot.id.split(";")[0]), Integer.parseInt(plot.id.split(";")[1])); + com.intellectualcrafters.plot.Plot pl = null; + if (online) { + pl = new com.intellectualcrafters.plot.Plot(id, plot.getOwnerId(), plot.getBiome(), psAdded, psTrusted, psDenied, + + "", PlotHomePosition.DEFAULT, null, world.getName(), new boolean[] { false, false, false, false }); + } + else { + final String owner = plot.getOwner(); + pl = new com.intellectualcrafters.plot.Plot(id, UUID.nameUUIDFromBytes(("OfflinePlayer:" + owner).getBytes(Charsets.UTF_8)), plot.getBiome(), psAdded, psTrusted, psDenied, + + "", PlotHomePosition.DEFAULT, null, world.getName(), new boolean[] { false, false, false, false }); + } + + if (pl != null) { + if (!PlotMain.getPlots(world).containsKey(id)) { + createdPlots.add(pl); + } + else { + duplicate++; + } + } + } + if (duplicate > 0) { + PlotMain.sendConsoleSenderMessage("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world.getName() + "'. Have you run the converter already?"); + } + } + } + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating plot DB"); + DBFunc.createPlots(createdPlots); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating settings/helpers DB"); + + // TODO createPlot doesn't add denied users + DBFunc.createAllSettingsAndHelpers(createdPlots); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Saving configuration..."); + try { PlotMain.config.save(PlotMain.configFile); - } catch (IOException e) { + } + catch (final IOException e) { PlotMain.sendConsoleSenderMessage(" - &cFailed to save configuration."); } - - boolean MV = false; - boolean MW = false; - - if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + + boolean MV = false; + boolean MW = false; + + if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { MV = true; } - else if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { + else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { MW = true; } - - for (String worldname : worlds) { - World world = Bukkit.getWorld(worldname); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Reloading generator for world: '"+worldname+"'..."); - - PlotMain.removePlotWorld(worldname); - - if (MV) { - // unload - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + worldname); - try { - Thread.sleep(1000); - } catch(InterruptedException ex) { - Thread.currentThread().interrupt(); - } - // load - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + worldname + " normal -g PlotSquared"); - } - else if (MW) { - // unload - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + worldname); - try { - Thread.sleep(1000); - } catch(InterruptedException ex) { - Thread.currentThread().interrupt(); - } - // load - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + worldname+" plugin:PlotSquared"); - } - else { - System.out.print("LOADED WORLD"); - Bukkit.getServer().unloadWorld(world, true); - World myworld = WorldCreator.name(worldname).generator(new WorldGenerator(worldname)).createWorld(); + + for (final String worldname : worlds) { + final World world = Bukkit.getWorld(worldname); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Reloading generator for world: '" + worldname + "'..."); + + PlotMain.removePlotWorld(worldname); + + if (MV) { + // unload + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + worldname); + try { + Thread.sleep(1000); + } + catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); + } + // load + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + worldname + " normal -g PlotSquared"); + } + else if (MW) { + // unload + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + worldname); + try { + Thread.sleep(1000); + } + catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); + } + // load + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + worldname + " plugin:PlotSquared"); + } + else { + System.out.print("LOADED WORLD"); + Bukkit.getServer().unloadWorld(world, true); + final World myworld = WorldCreator.name(worldname).generator(new WorldGenerator(worldname)).createWorld(); myworld.save(); - } - } - - PlotMain.setAllPlotsRaw(DBFunc.getPlots()); - - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Disabling PlotMe..."); - Bukkit.getPluginManager().disablePlugin(plotMePlugin); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Conversion has finished"); - PlotMain.sendConsoleSenderMessage("&cAlthough the server may be functional in it's current state, it is recommended that you restart the server and remove PlotMe to finalize the installation. Please make careful note of any warning messages that may have showed up during conversion."); + } + } + + PlotMain.setAllPlotsRaw(DBFunc.getPlots()); + + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Disabling PlotMe..."); + Bukkit.getPluginManager().disablePlugin(plotMePlugin); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8:&7 Conversion has finished"); + PlotMain.sendConsoleSenderMessage("&cAlthough the server may be functional in it's current state, it is recommended that you restart the server and remove PlotMe to finalize the installation. Please make careful note of any warning messages that may have showed up during conversion."); } - }, 20); - } + }, 20); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java index 56e1318a9..ef557214d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java @@ -2,482 +2,462 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = DBFunc.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot.database; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.Logger.LogLevel; +import static com.intellectualcrafters.plot.PlotMain.connection; +import static com.intellectualcrafters.plot.Settings.DB.PREFIX; + +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Set; +import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.block.Biome; -import java.sql.*; -import java.util.*; - -import static com.intellectualcrafters.plot.PlotMain.connection; -import static com.intellectualcrafters.plot.Settings.DB.PREFIX; +import com.intellectualcrafters.plot.Flag; +import com.intellectualcrafters.plot.FlagManager; +import com.intellectualcrafters.plot.Logger; +import com.intellectualcrafters.plot.Logger.LogLevel; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotComment; +import com.intellectualcrafters.plot.PlotHomePosition; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; /** * @author Citymonstret */ public class SQLManager extends AbstractDB { - // TODO MongoDB @Brandon + // TODO MongoDB @Brandon - - public static final String SET_OWNER = "UPDATE `" + PREFIX + "plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ?"; - public static final String GET_ALL_PLOTS = "SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `" + PREFIX + "plot`"; - public static final String CREATE_PLOTS = "INSERT INTO `" + PREFIX + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) values "; + public static final String SET_OWNER = "UPDATE `" + PREFIX + "plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ?"; + public static final String GET_ALL_PLOTS = "SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `" + PREFIX + "plot`"; + public static final String CREATE_PLOTS = "INSERT INTO `" + PREFIX + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) values "; public static final String CREATE_SETTINGS = "INSERT INTO `" + PREFIX + "plot_settings` (`plot_plot_id`) values "; - public static final String CREATE_HELPERS = "INSERT INTO `" + PREFIX + "plot_helpers` (`plot_plot_id`, `user_uuid`) values "; - public static final String CREATE_PLOT = "INSERT INTO `" + PREFIX + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) VALUES(?, ?, ?, ?)"; - /** - * Set Plot owner - * - * @param plot - * @param uuid - */ - public void setOwner(final Plot plot, final UUID uuid) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement(SET_OWNER); - statement.setString(1, uuid.toString()); - statement.setInt(2, plot.id.x); - statement.setInt(3, plot.id.y); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Could not set owner for plot " + plot.id); - } - } - }); - } + public static final String CREATE_HELPERS = "INSERT INTO `" + PREFIX + "plot_helpers` (`plot_plot_id`, `user_uuid`) values "; + public static final String CREATE_PLOT = "INSERT INTO `" + PREFIX + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) VALUES(?, ?, ?, ?)"; - @Override - public void createAllSettingsAndHelpers(ArrayList plots) { - - // TODO SEVERE [ More than 5000 plots will fail in a single SQLite query. - - HashMap> stored = new HashMap>(); - HashMap> helpers = new HashMap>(); - try { - PreparedStatement stmt = - connection.prepareStatement(GET_ALL_PLOTS); - ResultSet result = stmt.executeQuery(); - while (result.next()) { - int id = result.getInt("id"); - int idx = result.getInt("plot_id_x"); - int idz = result.getInt("plot_id_z"); - String world = result.getString("world"); + /** + * Set Plot owner + * + * @param plot + * @param uuid + */ + @Override + public void setOwner(final Plot plot, final UUID uuid) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement(SET_OWNER); + statement.setString(1, uuid.toString()); + statement.setInt(2, plot.id.x); + statement.setInt(3, plot.id.y); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Could not set owner for plot " + plot.id); + } + } + }); + } - if (!stored.containsKey(world)) { - stored.put(world, new HashMap()); - } - stored.get(world).put(new PlotId(idx, idz), id); - } - } - catch (SQLException e) { - e.printStackTrace(); - } + @Override + public void createAllSettingsAndHelpers(final ArrayList plots) { - for (Plot plot : plots) { - String world = Bukkit.getWorld(plot.world).getName(); - if (stored.containsKey(world)) { - Integer id = stored.get(world).get(plot.id); - if (id != null) { - helpers.put(id, plot.helpers); - } - } - } + // TODO SEVERE [ More than 5000 plots will fail in a single SQLite + // query. - if (helpers.size() == 0) { - return; - } + final HashMap> stored = new HashMap>(); + final HashMap> helpers = new HashMap>(); + try { + final PreparedStatement stmt = connection.prepareStatement(GET_ALL_PLOTS); + final ResultSet result = stmt.executeQuery(); + while (result.next()) { + final int id = result.getInt("id"); + final int idx = result.getInt("plot_id_x"); + final int idz = result.getInt("plot_id_z"); + final String world = result.getString("world"); - // add plot settings - Integer[] ids = helpers.keySet().toArray(new Integer[0]); - StringBuilder statement = new StringBuilder(CREATE_SETTINGS); - for (int i = 0; i < (ids.length - 1); i++) { - statement.append("(?),"); - } - statement.append("(?)"); - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement(statement.toString()); - for (int i = 0; i < ids.length; i++) { - stmt.setInt(i + 1, ids[i]); - } - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - } + if (!stored.containsKey(world)) { + stored.put(world, new HashMap()); + } + stored.get(world).put(new PlotId(idx, idz), id); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } - // add plot helpers - String prefix = ""; - statement = new StringBuilder(CREATE_HELPERS); - for (Integer id : helpers.keySet()) { - for (UUID helper : helpers.get(id)) { - statement.append(prefix + "(?, ?)"); - prefix = ","; - } - } - if (prefix.equals("")) { - return; - } - try { - stmt = connection.prepareStatement(statement.toString()); - int counter = 0; - for (Integer id : helpers.keySet()) { - for (UUID helper : helpers.get(id)) { + for (final Plot plot : plots) { + final String world = Bukkit.getWorld(plot.world).getName(); + if (stored.containsKey(world)) { + final Integer id = stored.get(world).get(plot.id); + if (id != null) { + helpers.put(id, plot.helpers); + } + } + } - stmt.setInt((counter * 2) + 1, id); - stmt.setString((counter * 2) + 2, helper.toString()); - counter++; - } - } - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set helper for plots"); - e.printStackTrace(); - } - } + if (helpers.size() == 0) { + return; + } - /** - * Create a plot - * - * @param plots - */ - @Override - public void createPlots(ArrayList plots) { - - // TODO SEVERE [ More than 5000 plots will fail in a single SQLite query. - - if (plots.size() == 0) { - return; - } - StringBuilder statement = - new StringBuilder(CREATE_PLOTS); + // add plot settings + final Integer[] ids = helpers.keySet().toArray(new Integer[0]); + StringBuilder statement = new StringBuilder(CREATE_SETTINGS); + for (int i = 0; i < (ids.length - 1); i++) { + statement.append("(?),"); + } + statement.append("(?)"); + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement(statement.toString()); + for (int i = 0; i < ids.length; i++) { + stmt.setInt(i + 1, ids[i]); + } + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + } - for (int i = 0; i < (plots.size() - 1); i++) { - statement.append("(?,?,?,?),"); - } - statement.append("(?,?,?,?)"); + // add plot helpers + String prefix = ""; + statement = new StringBuilder(CREATE_HELPERS); + for (final Integer id : helpers.keySet()) { + for (final UUID helper : helpers.get(id)) { + statement.append(prefix + "(?, ?)"); + prefix = ","; + } + } + if (prefix.equals("")) { + return; + } + try { + stmt = connection.prepareStatement(statement.toString()); + int counter = 0; + for (final Integer id : helpers.keySet()) { + for (final UUID helper : helpers.get(id)) { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement(statement.toString()); - for (int i = 0; i < plots.size(); i++) { - Plot plot = plots.get(i); - stmt.setInt((i * 4) + 1, plot.id.x); - stmt.setInt((i * 4) + 2, plot.id.y); - stmt.setString((i * 4) + 3, plot.owner.toString()); - stmt.setString((i * 4) + 4, plot.world); - } - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Failed to save plots!"); - } - } + stmt.setInt((counter * 2) + 1, id); + stmt.setString((counter * 2) + 2, helper.toString()); + counter++; + } + } + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set helper for plots"); + e.printStackTrace(); + } + } - /** - * Create a plot - * - * @param plot - */ - @Override - public void createPlot(Plot plot) { - PreparedStatement stmt = null; - try { - stmt = - connection.prepareStatement(CREATE_PLOT); - stmt.setInt(1, plot.id.x); - stmt.setInt(2, plot.id.y); - stmt.setString(3, plot.owner.toString()); - stmt.setString(4, plot.world); - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Failed to save plot " + plot.id); - } - } + /** + * Create a plot + * + * @param plots + */ + @Override + public void createPlots(final ArrayList plots) { - /** - * Create tables - * - * @throws SQLException - */ - @Override - public void createTables(String database, boolean add_constraint) throws SQLException { - boolean mysql = database.equals("mysql"); - Statement stmt = connection.createStatement(); - if (mysql) { - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," - + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," - + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," - + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_comments` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`tier` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," - + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," - + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," - + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," - + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," - + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)," - + " UNIQUE KEY `unique_alias` (`alias`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_ratings` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); - if (add_constraint) { - stmt.addBatch("ALTER TABLE `" + PREFIX + "plot_settings` ADD CONSTRAINT `"+ PREFIX + "plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `"+PREFIX+"plot` (`id`) ON DELETE CASCADE"); - } + // TODO SEVERE [ More than 5000 plots will fail in a single SQLite + // query. - } - else { - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot` (" + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," - + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," - + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," - + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_comments` (" + "`plot_plot_id` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`tier` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," - + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," - + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," - + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," - + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," - + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_ratings` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`))"); - } - stmt.executeBatch(); - stmt.clearBatch(); - stmt.close(); - } + if (plots.size() == 0) { + return; + } + final StringBuilder statement = new StringBuilder(CREATE_PLOTS); - /** - * Delete a plot - * - * @param plot - */ - @Override - public void delete(final String world, final Plot plot) { - PlotMain.removePlot(world, plot.id, false); - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - int id = getId(world, plot.id); - try { - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_helpers` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `"+ PREFIX +"plot` WHERE `id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Failed to delete plot " + plot.id); - } - } - }); - } + for (int i = 0; i < (plots.size() - 1); i++) { + statement.append("(?,?,?,?),"); + } + statement.append("(?,?,?,?)"); - /** - * Create plot settings - * - * @param id - * @param plot - */ - @Override - public void createPlotSettings(final int id, final Plot plot) { - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("INSERT INTO `"+ PREFIX +"plot_settings`(`plot_plot_id`) VALUES(" + "?)"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - } + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement(statement.toString()); + for (int i = 0; i < plots.size(); i++) { + final Plot plot = plots.get(i); + stmt.setInt((i * 4) + 1, plot.id.x); + stmt.setInt((i * 4) + 2, plot.id.y); + stmt.setString((i * 4) + 3, plot.owner.toString()); + stmt.setString((i * 4) + 4, plot.world); + } + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Failed to save plots!"); + } + } - } - }); - } + /** + * Create a plot + * + * @param plot + */ + @Override + public void createPlot(final Plot plot) { + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement(CREATE_PLOT); + stmt.setInt(1, plot.id.x); + stmt.setInt(2, plot.id.y); + stmt.setString(3, plot.owner.toString()); + stmt.setString(4, plot.world); + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Failed to save plot " + plot.id); + } + } - @Override - public int getId(String world, PlotId id2) { - PreparedStatement stmt = null; - try { - 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, id2.x); - stmt.setInt(2, id2.y); - stmt.setString(3, world); - ResultSet r = stmt.executeQuery(); - int id = Integer.MAX_VALUE; - while (r.next()) { - id = r.getInt("id"); - } - stmt.close(); - return id; - } - catch (SQLException e) { - e.printStackTrace(); - } - return Integer.MAX_VALUE; - } + /** + * Create tables + * + * @throws SQLException + */ + @Override + public void createTables(final String database, final boolean add_constraint) throws SQLException { + final boolean mysql = database.equals("mysql"); + final Statement stmt = connection.createStatement(); + if (mysql) { + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_comments` (" + "`plot_plot_id` INT(11) NOT NULL," + "`comment` VARCHAR(40) NOT NULL," + "`tier` INT(11) NOT NULL," + "`sender` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)," + " UNIQUE KEY `unique_alias` (`alias`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_ratings` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + if (add_constraint) { + stmt.addBatch("ALTER TABLE `" + PREFIX + "plot_settings` ADD CONSTRAINT `" + PREFIX + "plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `" + PREFIX + "plot` (`id`) ON DELETE CASCADE"); + } - /** - * @return - */ - @Override - public LinkedHashMap> getPlots() { - LinkedHashMap> newplots = new LinkedHashMap>(); - try { - DatabaseMetaData data = connection.getMetaData(); - ResultSet rs = data.getColumns(null, null, PREFIX+"plot", "plot_id"); - boolean execute = rs.next(); - if (execute) { - Statement statement = connection.createStatement(); - statement.addBatch("ALTER IGNORE TABLE `" + PREFIX + "plot` ADD `plot_id_x` int(11) DEFAULT 0"); - statement.addBatch("ALTER IGNORE TABLE `" + PREFIX +"plot` ADD `plot_id_z` int(11) DEFAULT 0"); - statement.addBatch("UPDATE `"+PREFIX+"plot` SET\n" + " `plot_id_x` = IF(" - + " LOCATE(';', `plot_id`) > 0," - + " SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," + " `plot_id`" - + " )," + " `plot_id_z` = IF(" + " LOCATE(';', `plot_id`) > 0," - + " SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," + " NULL" + " )"); - statement.addBatch("ALTER TABLE `" + PREFIX +"plot` DROP `plot_id`"); - statement.addBatch("ALTER IGNORE TABLE `" + PREFIX +"plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL"); - statement.executeBatch(); - statement.close(); - } - rs = data.getColumns(null, null, PREFIX + "plot_settings", "merged"); - if (!rs.next()) { - Statement statement = connection.createStatement(); - statement.addBatch("ALTER TABLE `" + PREFIX + "plot_settings` ADD `merged` int(11) DEFAULT NULL"); - statement.executeBatch(); - statement.close(); - } - } - catch (Exception e) { - e.printStackTrace(); - } - HashMap plots = new HashMap(); - - - Statement stmt = null; - try { + } + else { + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot` (" + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_comments` (" + "`plot_plot_id` INT(11) NOT NULL," + "`comment` VARCHAR(40) NOT NULL," + "`tier` INT(11) NOT NULL," + "`sender` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + PREFIX + "plot_ratings` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`))"); + } + stmt.executeBatch(); + stmt.clearBatch(); + stmt.close(); + } - Set worlds = new HashSet(); - if (PlotMain.config.contains("worlds")) { - worlds = PlotMain.config.getConfigurationSection("worlds").getKeys(false); - } - - HashMap uuids = new HashMap(); - HashMap noExist = new HashMap(); - - /* + /** + * Delete a plot + * + * @param plot + */ + @Override + public void delete(final String world, final Plot plot) { + PlotMain.removePlot(world, plot.id, false); + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + final int id = getId(world, plot.id); + try { + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_helpers` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot` WHERE `id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Failed to delete plot " + plot.id); + } + } + }); + } + + /** + * Create plot settings + * + * @param id + * @param plot + */ + @Override + public void createPlotSettings(final int id, final Plot plot) { + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + } + + } + }); + } + + @Override + public int getId(final String world, final PlotId id2) { + PreparedStatement stmt = null; + try { + 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, id2.x); + stmt.setInt(2, id2.y); + stmt.setString(3, world); + final ResultSet r = stmt.executeQuery(); + int id = Integer.MAX_VALUE; + while (r.next()) { + id = r.getInt("id"); + } + stmt.close(); + return id; + } + catch (final SQLException e) { + e.printStackTrace(); + } + return Integer.MAX_VALUE; + } + + /** + * @return + */ + @Override + public LinkedHashMap> getPlots() { + final LinkedHashMap> newplots = new LinkedHashMap>(); + try { + final DatabaseMetaData data = connection.getMetaData(); + ResultSet rs = data.getColumns(null, null, PREFIX + "plot", "plot_id"); + final boolean execute = rs.next(); + if (execute) { + final Statement statement = connection.createStatement(); + statement.addBatch("ALTER IGNORE TABLE `" + PREFIX + "plot` ADD `plot_id_x` int(11) DEFAULT 0"); + statement.addBatch("ALTER IGNORE TABLE `" + PREFIX + "plot` ADD `plot_id_z` int(11) DEFAULT 0"); + statement.addBatch("UPDATE `" + PREFIX + "plot` SET\n" + " `plot_id_x` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," + " `plot_id`" + " )," + " `plot_id_z` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," + " NULL" + " )"); + statement.addBatch("ALTER TABLE `" + PREFIX + "plot` DROP `plot_id`"); + statement.addBatch("ALTER IGNORE TABLE `" + PREFIX + "plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL"); + statement.executeBatch(); + statement.close(); + } + rs = data.getColumns(null, null, PREFIX + "plot_settings", "merged"); + if (!rs.next()) { + final Statement statement = connection.createStatement(); + statement.addBatch("ALTER TABLE `" + PREFIX + "plot_settings` ADD `merged` int(11) DEFAULT NULL"); + statement.executeBatch(); + statement.close(); + } + } + catch (final Exception e) { + e.printStackTrace(); + } + final HashMap plots = new HashMap(); + + Statement stmt = null; + try { + + Set worlds = new HashSet(); + if (PlotMain.config.contains("worlds")) { + worlds = PlotMain.config.getConfigurationSection("worlds").getKeys(false); + } + + final HashMap uuids = new HashMap(); + final HashMap noExist = new HashMap(); + + /* * Getting plots */ - stmt = connection.createStatement(); - ResultSet r = stmt.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world` FROM `" + PREFIX +"plot`"); - PlotId plot_id; - int id; - Plot p; - String o; - UUID user; - while (r.next()) { - plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); - id = r.getInt("id"); - String worldname = r.getString("world"); - if (!worlds.contains(worldname)) { - if (noExist.containsKey(worldname)) { - noExist.put(worldname,noExist.get(worldname)+1); - } - else { - noExist.put(worldname,1); - } - } - o = r.getString("owner"); - user = uuids.get(o); - if (user==null) { - user = UUID.fromString(o); - uuids.put(o, user); - } - p = new Plot(plot_id, user, Biome.FOREST, new ArrayList(), new ArrayList(), new ArrayList(), "", PlotHomePosition.DEFAULT, null, worldname, new boolean[] {false, false, false, false}); - plots.put(id, p); - } - stmt.close(); - - /* - * Getting helpers - */ - stmt = connection.createStatement(); + stmt = connection.createStatement(); + ResultSet r = stmt.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world` FROM `" + PREFIX + "plot`"); + PlotId plot_id; + int id; + Plot p; + String o; + UUID user; + while (r.next()) { + plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); + id = r.getInt("id"); + final String worldname = r.getString("world"); + if (!worlds.contains(worldname)) { + if (noExist.containsKey(worldname)) { + noExist.put(worldname, noExist.get(worldname) + 1); + } + else { + noExist.put(worldname, 1); + } + } + o = r.getString("owner"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } + p = new Plot(plot_id, user, Biome.FOREST, new ArrayList(), new ArrayList(), new ArrayList(), "", PlotHomePosition.DEFAULT, null, worldname, new boolean[] { false, false, false, false }); + plots.put(id, p); + } + stmt.close(); + + /* + * Getting helpers + */ + stmt = connection.createStatement(); r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + PREFIX + "plot_helpers`"); while (r.next()) { id = r.getInt("plot_plot_id"); o = r.getString("user_uuid"); user = uuids.get(o); - if (user==null) { + if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } - Plot plot = plots.get(id); - if (plot!=null) { + final Plot plot = plots.get(id); + if (plot != null) { plot.addHelper(user); } else { - PlotMain.sendConsoleSenderMessage("&cPLOT "+id+" in plot_helpers does not exist. Please create the plot or remove this entry."); + PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_helpers does not exist. Please create the plot or remove this entry."); } } stmt.close(); - + /* * Getting trusted */ @@ -487,20 +467,20 @@ public class SQLManager extends AbstractDB { id = r.getInt("plot_plot_id"); o = r.getString("user_uuid"); user = uuids.get(o); - if (user==null) { + if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } - Plot plot = plots.get(id); - if (plot!=null) { + final Plot plot = plots.get(id); + if (plot != null) { plot.addTrusted(user); } else { - PlotMain.sendConsoleSenderMessage("&cPLOT "+id+" in plot_trusted does not exist. Please create the plot or remove this entry."); + PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_trusted does not exist. Please create the plot or remove this entry."); } } stmt.close(); - + /* * Getting denied */ @@ -510,201 +490,197 @@ public class SQLManager extends AbstractDB { id = r.getInt("plot_plot_id"); o = r.getString("user_uuid"); user = uuids.get(o); - if (user==null) { + if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } - Plot plot = plots.get(id); - if (plot!=null) { + final Plot plot = plots.get(id); + if (plot != null) { plot.addDenied(user); } else { - PlotMain.sendConsoleSenderMessage("&cPLOT "+id+" in plot_denied does not exist. Please create the plot or remove this entry."); + PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_denied does not exist. Please create the plot or remove this entry."); } } stmt.close(); - + stmt = connection.createStatement(); r = stmt.executeQuery("SELECT * FROM `" + PREFIX + "plot_settings`"); while (r.next()) { id = r.getInt("plot_plot_id"); - Plot plot = plots.get(id); - if (plot!=null) { - - String b = r.getString("biome"); + final Plot plot = plots.get(id); + if (plot != null) { + + final String b = r.getString("biome"); Biome biome = null; - if (b!=null) { - for (Biome mybiome : Biome.values()) { + if (b != null) { + for (final Biome mybiome : Biome.values()) { if (mybiome.toString().equalsIgnoreCase(b)) { biome = mybiome; break; } } } - if (biome==null) { + if (biome == null) { biome = Biome.FOREST; } plot.settings.setBiome(biome); - - String alias = r.getString("alias"); - if (alias!=null) { + + final String alias = r.getString("alias"); + if (alias != null) { plot.settings.setAlias(alias); } - - String pos = r.getString("position"); - if (pos!=null) { - for (PlotHomePosition plotHomePosition : PlotHomePosition.values()) { + + final String pos = r.getString("position"); + if (pos != null) { + for (final PlotHomePosition plotHomePosition : PlotHomePosition.values()) { if (plotHomePosition.isMatching(pos)) { - if (plotHomePosition!=PlotHomePosition.DEFAULT) { + if (plotHomePosition != PlotHomePosition.DEFAULT) { plot.settings.setPosition(plotHomePosition); } break; } } } - Integer m = r.getInt("merged"); - if (m!=null) { - boolean[] merged = new boolean[4]; + final Integer m = r.getInt("merged"); + if (m != null) { + final boolean[] merged = new boolean[4]; for (int i = 0; i < 4; i++) { - merged[3 - i] = (((int) m) & (1 << i)) != 0; + merged[3 - i] = ((m) & (1 << i)) != 0; } plot.settings.setMerged(merged); } else { - plot.settings.setMerged(new boolean[] {false, false, false, false}); + plot.settings.setMerged(new boolean[] { false, false, false, false }); } - + String[] flags_string; - String myflags = r.getString("flags"); + final String myflags = r.getString("flags"); if (myflags == null) { flags_string = new String[] {}; } else { flags_string = myflags.split(","); } - ArrayList flags = new ArrayList(); + final ArrayList flags = new ArrayList(); boolean exception = false; - for (int i = 0; i < flags_string.length; i++) { - if (flags_string[i].contains(":")) { - String[] split = flags_string[i].split(":"); + for (final String element : flags_string) { + if (element.contains(":")) { + final String[] split = element.split(":"); try { flags.add(new Flag(FlagManager.getFlag(split[0], true), split[1])); } - catch (Exception e) { + catch (final Exception e) { exception = true; } } else { - flags.add(new Flag(FlagManager.getFlag(flags_string[i], true), "")); + flags.add(new Flag(FlagManager.getFlag(element, true), "")); } } if (exception) { - PlotMain.sendConsoleSenderMessage("&cPlot "+id+" had an invalid flag. A fix has been attempted."); + PlotMain.sendConsoleSenderMessage("&cPlot " + id + " had an invalid flag. A fix has been attempted."); setFlags(id, flags.toArray(new Flag[0])); } plot.settings.setFlags(flags.toArray(new Flag[0])); } else { - PlotMain.sendConsoleSenderMessage("&cPLOT "+id+" in plot_settings does not exist. Please create the plot or remove this entry."); + PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_settings does not exist. Please create the plot or remove this entry."); } } stmt.close(); - for (Plot plot:plots.values()) { - String world = plot.world; + for (final Plot plot : plots.values()) { + final String world = plot.world; if (!newplots.containsKey(world)) { newplots.put(world, new HashMap()); } newplots.get(world).put(plot.id, plot); } - for (String worldname: noExist.keySet()) { - PlotMain.sendConsoleSenderMessage("&c[WARNING] Found "+noExist.get(worldname)+" plots in DB for non existant world; '"+worldname+"'!!!\n&c - Please create this world, or remove the plots from the DB using the purge command!"); - } - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to load plots."); - e.printStackTrace(); - } - return newplots; - } - - - @Override - public void setMerged(final String world, final Plot plot, final boolean[] merged) { - plot.settings.setMerged(merged); - runTask(new Runnable() { - @Override - public void run() { - try { - int n = 0; - for (int i = 0; i < 4; ++i) { - n = (n << 1) + (merged[i] ? 1 : 0); - } - PreparedStatement stmt = - connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); - stmt.setInt(1, n); - stmt.setInt(2, getId(world, plot.id)); - stmt.execute(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Could not set merged for plot " + plot.id); - } - } - }); - } - - @Override - public void setFlags(final String world, final Plot plot, final Flag[] flags) { - plot.settings.setFlags(flags); - final StringBuilder flag_string = new StringBuilder(); - int i = 0; - for (Flag flag : flags) { - if (i != 0) { - flag_string.append(","); - } - flag_string.append(flag.getKey() + ":" + flag.getValue()); - i++; - } - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement stmt = - connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); - stmt.setString(1, flag_string.toString()); - stmt.setInt(2, getId(world, plot.id)); - stmt.execute(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Could not set flag for plot " + plot.id); - } - } - }); - } - - public void setFlags(final int id, final Flag[] flags) { - ArrayList newflags = new ArrayList(); - for (Flag flag : flags) { - if (flag!=null && flag.getKey()!=null && !flag.getKey().equals("")) { - newflags.add(flag); + for (final String worldname : noExist.keySet()) { + PlotMain.sendConsoleSenderMessage("&c[WARNING] Found " + noExist.get(worldname) + " plots in DB for non existant world; '" + worldname + "'!!!\n&c - Please create this world, or remove the plots from the DB using the purge command!"); } } - final String flag_string = StringUtils.join(newflags,","); + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to load plots."); + e.printStackTrace(); + } + return newplots; + } + + @Override + public void setMerged(final String world, final Plot plot, final boolean[] merged) { + plot.settings.setMerged(merged); runTask(new Runnable() { @Override public void run() { try { - PreparedStatement stmt = - connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); + int n = 0; + for (int i = 0; i < 4; ++i) { + n = (n << 1) + (merged[i] ? 1 : 0); + } + final PreparedStatement stmt = connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); + stmt.setInt(1, n); + stmt.setInt(2, getId(world, plot.id)); + stmt.execute(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "Could not set merged for plot " + plot.id); + } + } + }); + } + + @Override + public void setFlags(final String world, final Plot plot, final Flag[] flags) { + plot.settings.setFlags(flags); + final StringBuilder flag_string = new StringBuilder(); + int i = 0; + for (final Flag flag : flags) { + if (i != 0) { + flag_string.append(","); + } + flag_string.append(flag.getKey() + ":" + flag.getValue()); + i++; + } + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement stmt = connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); + stmt.setString(1, flag_string.toString()); + stmt.setInt(2, getId(world, plot.id)); + stmt.execute(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "Could not set flag for plot " + plot.id); + } + } + }); + } + + public void setFlags(final int id, final Flag[] flags) { + final ArrayList newflags = new ArrayList(); + for (final Flag flag : flags) { + if ((flag != null) && (flag.getKey() != null) && !flag.getKey().equals("")) { + newflags.add(flag); + } + } + final String flag_string = StringUtils.join(newflags, ","); + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement stmt = connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); stmt.setString(1, flag_string); stmt.setInt(2, id); stmt.execute(); stmt.close(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); Logger.add(LogLevel.WARNING, "Could not set flag for plot " + id); } @@ -712,261 +688,258 @@ public class SQLManager extends AbstractDB { }); } - /** - * @param plot - * @param alias - */ - @Override - public void setAlias(final String world, final Plot plot, final String alias) { - plot.settings.setAlias(alias); - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - try { - stmt = - connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); - stmt.setString(1, alias); - stmt.setInt(2, getId(world, plot.id)); - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set alias for plot " + plot.id); - e.printStackTrace(); - } - - } - }); - } - - /** - * @param r - */ - private void runTask(Runnable r) { - PlotMain.getMain().getServer().getScheduler().runTaskAsynchronously(PlotMain.getMain(), r); - } - - @Override - public void purge(final String world, final PlotId id) { - runTask(new Runnable() { + /** + * @param plot + * @param alias + */ + @Override + public void setAlias(final String world, final Plot plot, final String alias) { + plot.settings.setAlias(alias); + runTask(new Runnable() { @Override public void run() { - ArrayList ids = new ArrayList(); - + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); + stmt.setString(1, alias); + stmt.setInt(2, getId(world, plot.id)); + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set alias for plot " + plot.id); + e.printStackTrace(); + } + + } + }); + } + + /** + * @param r + */ + private void runTask(final Runnable r) { + PlotMain.getMain().getServer().getScheduler().runTaskAsynchronously(PlotMain.getMain(), r); + } + + @Override + public void purge(final String world, final PlotId id) { + runTask(new Runnable() { + @Override + public void run() { + final ArrayList ids = new ArrayList(); + // Fetching a list of plot IDs for a world try { - PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" + PREFIX + "plot` WHERE `world` = ? AND `plot_id_x` = ? AND `plot_id_z` = ?"); + final PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" + PREFIX + "plot` WHERE `world` = ? AND `plot_id_x` = ? AND `plot_id_z` = ?"); stmt.setString(1, world); stmt.setInt(2, id.x); stmt.setInt(3, id.y); - ResultSet result = stmt.executeQuery(); + final ResultSet result = stmt.executeQuery(); while (result.next()) { - int id = result.getInt("id"); + final int id = result.getInt("id"); ids.add(id); } } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); - Logger.add(LogLevel.WARNING, "FAILED TO PURGE WORLD '"+world+"'!"); + Logger.add(LogLevel.WARNING, "FAILED TO PURGE WORLD '" + world + "'!"); return; } if (ids.size() > 0) { try { - + String prefix = ""; - StringBuilder idstr = new StringBuilder(""); - - for (Integer id:ids) { + final StringBuilder idstr = new StringBuilder(""); + + for (final Integer id : ids) { idstr.append(prefix + id); prefix = " OR `plot_plot_id` = "; } - - PreparedStatement stmt = connection.prepareStatement("DELETE FROM `" + PREFIX +"plot_helpers` WHERE `plot_plot_id` = "+idstr+""); + + PreparedStatement stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_helpers` WHERE `plot_plot_id` = " + idstr + ""); stmt.executeUpdate(); stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_denied` WHERE `plot_plot_id` = "+idstr+""); + + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_denied` WHERE `plot_plot_id` = " + idstr + ""); stmt.executeUpdate(); stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = "+idstr+""); + + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = " + idstr + ""); stmt.executeUpdate(); stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = "+idstr+""); + + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = " + idstr + ""); stmt.executeUpdate(); stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot` WHERE `plot_plot_id` = "+idstr+""); + + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot` WHERE `plot_plot_id` = " + idstr + ""); stmt.setString(1, world); stmt.executeUpdate(); stmt.close(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); - Logger.add(LogLevel.DANGER, "FAILED TO PURGE PLOT FROM DB '"+world+"' , '"+id+"' !"); + Logger.add(LogLevel.DANGER, "FAILED TO PURGE PLOT FROM DB '" + world + "' , '" + id + "' !"); return; } } - Logger.add(LogLevel.GENERAL, "SUCCESSFULLY PURGED PLOT FROM DB '"+world+"' , '"+id+"'!"); + Logger.add(LogLevel.GENERAL, "SUCCESSFULLY PURGED PLOT FROM DB '" + world + "' , '" + id + "'!"); } - }); - } + }); + } - @Override - public void purge(final String world) { - runTask(new Runnable() { - @Override - public void run() { - ArrayList ids = new ArrayList(); - - // Fetching a list of plot IDs for a world - try { - PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" + PREFIX + "plot` WHERE `world` = ?"); - stmt.setString(1, world); - ResultSet result = stmt.executeQuery(); - while (result.next()) { - int id = result.getInt("id"); - ids.add(id); - } - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "FAILED TO PURGE WORLD '"+world+"'!"); - return; - } - if (ids.size() > 0) { - try { - - String prefix = ""; - StringBuilder idstr = new StringBuilder(""); - - for (Integer id:ids) { - idstr.append(prefix + id); - prefix = " OR `plot_plot_id` = "; - } - - PreparedStatement stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_helpers` WHERE `plot_plot_id` = "+idstr+""); - stmt.executeUpdate(); - stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_denied` WHERE `plot_plot_id` = "+idstr+""); - stmt.executeUpdate(); - stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = "+idstr+""); + @Override + public void purge(final String world) { + runTask(new Runnable() { + @Override + public void run() { + final ArrayList ids = new ArrayList(); + + // Fetching a list of plot IDs for a world + try { + final PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" + PREFIX + "plot` WHERE `world` = ?"); + stmt.setString(1, world); + final ResultSet result = stmt.executeQuery(); + while (result.next()) { + final int id = result.getInt("id"); + ids.add(id); + } + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "FAILED TO PURGE WORLD '" + world + "'!"); + return; + } + if (ids.size() > 0) { + try { + + String prefix = ""; + final StringBuilder idstr = new StringBuilder(""); + + for (final Integer id : ids) { + idstr.append(prefix + id); + prefix = " OR `plot_plot_id` = "; + } + + PreparedStatement stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_helpers` WHERE `plot_plot_id` = " + idstr + ""); stmt.executeUpdate(); stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = "+idstr+""); + + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_denied` WHERE `plot_plot_id` = " + idstr + ""); stmt.executeUpdate(); stmt.close(); - - stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot` WHERE `world` = ?"); - stmt.setString(1, world); - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "FAILED TO PURGE WORLD '"+world+"'!"); - return; - } - } - Logger.add(LogLevel.GENERAL, "SUCCESSFULLY PURGED WORLD '"+world+"'!"); - } - }); - } - - /** - * @param plot - * @param position - */ - @Override - public void setPosition(final String world, final Plot plot, final String position) { - plot.settings.setPosition(PlotHomePosition.valueOf(position)); - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - try { - stmt = - connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); - stmt.setString(1, position); - stmt.setInt(2, getId(world, plot.id)); - stmt.executeUpdate(); - stmt.close(); - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set position for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } - /** - * @param id - * @return - */ - @Override - public HashMap getSettings(int id) { - HashMap h = new HashMap(); - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("SELECT * FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - ResultSet r = stmt.executeQuery(); - String var; - Object val; - while (r.next()) { - var = "biome"; - val = r.getObject(var); - h.put(var, val); - var = "rain"; - val = r.getObject(var); - h.put(var, val); - var = "custom_time"; - val = r.getObject(var); - h.put(var, val); - var = "time"; - val = r.getObject(var); - h.put(var, val); - var = "deny_entry"; - val = r.getObject(var); - h.put(var, (short) 0); - var = "alias"; - val = r.getObject(var); - h.put(var, val); - var = "position"; - val = r.getObject(var); - h.put(var, val); - var = "flags"; - val = r.getObject(var); - h.put(var, val); - var = "merged"; - val = r.getObject(var); - h.put(var, val); - } - stmt.close(); - ; - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to load settings for plot: " + id); - e.printStackTrace(); - } - return h; - } + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = " + idstr + ""); + stmt.executeUpdate(); + stmt.close(); - @Override + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = " + idstr + ""); + stmt.executeUpdate(); + stmt.close(); + + stmt = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot` WHERE `world` = ?"); + stmt.setString(1, world); + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "FAILED TO PURGE WORLD '" + world + "'!"); + return; + } + } + Logger.add(LogLevel.GENERAL, "SUCCESSFULLY PURGED WORLD '" + world + "'!"); + } + }); + } + + /** + * @param plot + * @param position + */ + @Override + public void setPosition(final String world, final Plot plot, final String position) { + plot.settings.setPosition(PlotHomePosition.valueOf(position)); + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement("UPDATE `" + PREFIX + "plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); + stmt.setString(1, position); + stmt.setInt(2, getId(world, plot.id)); + stmt.executeUpdate(); + stmt.close(); + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set position for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } + + /** + * @param id + * @return + */ + @Override + public HashMap getSettings(final int id) { + final HashMap h = new HashMap(); + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement("SELECT * FROM `" + PREFIX + "plot_settings` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + final ResultSet r = stmt.executeQuery(); + String var; + Object val; + while (r.next()) { + var = "biome"; + val = r.getObject(var); + h.put(var, val); + var = "rain"; + val = r.getObject(var); + h.put(var, val); + var = "custom_time"; + val = r.getObject(var); + h.put(var, val); + var = "time"; + val = r.getObject(var); + h.put(var, val); + var = "deny_entry"; + val = r.getObject(var); + h.put(var, (short) 0); + var = "alias"; + val = r.getObject(var); + h.put(var, val); + var = "position"; + val = r.getObject(var); + h.put(var, val); + var = "flags"; + val = r.getObject(var); + h.put(var, val); + var = "merged"; + val = r.getObject(var); + h.put(var, val); + } + stmt.close(); + ; + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to load settings for plot: " + id); + e.printStackTrace(); + } + return h; + } + + @Override public void removeComment(final String world, final Plot plot, final PlotComment comment) { runTask(new Runnable() { @Override public void run() { try { - PreparedStatement statement = - connection.prepareStatement("DELETE FROM `"+PREFIX+"plot_comments` WHERE `plot_plot_id` = ? AND `comment` = ? AND `tier` = ? AND `sender` = ?"); + final PreparedStatement statement = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_comments` WHERE `plot_plot_id` = ? AND `comment` = ? AND `tier` = ? AND `sender` = ?"); statement.setInt(1, getId(world, plot.id)); statement.setString(2, comment.comment); statement.setInt(3, comment.tier); @@ -974,7 +947,7 @@ public class SQLManager extends AbstractDB { statement.executeUpdate(); statement.close(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); Logger.add(LogLevel.WARNING, "Failed to remove helper for plot " + plot.id); } @@ -982,40 +955,37 @@ public class SQLManager extends AbstractDB { }); } - @Override - public ArrayList getComments(String world, Plot plot, int tier) { - ArrayList comments = new ArrayList(); + public ArrayList getComments(final String world, final Plot plot, final int tier) { + final ArrayList comments = new ArrayList(); try { - PreparedStatement statement = - connection.prepareStatement("SELECT `*` FROM `" + PREFIX + "plot_comments` WHERE `plot_plot_id` = ? AND `tier` = ?"); + final PreparedStatement statement = connection.prepareStatement("SELECT `*` FROM `" + PREFIX + "plot_comments` WHERE `plot_plot_id` = ? AND `tier` = ?"); statement.setInt(1, getId(plot.getWorld().getName(), plot.id)); statement.setInt(2, tier); - ResultSet set = statement.executeQuery(); + final ResultSet set = statement.executeQuery(); PlotComment comment; while (set.next()) { - String sender = set.getString("sender"); - String msg = set.getString("comment"); + final String sender = set.getString("sender"); + final String msg = set.getString("comment"); comment = new PlotComment(msg, sender, tier); comments.add(comment); } statement.close(); } - catch (SQLException e) { + catch (final SQLException e) { Logger.add(LogLevel.WARNING, "Failed to fetch rating for plot " + plot.getId().toString()); e.printStackTrace(); } return comments; } - + @Override public void setComment(final String world, final Plot plot, final PlotComment comment) { runTask(new Runnable() { @Override public void run() { try { - PreparedStatement statement = - connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_comments` (`plot_plot_id`, `comment`, `tier`, `sender`) VALUES(?,?,?,?)"); + final PreparedStatement statement = connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_comments` (`plot_plot_id`, `comment`, `tier`, `sender`) VALUES(?,?,?,?)"); statement.setInt(1, getId(world, plot.id)); statement.setString(2, comment.comment); statement.setInt(3, comment.tier); @@ -1023,184 +993,177 @@ public class SQLManager extends AbstractDB { statement.executeUpdate(); statement.close(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); Logger.add(LogLevel.WARNING, "Failed to remove helper for plot " + plot.id); } } }); - + } - - /** - * @param plot - * @param player - */ - @Override - public void removeHelper(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement("DELETE FROM `"+PREFIX+"plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Failed to remove helper for plot " + plot.id); - } - } - }); - } - /** - * @param plot - * @param player - */ - @Override - public void removeTrusted(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement("DELETE FROM `"+PREFIX+"plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Failed to remove trusted user for plot " + plot.id); - } - } - }); - } + /** + * @param plot + * @param player + */ + @Override + public void removeHelper(final String world, final Plot plot, final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "Failed to remove helper for plot " + plot.id); + } + } + }); + } - /** - * @param plot - * @param player - */ - @Override - public void setHelper(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set helper for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + /** + * @param plot + * @param player + */ + @Override + public void removeTrusted(final String world, final Plot plot, final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "Failed to remove trusted user for plot " + plot.id); + } + } + }); + } - /** - * @param plot - * @param player - */ - @Override - public void setTrusted(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set plot trusted for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + /** + * @param plot + * @param player + */ + @Override + public void setHelper(final String world, final Plot plot, final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set helper for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } - /** - * @param plot - * @param player - */ - @Override - public void removeDenied(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Failed to remove denied for plot " + plot.id); - } - } - }); - } + /** + * @param plot + * @param player + */ + @Override + public void setTrusted(final String world, final Plot plot, final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set plot trusted for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } - /** - * @param plot - * @param player - */ - @Override - public void setDenied(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = - connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set denied for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + /** + * @param plot + * @param player + */ + @Override + public void removeDenied(final String world, final Plot plot, final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement("DELETE FROM `" + PREFIX + "plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "Failed to remove denied for plot " + plot.id); + } + } + }); + } - @Override - public double getRatings(final Plot plot) { - try { - PreparedStatement statement = - connection.prepareStatement("SELECT AVG(`rating`) AS `rating` FROM `" + PREFIX + "plot_ratings` WHERE `plot_plot_id` = ? "); - statement.setInt(1, getId(plot.getWorld().getName(), plot.id)); - ResultSet set = statement.executeQuery(); - double rating = 0; - while (set.next()) { - rating = set.getDouble("rating"); - } - statement.close(); - return rating; - } - catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to fetch rating for plot " + plot.getId().toString()); - e.printStackTrace(); - } - return 0.0d; - } + /** + * @param plot + * @param player + */ + @Override + public void setDenied(final String world, final Plot plot, final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + final PreparedStatement statement = connection.prepareStatement("INSERT INTO `" + PREFIX + "plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set denied for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } + + @Override + public double getRatings(final Plot plot) { + try { + final PreparedStatement statement = connection.prepareStatement("SELECT AVG(`rating`) AS `rating` FROM `" + PREFIX + "plot_ratings` WHERE `plot_plot_id` = ? "); + statement.setInt(1, getId(plot.getWorld().getName(), plot.id)); + final ResultSet set = statement.executeQuery(); + double rating = 0; + while (set.next()) { + rating = set.getDouble("rating"); + } + statement.close(); + return rating; + } + catch (final SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to fetch rating for plot " + plot.getId().toString()); + e.printStackTrace(); + } + return 0.0d; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLite.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLite.java index 78fe58323..4307234e1 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLite.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/SQLite.java @@ -19,88 +19,86 @@ import org.bukkit.plugin.Plugin; */ public class SQLite extends Database { - private Connection connection; - private final String dbLocation; + private Connection connection; + private final String dbLocation; - /** - * Creates a new SQLite instance - * - * @param plugin - * Plugin instance - * @param dbLocation - * Location of the Database (Must end in .db) - */ - public SQLite(Plugin plugin, String dbLocation) { - super(plugin); - this.dbLocation = dbLocation; - } + /** + * Creates a new SQLite instance + * + * @param plugin + * Plugin instance + * @param dbLocation + * Location of the Database (Must end in .db) + */ + public SQLite(final Plugin plugin, final String dbLocation) { + super(plugin); + this.dbLocation = dbLocation; + } - @Override - public Connection openConnection() throws SQLException, ClassNotFoundException { - if (checkConnection()) { - return this.connection; - } - if (!this.plugin.getDataFolder().exists()) { - this.plugin.getDataFolder().mkdirs(); - } - File file = new File(this.plugin.getDataFolder(), this.dbLocation); - if (!(file.exists())) { - try { - file.createNewFile(); - } - catch (IOException e) { - this.plugin.getLogger().log(Level.SEVERE, "Unable to create database!"); - } - } - Class.forName("org.sqlite.JDBC"); - this.connection = - DriverManager.getConnection("jdbc:sqlite:" + this.plugin.getDataFolder().toPath().toString() + "/" - + this.dbLocation); - return this.connection; - } + @Override + public Connection openConnection() throws SQLException, ClassNotFoundException { + if (checkConnection()) { + return this.connection; + } + if (!this.plugin.getDataFolder().exists()) { + this.plugin.getDataFolder().mkdirs(); + } + final File file = new File(this.plugin.getDataFolder(), this.dbLocation); + if (!(file.exists())) { + try { + file.createNewFile(); + } + catch (final IOException e) { + this.plugin.getLogger().log(Level.SEVERE, "Unable to create database!"); + } + } + Class.forName("org.sqlite.JDBC"); + this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.plugin.getDataFolder().toPath().toString() + "/" + this.dbLocation); + return this.connection; + } - @Override - public boolean checkConnection() throws SQLException { - return (this.connection != null) && !this.connection.isClosed(); - } + @Override + public boolean checkConnection() throws SQLException { + return (this.connection != null) && !this.connection.isClosed(); + } - @Override - public Connection getConnection() { - return this.connection; - } + @Override + public Connection getConnection() { + return this.connection; + } - @Override - public boolean closeConnection() throws SQLException { - if (this.connection == null) { - return false; - } - this.connection.close(); - return true; - } + @Override + public boolean closeConnection() throws SQLException { + if (this.connection == null) { + return false; + } + this.connection.close(); + return true; + } - @Override - public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public ResultSet querySQL(final String query) throws SQLException, ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + final Statement statement = this.connection.createStatement(); - ResultSet result = statement.executeQuery(query); + final ResultSet result = statement.executeQuery(query); - return result; - } + return result; + } - @Override - public int updateSQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public int updateSQL(final String query) throws SQLException, ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + final Statement statement = this.connection.createStatement(); - int result = statement.executeUpdate(query); + final int result = statement.executeUpdate(query); - return result; - } + return result; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/PlotTable.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/PlotTable.java index d74e95675..28e3ee383 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/PlotTable.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/PlotTable.java @@ -12,6 +12,6 @@ public class PlotTable extends SQLTable { @Override public void create() { // TODO Auto-generated method stub - + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLField.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLField.java index 86526e392..f0dbcb866 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLField.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLField.java @@ -5,10 +5,10 @@ package com.intellectualcrafters.plot.database.sqlobjects; */ public class SQLField { - private SQLType type; - private Object value; + private final SQLType type; + private final Object value; - public SQLField(SQLType type, Object value) { + public SQLField(final SQLType type, final Object value) { this.type = type; this.value = value; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLTable.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLTable.java index 2aa281d3f..793482490 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLTable.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLTable.java @@ -7,14 +7,12 @@ import com.intellectualcrafters.plot.Settings; */ public abstract class SQLTable { - private String name; - private SQLField[] fields; - private String primaryKey; - - public SQLTable(String name, String primaryKey, SQLField ... fields) { + private final String name; + private final SQLField[] fields; + + public SQLTable(final String name, final String primaryKey, final SQLField... fields) { this.name = Settings.DB.PREFIX + name; this.fields = fields; - this.primaryKey = primaryKey; } @Override @@ -26,23 +24,6 @@ public abstract class SQLTable { return this.fields; } - private void createFromFields() { - StringBuilder statement = new StringBuilder(); - statement.append("CREATE TABLE `" + name + "` IF NOT EXISTS ("); - for(SQLField field : fields) { - switch(field.getType()) { - case INTEGER: - break; - case VARCHAR: - break; - case BOOL: - break; - default: - break; - } - } - } - public abstract void create(); } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLType.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLType.java index 97f067ebc..0ba15305e 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLType.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/database/sqlobjects/SQLType.java @@ -11,10 +11,10 @@ public enum SQLType { private Object defaultValue; private String sqlName; - private Class javaClass; - private int length; + private Class javaClass; + private int length; - SQLType(Object defaultValue, String sqlName, Class javaClass, int length) { + SQLType(final Object defaultValue, final String sqlName, final Class javaClass, final int length) { this.defaultValue = defaultValue; this.sqlName = sqlName; this.javaClass = javaClass; @@ -24,6 +24,7 @@ public enum SQLType { public int getLength() { return this.length; } + @Override public String toString() { return this.sqlName; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java index f6345e3e4..5d3bdc384 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerClaimPlotEvent.java >> Generated by: Citymonstret at * 2014-08-09 15:21 */ @@ -20,47 +20,47 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-09. */ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private Plot plot; + private final Plot plot; - /** - * PlayerClaimPlotEvent: Called when a plot is claimed - * - * @param player - * @param plot - */ - public PlayerClaimPlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } + /** + * PlayerClaimPlotEvent: Called when a plot is claimed + * + * @param player + * @param plot + */ + public PlayerClaimPlotEvent(final Player player, final Plot plot) { + super(player); + this.plot = plot; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java index 026bc4027..00a93ffc1 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java @@ -11,29 +11,29 @@ import com.intellectualcrafters.plot.Plot; */ public class PlayerEnterPlotEvent extends PlayerEvent { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; + private final Plot plot; - /** - * PlayerEnterPlotEvent: Called when a player leaves a plot - * - * @param player - * @param plot - */ - public PlayerEnterPlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } + /** + * PlayerEnterPlotEvent: Called when a player leaves a plot + * + * @param player + * @param plot + */ + public PlayerEnterPlotEvent(final Player player, final Plot plot) { + super(player); + this.plot = plot; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } public static HandlerList getHandlerList() { return handlers; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java index 9eb41c20c..c0b19e6c8 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java @@ -10,29 +10,29 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-16. */ public class PlayerLeavePlotEvent extends PlayerEvent { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; + private final Plot plot; - /** - * PlayerLeavePlotEvent: Called when a player leaves a plot - * - * @param player - * @param plot - */ - public PlayerLeavePlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } + /** + * PlayerLeavePlotEvent: Called when a player leaves a plot + * + * @param player + * @param plot + */ + public PlayerLeavePlotEvent(final Player player, final Plot plot) { + super(player); + this.plot = plot; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } public static HandlerList getHandlerList() { return handlers; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java index c53eb260a..d0d346e4d 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java @@ -1,74 +1,75 @@ package com.intellectualcrafters.plot.events; -import com.intellectualcrafters.plot.Plot; +import java.util.UUID; + import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import java.util.UUID; +import com.intellectualcrafters.plot.Plot; /** * Created by Citymonstret on 2014-08-16. */ public class PlayerPlotDeniedEvent extends Event { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; - private Player initiator; - private boolean added; - private UUID player; + private final Plot plot; + private final Player initiator; + private final boolean added; + private final UUID player; - /** - * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a - * plot - * - * @param initiator - * @param plot - * @param player - * @param added - */ - public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) { - this.initiator = initiator; - this.plot = plot; - this.added = added; - this.player = player; - } + /** + * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a + * plot + * + * @param initiator + * @param plot + * @param player + * @param added + */ + public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { + this.initiator = initiator; + this.plot = plot; + this.added = added; + this.player = player; + } - /** - * If a user was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } + /** + * If a user was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } - /** - * The player added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } + /** + * The player added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } - /** - * The plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * The plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } public static HandlerList getHandlerList() { return handlers; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java index 2bf20938b..14d71f866 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java @@ -1,73 +1,74 @@ package com.intellectualcrafters.plot.events; -import com.intellectualcrafters.plot.Plot; +import java.util.UUID; + import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import java.util.UUID; +import com.intellectualcrafters.plot.Plot; /** * Created by Citymonstret on 2014-08-16. */ public class PlayerPlotHelperEvent extends Event { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; - private Player initiator; - private boolean added; - private UUID player; + private final Plot plot; + private final Player initiator; + private final boolean added; + private final UUID player; - /** - * PlayerPlotHelperEvent: Called when a plot helper is added/removed - * - * @param initiator - * @param plot - * @param player - * @param added - */ - public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) { - this.initiator = initiator; - this.plot = plot; - this.added = added; - this.player = player; - } + /** + * PlayerPlotHelperEvent: Called when a plot helper is added/removed + * + * @param initiator + * @param plot + * @param player + * @param added + */ + public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { + this.initiator = initiator; + this.plot = plot; + this.added = added; + this.player = player; + } - /** - * If a player was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } + /** + * If a player was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } - /** - * The UUID added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } + /** + * The UUID added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } - /** - * The plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * The plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } public static HandlerList getHandlerList() { return handlers; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java index 5510bb3a0..ea91c7bd8 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java @@ -1,73 +1,74 @@ package com.intellectualcrafters.plot.events; -import com.intellectualcrafters.plot.Plot; +import java.util.UUID; + import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import java.util.UUID; +import com.intellectualcrafters.plot.Plot; /** * Created by Citymonstret on 2014-08-16. */ public class PlayerPlotTrustedEvent extends Event { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; - private Player initiator; - private boolean added; - private UUID player; + private final Plot plot; + private final Player initiator; + private final boolean added; + private final UUID player; - /** - * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed - * - * @param initiator - * @param plot - * @param player - * @param added - */ - public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) { - this.initiator = initiator; - this.plot = plot; - this.added = added; - this.player = player; - } + /** + * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed + * + * @param initiator + * @param plot + * @param player + * @param added + */ + public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) { + this.initiator = initiator; + this.plot = plot; + this.added = added; + this.player = player; + } - /** - * If a player was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } + /** + * If a player was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } - /** - * The UUID added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } + /** + * The UUID added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } - /** - * The plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * The plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } public static HandlerList getHandlerList() { return handlers; diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java index 6ab6acc8d..ec34e20e8 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerTeleportToPlotEvent.java >> Generated by: Citymonstret at * 2014-08-09 14:57 */ @@ -21,60 +21,60 @@ import com.intellectualcrafters.plot.Plot; * Called when a player teleports to a plot */ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private Location from; - private Plot plot; + private final Location from; + private final Plot plot; - private boolean cancelled; + private boolean cancelled; - /** - * PlayerTeleportToPlotEvent: Called when a player teleports to a plot - * - * @param player - * @param from - * @param plot - */ - public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { - super(player); - this.from = from; - this.plot = plot; - } + /** + * PlayerTeleportToPlotEvent: Called when a player teleports to a plot + * + * @param player + * @param from + * @param plot + */ + public PlayerTeleportToPlotEvent(final Player player, final Location from, final Plot plot) { + super(player); + this.from = from; + this.plot = plot; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - /** - * Get the from location - * - * @return Location - */ - public Location getFrom() { - return this.from; - } + /** + * Get the from location + * + * @return Location + */ + public Location getFrom() { + return this.from; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } + @Override + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotClearEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotClearEvent.java index 7ea9c3165..8b62a2e91 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotClearEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotClearEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlotClearEvent.java >> Generated by: Citymonstret at 2014-08-09 * 15:21 */ @@ -19,57 +19,57 @@ import com.intellectualcrafters.plot.PlotId; * Called when a plot is cleared */ public class PlotClearEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private PlotId id; - private String world; + private final PlotId id; + private final String world; - /** - * PlotDeleteEvent: Called when a plot is cleared - * - * @param world - * @param id - */ - public PlotClearEvent(String world, PlotId id) { - this.id = id; - this.world = world; - } + /** + * PlotDeleteEvent: Called when a plot is cleared + * + * @param world + * @param id + */ + public PlotClearEvent(final String world, final PlotId id) { + this.id = id; + this.world = world; + } - /** - * Get the PlotId - * - * @return PlotId - */ - public PlotId getPlotId() { - return this.id; - } + /** + * Get the PlotId + * + * @return PlotId + */ + public PlotId getPlotId() { + return this.id; + } - /** - * Get the world name - * - * @return String - */ - public String getWorld() { - return this.world; - } + /** + * Get the world name + * + * @return String + */ + public String getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotDeleteEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotDeleteEvent.java index e605bba35..b510c3cc3 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotDeleteEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotDeleteEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlotDeleteEvent.java >> Generated by: Citymonstret at 2014-08-09 * 15:21 */ @@ -19,57 +19,57 @@ import com.intellectualcrafters.plot.PlotId; * Called when a plot is deleted */ public class PlotDeleteEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private PlotId id; - private String world; + private final PlotId id; + private final String world; - /** - * PlotDeleteEvent: Called when a plot is deleted - * - * @param world - * @param id - */ - public PlotDeleteEvent(String world, PlotId id) { - this.id = id; - this.world = world; - } + /** + * PlotDeleteEvent: Called when a plot is deleted + * + * @param world + * @param id + */ + public PlotDeleteEvent(final String world, final PlotId id) { + this.id = id; + this.world = world; + } - /** - * Get the PlotId - * - * @return PlotId - */ - public PlotId getPlotId() { - return this.id; - } + /** + * Get the PlotId + * + * @return PlotId + */ + public PlotId getPlotId() { + return this.id; + } - /** - * Get the world name - * - * @return String - */ - public String getWorld() { - return this.world; - } + /** + * Get the world name + * + * @return String + */ + public String getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java index 16ffada92..11193eae3 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerClaimPlotEvent.java >> Generated by: Citymonstret at * 2014-08-09 15:21 */ @@ -20,57 +20,57 @@ import com.intellectualcrafters.plot.Plot; * Called when a Flag is added to a plot */ public class PlotFlagAddEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private Plot plot; - private Flag flag; + private final Plot plot; + private final Flag flag; - /** - * PlotFlagAddEvent: Called when a Flag is added to a plot - * - * @param flag - * @param plot - */ - public PlotFlagAddEvent(Flag flag, Plot plot) { - this.plot = plot; - this.flag = flag; - } + /** + * PlotFlagAddEvent: Called when a Flag is added to a plot + * + * @param flag + * @param plot + */ + public PlotFlagAddEvent(final Flag flag, final Plot plot) { + this.plot = plot; + this.flag = flag; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * Get the flag involved - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } + /** + * Get the flag involved + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java index 34294fb42..24b5b7c02 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerClaimPlotEvent.java >> Generated by: Citymonstret at * 2014-08-09 15:21 */ @@ -20,57 +20,57 @@ import com.intellectualcrafters.plot.Plot; * Called when a flag is removed from a plot */ public class PlotFlagRemoveEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private Plot plot; - private Flag flag; + private final Plot plot; + private final Flag flag; - /** - * PlotFlagRemoveEvent: Called when a flag is removed from a plot - * - * @param flag - * @param plot - */ - public PlotFlagRemoveEvent(Flag flag, Plot plot) { - this.plot = plot; - this.flag = flag; - } + /** + * PlotFlagRemoveEvent: Called when a flag is removed from a plot + * + * @param flag + * @param plot + */ + public PlotFlagRemoveEvent(final Flag flag, final Plot plot) { + this.plot = plot; + this.flag = flag; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * Get the flag involved - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } + /** + * Get the flag involved + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotMergeEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotMergeEvent.java index 8335054c5..b6f4e34cc 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotMergeEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotMergeEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerClaimPlotEvent.java >> Generated by: Citymonstret at * 2014-08-09 15:21 */ @@ -23,61 +23,61 @@ import com.intellectualcrafters.plot.PlotId; * Created by Citymonstret on 2014-08-09. */ public class PlotMergeEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private ArrayList plots; - private Plot plot; - private World world; + private final ArrayList plots; + private Plot plot; + private World world; - /** - * PlotMergeEvent: Called when plots are merged - * - * @param player - * @param plot - */ - public PlotMergeEvent(World world, Plot plot, ArrayList plots) { - this.plots = plots; - } + /** + * PlotMergeEvent: Called when plots are merged + * + * @param player + * @param plot + */ + public PlotMergeEvent(final World world, final Plot plot, final ArrayList plots) { + this.plots = plots; + } - /** - * Get the plots being added; - * - * @return Plot - */ - public ArrayList getPlots() { - return this.plots; - } + /** + * Get the plots being added; + * + * @return Plot + */ + public ArrayList getPlots() { + return this.plots; + } - /** - * Get the main plot - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the main plot + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - public World getWorld() { - return this.world; - } + public World getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java index 5197a7ca5..0f07856df 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java @@ -2,7 +2,7 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerClaimPlotEvent.java >> Generated by: Citymonstret at * 2014-08-09 15:21 */ @@ -22,52 +22,52 @@ import com.intellectualcrafters.plot.PlotId; * Created by Citymonstret on 2014-08-09. */ public class PlotUnlinkEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private ArrayList plots; - private World world; + private final ArrayList plots; + private final World world; - /** - * Called when a mega-plot is unlinked. - * - * @param world - * @param plots - */ - public PlotUnlinkEvent(World world, ArrayList plots) { - this.plots = plots; - this.world = world; - } + /** + * Called when a mega-plot is unlinked. + * + * @param world + * @param plots + */ + public PlotUnlinkEvent(final World world, final ArrayList plots) { + this.plots = plots; + this.world = world; + } - /** - * Get the plots involved - * - * @return PlotId - */ - public ArrayList getPlots() { - return this.plots; - } + /** + * Get the plots involved + * + * @return PlotId + */ + public ArrayList getPlots() { + return this.plots; + } - public World getWorld() { - return this.world; - } + public World getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(final boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotManager.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotManager.java index 2cb51e7b2..4a4862a42 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotManager.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotManager.java @@ -1,658 +1,663 @@ package com.intellectualcrafters.plot.generator; -import com.intellectualcrafters.plot.*; +import java.util.ArrayList; + import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; -import java.util.ArrayList; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotBlock; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotManager; +import com.intellectualcrafters.plot.PlotWorld; public class DefaultPlotManager extends PlotManager { - /** - * Default implementation of getting a plot at a given location For a - * simplified explanation of the math involved: - Get the current coords - - * shift these numbers down to something relatable for a single plot - * (similar to reducing trigonometric functions down to the first quadrant) - * - e.g. If the plot size is 20 blocks, and we are at x=25, it's equivalent - * to x=5 for that specific plot From this, and knowing how thick the road - * is, we can say whether x=5 is road, or plot. The number of shifts done, - * is also counted, and this number gives us the PlotId - */ - @Override - public PlotId getPlotIdAbs(PlotWorld plotworld, Location loc) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + /** + * Default implementation of getting a plot at a given location For a + * simplified explanation of the math involved: - Get the current coords - + * shift these numbers down to something relatable for a single plot + * (similar to reducing trigonometric functions down to the first quadrant) + * - e.g. If the plot size is 20 blocks, and we are at x=25, it's equivalent + * to x=5 for that specific plot From this, and knowing how thick the road + * is, we can say whether x=5 is road, or plot. The number of shifts done, + * is also counted, and this number gives us the PlotId + */ + @Override + public PlotId getPlotIdAbs(final PlotWorld plotworld, final Location loc) { + final DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - // get x,z loc - int x = loc.getBlockX(); - int z = loc.getBlockZ(); + // get x,z loc + int x = loc.getBlockX(); + int z = loc.getBlockZ(); - // get plot size - int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; + // get plot size + final int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; - // get size of path on bottom part, and top part of plot - // (As 0,0 is in the middle of a road, not the very start) - int pathWidthLower; - if ((dpw.ROAD_WIDTH % 2) == 0) { - pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); - } - else { - pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); - } - - // calulating how many shifts need to be done - int dx = x / size; - int dz = z / size; - if (x < 0) { - dx--; - x += ((-dx) * size); - } - if (z < 0) { - dz--; - z += ((-dz) * size); - } - - // reducing to first plot - int rx = (x) % size; - int rz = (z) % size; - - // checking if road (return null if so) - int end = pathWidthLower + dpw.PLOT_WIDTH; - boolean northSouth = (rz <= pathWidthLower) || (rz > end); - boolean eastWest = (rx <= pathWidthLower) || (rx > end); - if (northSouth || eastWest) { - return null; - } - // returning the plot id (based on the number of shifts required) - return new PlotId(dx + 1, dz + 1); - } - - /** - * Some complex stuff for traversing mega plots (return getPlotIdAbs if you - * do not support mega plots) - */ - @Override - public PlotId getPlotId(PlotWorld plotworld, Location loc) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - int x = loc.getBlockX(); - int z = loc.getBlockZ(); - - if (plotworld == null) { - return null; - } - int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; - int pathWidthLower; - if ((dpw.ROAD_WIDTH % 2) == 0) { - pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); - } - else { - pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); - } - - int dx = x / size; - int dz = z / size; - - if (x < 0) { - dx--; - x += ((-dx) * size); - } - if (z < 0) { - dz--; - z += ((-dz) * size); - } - - int rx = (x) % size; - int rz = (z) % size; - - int end = pathWidthLower + dpw.PLOT_WIDTH; - - boolean northSouth = (rz <= pathWidthLower) || (rz > end); - boolean eastWest = (rx <= pathWidthLower) || (rx > end); - if (northSouth && eastWest) { - // This means you are in the intersection - PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, dpw.ROAD_WIDTH)); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return null; - } - if ((plot.settings.getMerged(0) && plot.settings.getMerged(3))) { - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - return null; - } - if (northSouth) { - // You are on a road running West to East (yeah, I named the var - // poorly) - PlotId id = PlayerFunctions.getPlotAbs(loc.add(0, 0, dpw.ROAD_WIDTH)); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return null; - } - if (plot.settings.getMerged(0)) { - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - return null; - } - if (eastWest) { - // This is the road separating an Eastern and Western plot - PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, 0)); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return null; - } - if (plot.settings.getMerged(3)) { - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - return null; - } - PlotId id = new PlotId(dx + 1, dz + 1); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return id; - } - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - - /** - * Check if a location is inside a specific plot(non-Javadoc) - For this - * implementation, we don't need to do anything fancier than referring to - * getPlotIdAbs(...) - */ - @Override - public boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid) { - PlotId result = getPlotIdAbs(plotworld, loc); - if (result == null) { - return false; - } - return result == plotid; - } - - /** - * Get the bottom plot loc (some basic math) - */ - @Override - public Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - int px = plotid.x; - int pz = plotid.y; - - int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - - return new Location(Bukkit.getWorld(plotworld.worldname), x, 1, z); - } - - /** - * Get the top plot loc (some basic math) - */ - @Override - public Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - int px = plotid.x; - int pz = plotid.y; - - int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - - return new Location(Bukkit.getWorld(plotworld.worldname), x, 256, z); - } - - /** - * Clearing the plot needs to only consider removing the blocks - This - * implementation has used the SetCuboid function, as it is fast, and uses - * NMS code - It also makes use of the fact that deleting chunks is a lot - * faster than block updates This code is very messy, but you don't need to - * do something quite as complex unless you happen to have 512x512 sized - * plots - */ - @Override - public boolean clearPlot(World world, Plot plot) { - - // TODO LOAD CHUNKS TO CLEAR IT PROPERLY - - - DefaultPlotWorld dpw = ((DefaultPlotWorld) PlotMain.getWorldSettings(world)); - - final Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add(1, 0, 1); - final Location pos2 = PlotHelper.getPlotTopLoc(world, plot.id); - - PlotBlock[] plotfloor = dpw.TOP_BLOCK; - PlotBlock[] filling = dpw.MAIN_BLOCK; - - //PlotBlock wall = dpw.WALL_BLOCK; - PlotBlock wall = plot.hasOwner() ? dpw.CLAIMED_WALL_BLOCK : dpw.WALL_BLOCK; - - PlotBlock wall_filling = dpw.WALL_FILLING; - - Block block = world.getBlockAt(new Location(world, pos1.getBlockX()-1, 1, pos1.getBlockZ())); - if (block.getTypeId()!=wall_filling.id || block.getData()!=wall_filling.data) { - setWallFilling(world, dpw, plot.id, wall_filling); + // get size of path on bottom part, and top part of plot + // (As 0,0 is in the middle of a road, not the very start) + int pathWidthLower; + if ((dpw.ROAD_WIDTH % 2) == 0) { + pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); } - - block = world.getBlockAt(new Location(world, pos1.getBlockX()-1, dpw.WALL_HEIGHT+1, pos1.getBlockZ())); - if (block.getTypeId()!=wall.id || block.getData()!=wall.data) { - setWall(world, dpw, plot.id, wall); + else { + pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); } - - if ((pos2.getBlockX() - pos1.getBlockX()) < 48) { - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, 1, pos2.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, world.getMaxHeight() + 1, pos2.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, pos2.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getBlockZ() + 1), plotfloor); - return true; - } - int startX = (pos1.getBlockX() / 16) * 16; - int startZ = (pos1.getBlockZ() / 16) * 16; - int chunkX = 16 + pos2.getBlockX(); - int chunkZ = 16 + pos2.getBlockZ(); - Location l1 = PlotHelper.getPlotBottomLoc(world, plot.id); - Location l2 = PlotHelper.getPlotTopLoc(world, plot.id); - int plotMinX = l1.getBlockX() + 1; - int plotMinZ = l1.getBlockZ() + 1; - int plotMaxX = l2.getBlockX(); - int plotMaxZ = l2.getBlockZ(); - Location min = null; - Location max = null; - for (int i = startX; i < chunkX; i += 16) { - for (int j = startZ; j < chunkZ; j += 16) { - Plot plot1 = PlotHelper.getCurrentPlot(new Location(world, i, 0, j)); - if ((plot1 != null) && (plot1.getId() != plot.getId())) { - break; - } - Plot plot2 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j)); - if ((plot2 != null) && (plot2.getId() != plot.getId())) { - break; - } - Plot plot3 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j + 15)); - if ((plot3 != null) && (plot3.getId() != plot.getId())) { - break; - } - Plot plot4 = PlotHelper.getCurrentPlot(new Location(world, i, 0, j + 15)); - if ((plot4 != null) && (plot4.getId() != plot.getId())) { - break; - } - Plot plot5 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j + 15)); - if ((plot5 != null) && (plot5.getId() != plot.getId())) { - break; - } - if (min == null) { - min = new Location(world, Math.max(i - 1, plotMinX), 0, Math.max(j - 1, plotMinZ)); - max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ)); - } - else - if ((max.getBlockZ() < (j + 15)) || (max.getBlockX() < (i + 15))) { - max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ)); - } - world.regenerateChunk(i / 16, j / 16); - } - } - if (min == null) { - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, 1, pos2.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, world.getMaxHeight() + 1, pos2.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, pos2.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getBlockZ() + 1), plotfloor); - } - else { + // calulating how many shifts need to be done + int dx = x / size; + int dz = z / size; + if (x < 0) { + dx--; + x += ((-dx) * size); + } + if (z < 0) { + dz--; + z += ((-dz) * size); + } - if (min.getBlockX() < plotMinX) { - min.setX(plotMinX); - } - if (min.getBlockZ() < plotMinZ) { - min.setZ(plotMinZ); - } - if (max.getBlockX() > plotMaxX) { - max.setX(plotMaxX); - } - if (max.getBlockZ() > plotMaxZ) { - max.setZ(plotMaxZ); - } + // reducing to first plot + final int rx = (x) % size; + final int rz = (z) % size; - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, plotMinZ), new Location(world, min.getBlockX() + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, plotMinZ), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, plotMinZ), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); + // checking if road (return null if so) + final int end = pathWidthLower + dpw.PLOT_WIDTH; + final boolean northSouth = (rz <= pathWidthLower) || (rz > end); + final boolean eastWest = (rx <= pathWidthLower) || (rx > end); + if (northSouth || eastWest) { + return null; + } + // returning the plot id (based on the number of shifts required) + return new PlotId(dx + 1, dz + 1); + } - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, plotMinZ), new Location(world, max.getBlockX() + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, max.getBlockX() + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, plotMinZ), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT, plotMinZ), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); + /** + * Some complex stuff for traversing mega plots (return getPlotIdAbs if you + * do not support mega plots) + */ + @Override + public PlotId getPlotId(final PlotWorld plotworld, final Location loc) { + final DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, plotMinZ), new Location(world, plotMaxX + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, plotMinZ), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, plotMinZ), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); + int x = loc.getBlockX(); + int z = loc.getBlockZ(); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, min.getBlockZ()), new Location(world, min.getBlockX() + 1, 1, max.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, min.getBlockZ()), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, max.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, min.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), plotfloor); + if (plotworld == null) { + return null; + } + final int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; + int pathWidthLower; + if ((dpw.ROAD_WIDTH % 2) == 0) { + pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); + } + else { + pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); + } - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, max.getBlockZ()), new Location(world, min.getBlockX() + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, max.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); - PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + int dx = x / size; + int dz = z / size; - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, max.getBlockZ()), new Location(world, max.getBlockX() + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, max.getBlockX() + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, max.getBlockZ()), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + if (x < 0) { + dx--; + x += ((-dx) * size); + } + if (z < 0) { + dz--; + z += ((-dz) * size); + } - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, min.getBlockZ()), new Location(world, plotMaxX + 1, 1, max.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, min.getBlockZ()), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, max.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, min.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), plotfloor); + final int rx = (x) % size; + final int rz = (z) % size; - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, max.getBlockZ()), new Location(world, plotMaxX + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, max.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); - } - return true; - } + final int end = pathWidthLower + dpw.PLOT_WIDTH; - /** - * Remove sign for a plot - */ - @Override - public Location getSignLoc(World world, PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - return new Location(world, PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX(), dpw.ROAD_HEIGHT + 1, PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1); - } + final boolean northSouth = (rz <= pathWidthLower) || (rz > end); + final boolean eastWest = (rx <= pathWidthLower) || (rx > end); + if (northSouth && eastWest) { + // This means you are in the intersection + final PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, dpw.ROAD_WIDTH)); + final Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return null; + } + if ((plot.settings.getMerged(0) && plot.settings.getMerged(3))) { + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + return null; + } + if (northSouth) { + // You are on a road running West to East (yeah, I named the var + // poorly) + final PlotId id = PlayerFunctions.getPlotAbs(loc.add(0, 0, dpw.ROAD_WIDTH)); + final Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return null; + } + if (plot.settings.getMerged(0)) { + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + return null; + } + if (eastWest) { + // This is the road separating an Eastern and Western plot + final PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, 0)); + final Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return null; + } + if (plot.settings.getMerged(3)) { + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + return null; + } + final PlotId id = new PlotId(dx + 1, dz + 1); + final Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return id; + } + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } - @Override - public boolean setFloor(World world, PlotWorld plotworld, PlotId plotid, PlotBlock[] blocks) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - final Location pos1 = PlotHelper.getPlotBottomLoc(world, plotid).add(1, 0, 1); - final Location pos2 = PlotHelper.getPlotTopLoc(world, plotid); - PlotHelper.setCuboid(world, new Location(world,pos1.getX(),dpw.PLOT_HEIGHT,pos1.getZ()), new Location(world,pos2.getX()+1,dpw.PLOT_HEIGHT+1,pos2.getZ()+1), blocks); - return true; - } - - @Override - public boolean setWallFilling(World w, PlotWorld plotworld, PlotId plotid, PlotBlock plotblock) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - if (dpw.ROAD_WIDTH==0) { + /** + * Check if a location is inside a specific plot(non-Javadoc) - For this + * implementation, we don't need to do anything fancier than referring to + * getPlotIdAbs(...) + */ + @Override + public boolean isInPlotAbs(final PlotWorld plotworld, final Location loc, final PlotId plotid) { + final PlotId result = getPlotIdAbs(plotworld, loc); + if (result == null) { return false; } - Location bottom = PlotHelper.getPlotBottomLoc(w, plotid); - Location top = PlotHelper.getPlotTopLoc(w, plotid); + return result == plotid; + } + + /** + * Get the bottom plot loc (some basic math) + */ + @Override + public Location getPlotBottomLocAbs(final PlotWorld plotworld, final PlotId plotid) { + final DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + + final int px = plotid.x; + final int pz = plotid.y; + + final int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + final int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + + return new Location(Bukkit.getWorld(plotworld.worldname), x, 1, z); + } + + /** + * Get the top plot loc (some basic math) + */ + @Override + public Location getPlotTopLocAbs(final PlotWorld plotworld, final PlotId plotid) { + final DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + + final int px = plotid.x; + final int pz = plotid.y; + + final int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + final int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + + return new Location(Bukkit.getWorld(plotworld.worldname), x, 256, z); + } + + /** + * Clearing the plot needs to only consider removing the blocks - This + * implementation has used the SetCuboid function, as it is fast, and uses + * NMS code - It also makes use of the fact that deleting chunks is a lot + * faster than block updates This code is very messy, but you don't need to + * do something quite as complex unless you happen to have 512x512 sized + * plots + */ + @Override + public boolean clearPlot(final World world, final Plot plot) { + + // TODO LOAD CHUNKS TO CLEAR IT PROPERLY + + final DefaultPlotWorld dpw = ((DefaultPlotWorld) PlotMain.getWorldSettings(world)); + + final Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add(1, 0, 1); + final Location pos2 = PlotHelper.getPlotTopLoc(world, plot.id); + + final PlotBlock[] plotfloor = dpw.TOP_BLOCK; + final PlotBlock[] filling = dpw.MAIN_BLOCK; + + // PlotBlock wall = dpw.WALL_BLOCK; + final PlotBlock wall = plot.hasOwner() ? dpw.CLAIMED_WALL_BLOCK : dpw.WALL_BLOCK; + + final PlotBlock wall_filling = dpw.WALL_FILLING; + + Block block = world.getBlockAt(new Location(world, pos1.getBlockX() - 1, 1, pos1.getBlockZ())); + if ((block.getTypeId() != wall_filling.id) || (block.getData() != wall_filling.data)) { + setWallFilling(world, dpw, plot.id, wall_filling); + } + + block = world.getBlockAt(new Location(world, pos1.getBlockX() - 1, dpw.WALL_HEIGHT + 1, pos1.getBlockZ())); + if ((block.getTypeId() != wall.id) || (block.getData() != wall.data)) { + setWall(world, dpw, plot.id, wall); + } + + if ((pos2.getBlockX() - pos1.getBlockX()) < 48) { + PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, 1, pos2.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, world.getMaxHeight() + 1, pos2.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, pos2.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getBlockZ() + 1), plotfloor); + return true; + } + final int startX = (pos1.getBlockX() / 16) * 16; + final int startZ = (pos1.getBlockZ() / 16) * 16; + final int chunkX = 16 + pos2.getBlockX(); + final int chunkZ = 16 + pos2.getBlockZ(); + final Location l1 = PlotHelper.getPlotBottomLoc(world, plot.id); + final Location l2 = PlotHelper.getPlotTopLoc(world, plot.id); + final int plotMinX = l1.getBlockX() + 1; + final int plotMinZ = l1.getBlockZ() + 1; + final int plotMaxX = l2.getBlockX(); + final int plotMaxZ = l2.getBlockZ(); + Location min = null; + Location max = null; + for (int i = startX; i < chunkX; i += 16) { + for (int j = startZ; j < chunkZ; j += 16) { + final Plot plot1 = PlotHelper.getCurrentPlot(new Location(world, i, 0, j)); + if ((plot1 != null) && (plot1.getId() != plot.getId())) { + break; + } + final Plot plot2 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j)); + if ((plot2 != null) && (plot2.getId() != plot.getId())) { + break; + } + final Plot plot3 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j + 15)); + if ((plot3 != null) && (plot3.getId() != plot.getId())) { + break; + } + final Plot plot4 = PlotHelper.getCurrentPlot(new Location(world, i, 0, j + 15)); + if ((plot4 != null) && (plot4.getId() != plot.getId())) { + break; + } + final Plot plot5 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j + 15)); + if ((plot5 != null) && (plot5.getId() != plot.getId())) { + break; + } + if (min == null) { + min = new Location(world, Math.max(i - 1, plotMinX), 0, Math.max(j - 1, plotMinZ)); + max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ)); + } + else if ((max.getBlockZ() < (j + 15)) || (max.getBlockX() < (i + 15))) { + max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ)); + } + world.regenerateChunk(i / 16, j / 16); + } + } + + if (min == null) { + PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, 1, pos2.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, world.getMaxHeight() + 1, pos2.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, pos2.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getBlockZ() + 1), plotfloor); + } + else { + + if (min.getBlockX() < plotMinX) { + min.setX(plotMinX); + } + if (min.getBlockZ() < plotMinZ) { + min.setZ(plotMinZ); + } + if (max.getBlockX() > plotMaxX) { + max.setX(plotMaxX); + } + if (max.getBlockZ() > plotMaxZ) { + max.setZ(plotMaxZ); + } + + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, plotMinZ), new Location(world, min.getBlockX() + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, plotMinZ), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, plotMinZ), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, plotMinZ), new Location(world, max.getBlockX() + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, max.getBlockX() + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, plotMinZ), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT, plotMinZ), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, plotMinZ), new Location(world, plotMaxX + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, plotMinZ), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, plotMinZ), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, min.getBlockZ()), new Location(world, min.getBlockX() + 1, 1, max.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, min.getBlockZ()), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, max.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, min.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, max.getBlockZ()), new Location(world, min.getBlockX() + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, max.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); + PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, max.getBlockZ()), new Location(world, max.getBlockX() + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, max.getBlockX() + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, max.getBlockZ()), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, min.getBlockZ()), new Location(world, plotMaxX + 1, 1, max.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, min.getBlockZ()), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, max.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, min.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, max.getBlockZ()), new Location(world, plotMaxX + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, max.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + } + return true; + } + + /** + * Remove sign for a plot + */ + @Override + public Location getSignLoc(final World world, final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + return new Location(world, PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX(), dpw.ROAD_HEIGHT + 1, PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1); + } + + @Override + public boolean setFloor(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final Location pos1 = PlotHelper.getPlotBottomLoc(world, plotid).add(1, 0, 1); + final Location pos2 = PlotHelper.getPlotTopLoc(world, plotid); + PlotHelper.setCuboid(world, new Location(world, pos1.getX(), dpw.PLOT_HEIGHT, pos1.getZ()), new Location(world, pos2.getX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getZ() + 1), blocks); + return true; + } + + @Override + public boolean setWallFilling(final World w, final PlotWorld plotworld, final PlotId plotid, final PlotBlock plotblock) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + if (dpw.ROAD_WIDTH == 0) { + return false; + } + final Location bottom = PlotHelper.getPlotBottomLoc(w, plotid); + final Location top = PlotHelper.getPlotTopLoc(w, plotid); int x, z; Block block; - + z = bottom.getBlockZ(); for (x = bottom.getBlockX(); x < (top.getBlockX() + 1); x++) { - for (int y = 1; y<= dpw.WALL_HEIGHT; y++) { + for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { block = w.getBlockAt(x, y, z); PlotHelper.setBlock(block, plotblock); } } - + x = top.getBlockX() + 1; for (z = bottom.getBlockZ(); z < (top.getBlockZ() + 1); z++) { - for (int y = 1; y<= dpw.WALL_HEIGHT; y++) { + for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { block = w.getBlockAt(x, y, z); PlotHelper.setBlock(block, plotblock); } } - + z = top.getBlockZ() + 1; for (x = top.getBlockX() + 1; x > (bottom.getBlockX() - 1); x--) { - for (int y = 1; y<= dpw.WALL_HEIGHT; y++) { + for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { block = w.getBlockAt(x, y, z); PlotHelper.setBlock(block, plotblock); } } x = bottom.getBlockX(); for (z = top.getBlockZ() + 1; z > (bottom.getBlockZ() - 1); z--) { - for (int y = 1; y<= dpw.WALL_HEIGHT; y++) { + for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { block = w.getBlockAt(x, y, z); PlotHelper.setBlock(block, plotblock); } } return true; } - - @Override - public boolean setWall(World w, PlotWorld plotworld, PlotId plotid, PlotBlock plotblock) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - if (dpw.ROAD_WIDTH==0) { + + @Override + public boolean setWall(final World w, final PlotWorld plotworld, final PlotId plotid, final PlotBlock plotblock) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + if (dpw.ROAD_WIDTH == 0) { return false; } - Location bottom = PlotHelper.getPlotBottomLoc(w, plotid); - Location top = PlotHelper.getPlotTopLoc(w, plotid); + final Location bottom = PlotHelper.getPlotBottomLoc(w, plotid); + final Location top = PlotHelper.getPlotTopLoc(w, plotid); - int x, z; + int x, z; - Block block; - z = bottom.getBlockZ(); - for (x = bottom.getBlockX(); x < (top.getBlockX() + 1); x++) { - block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } - x = top.getBlockX() + 1; - for (z = bottom.getBlockZ(); z < (top.getBlockZ() + 1); z++) { - block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } - z = top.getBlockZ() + 1; - for (x = top.getBlockX() + 1; x > (bottom.getBlockX() - 1); x--) { - block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } - x = bottom.getBlockX(); - for (z = top.getBlockZ() + 1; z > (bottom.getBlockZ() - 1); z--) { - block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } - return true; - } + Block block; + z = bottom.getBlockZ(); + for (x = bottom.getBlockX(); x < (top.getBlockX() + 1); x++) { + block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } + x = top.getBlockX() + 1; + for (z = bottom.getBlockZ(); z < (top.getBlockZ() + 1); z++) { + block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } + z = top.getBlockZ() + 1; + for (x = top.getBlockX() + 1; x > (bottom.getBlockX() - 1); x--) { + block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } + x = bottom.getBlockX(); + for (z = top.getBlockZ() + 1; z > (bottom.getBlockZ() - 1); z--) { + block = w.getBlockAt(x, dpw.WALL_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } + return true; + } - /** - * Set a plot biome - */ - @Override - public boolean setBiome(World world, Plot plot, Biome biome) { + /** + * Set a plot biome + */ + @Override + public boolean setBiome(final World world, final Plot plot, final Biome biome) { - int bottomX = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX() - 1; - int topX = PlotHelper.getPlotTopLoc(world, plot.id).getBlockX() + 1; - int bottomZ = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1; - int topZ = PlotHelper.getPlotTopLoc(world, plot.id).getBlockZ() + 1; + final int bottomX = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX() - 1; + final int topX = PlotHelper.getPlotTopLoc(world, plot.id).getBlockX() + 1; + final int bottomZ = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1; + final int topZ = PlotHelper.getPlotTopLoc(world, plot.id).getBlockZ() + 1; - for (int x = bottomX; x <= topX; x++) { - for (int z = bottomZ; z <= topZ; z++) { - world.getBlockAt(x, 0, z).setBiome(biome); - } - } + for (int x = bottomX; x <= topX; x++) { + for (int z = bottomZ; z <= topZ; z++) { + world.getBlockAt(x, 0, z).setBiome(biome); + } + } - plot.settings.setBiome(biome); - PlotMain.updatePlot(plot); - PlotHelper.refreshPlotChunks(world, plot); + plot.settings.setBiome(biome); + PlotMain.updatePlot(plot); + PlotHelper.refreshPlotChunks(world, plot); - return true; - } + return true; + } - /** - * PLOT MERGING - */ - - @Override - public boolean createRoadEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - - int sx = pos2.getBlockX() + 1; - int ex = (sx + dpw.ROAD_WIDTH) - 1; - int sz = pos1.getBlockZ() - 1; - int ez = pos2.getBlockZ() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, ex + 1, 257 + 1, ez), new PlotBlock((short) 0, (byte) 0)); - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, 1, sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.WALL_HEIGHT + 1, sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 2, ez), dpw.WALL_BLOCK); - - PlotHelper.setSimpleCuboid(w, new Location(w, ex, 1, sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 2, ez), dpw.WALL_BLOCK); - - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - - return true; - } - - @Override - public boolean createRoadSouth(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - - int sz = pos2.getBlockZ() + 1; - int ez = (sz + dpw.ROAD_WIDTH) - 1; - int sx = pos1.getBlockX() - 1; - int ex = pos2.getBlockX() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock((short) 0, (byte) 0)); - - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz), new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, sz), new Location(w, ex, dpw.WALL_HEIGHT + 2, sz + 1), dpw.WALL_BLOCK); - - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, ez), new Location(w, ex, dpw.WALL_HEIGHT + 1, ez + 1), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), new Location(w, ex, dpw.WALL_HEIGHT + 2, ez + 1), dpw.WALL_BLOCK); - - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - - return true; - } - - @Override - public boolean createRoadSouthEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - - int sx = pos2.getBlockX() + 1; - int ex = (sx + dpw.ROAD_WIDTH) - 1; - int sz = pos2.getBlockZ() + 1; - int ez = (sz + dpw.ROAD_WIDTH) - 1; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.ROAD_HEIGHT + 1, sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - - return true; - } - - @Override - public boolean removeRoadEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - - int sx = pos2.getBlockX() + 1; - int ex = (sx + dpw.ROAD_WIDTH) - 1; - int sz = pos1.getBlockZ(); - int ez = pos2.getBlockZ() + 1; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); - PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT + 1, ez + 1), dpw.TOP_BLOCK); - - return true; - } - - @Override - public boolean removeRoadSouth(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - - int sz = pos2.getBlockZ() + 1; - int ez = (sz + dpw.ROAD_WIDTH) - 1; - int sx = pos1.getBlockX(); - int ex = pos2.getBlockX() + 1; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); - PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT + 1, ez + 1), dpw.TOP_BLOCK); - - return true; - } - - @Override - public boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World world = Bukkit.getWorld(plot.world); - - Location loc = getPlotTopLocAbs(dpw, plot.id); - - int sx = loc.getBlockX() + 1; - int ex = (sx + dpw.ROAD_WIDTH) - 1; - int sz = loc.getBlockZ() + 1; - int ez = (sz + dpw.ROAD_WIDTH) - 1; - - PlotHelper.setSimpleCuboid(world, new Location(world, sx, dpw.ROAD_HEIGHT + 1, sz), new Location(world, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); - - PlotHelper.setCuboid(world, new Location(world, sx + 1, 1, sz + 1), new Location(world, ex, dpw.ROAD_HEIGHT, ez), dpw.MAIN_BLOCK); - PlotHelper.setCuboid(world, new Location(world, sx + 1, dpw.ROAD_HEIGHT, sz + 1), new Location(world, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.TOP_BLOCK); - return true; - } - - /** - * Finishing off plot merging by adding in the walls surrounding the plot - * (OPTIONAL)(UNFINISHED) - */ - @Override - public boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList plotIds) { - - // TODO set plot wall - - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - - PlotId pos1 = plotIds.get(0); - PlotId pos2 = plotIds.get(plotIds.size() - 1); - - PlotBlock block = dpw.WALL_BLOCK; - - Location megaPlotBot = PlotHelper.getPlotBottomLoc(world, pos1); - Location megaPlotTop = PlotHelper.getPlotTopLoc(world, pos2).add(1, 0, 1); - for (int x = megaPlotBot.getBlockX(); x <= megaPlotTop.getBlockX(); x++) { - for (int z = megaPlotBot.getBlockZ(); z <= megaPlotTop.getBlockZ(); z++) { - if ((z == megaPlotBot.getBlockZ()) || (z == megaPlotTop.getBlockZ()) || (x == megaPlotBot.getBlockX()) - || (x == megaPlotTop.getBlockX())) { - world.getBlockAt(x, dpw.WALL_HEIGHT + 1, z).setTypeIdAndData(block.id, block.data, false); - } - } - } - return true; - } + /** + * PLOT MERGING + */ @Override - public boolean finishPlotUnlink(World world, PlotWorld plotworld, ArrayList plotIds) { + public boolean createRoadEast(final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final World w = Bukkit.getWorld(plot.world); + + final Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + final Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + final int sx = pos2.getBlockX() + 1; + final int ex = (sx + dpw.ROAD_WIDTH) - 1; + final int sz = pos1.getBlockZ() - 1; + final int ez = pos2.getBlockZ() + 2; + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, ex + 1, 257 + 1, ez), new PlotBlock((short) 0, (byte) 0)); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, 1, sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.WALL_HEIGHT + 1, sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 2, ez), dpw.WALL_BLOCK); + + PlotHelper.setSimpleCuboid(w, new Location(w, ex, 1, sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 2, ez), dpw.WALL_BLOCK); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); + return true; } @Override - public boolean startPlotMerge(World world, PlotWorld plotworld, ArrayList plotIds) { + public boolean createRoadSouth(final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final World w = Bukkit.getWorld(plot.world); + + final Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + final Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + final int sz = pos2.getBlockZ() + 1; + final int ez = (sz + dpw.ROAD_WIDTH) - 1; + final int sx = pos1.getBlockX() - 1; + final int ex = pos2.getBlockX() + 2; + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock((short) 0, (byte) 0)); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz), new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, sz), new Location(w, ex, dpw.WALL_HEIGHT + 2, sz + 1), dpw.WALL_BLOCK); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, ez), new Location(w, ex, dpw.WALL_HEIGHT + 1, ez + 1), dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), new Location(w, ex, dpw.WALL_HEIGHT + 2, ez + 1), dpw.WALL_BLOCK); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); + return true; } @Override - public boolean startPlotUnlink(World world, PlotWorld plotworld, ArrayList plotIds) { + public boolean createRoadSouthEast(final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final World w = Bukkit.getWorld(plot.world); + + final Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + final int sx = pos2.getBlockX() + 1; + final int ex = (sx + dpw.ROAD_WIDTH) - 1; + final int sz = pos2.getBlockZ() + 1; + final int ez = (sz + dpw.ROAD_WIDTH) - 1; + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.ROAD_HEIGHT + 1, sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); + + return true; + } + + @Override + public boolean removeRoadEast(final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final World w = Bukkit.getWorld(plot.world); + + final Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + final Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + final int sx = pos2.getBlockX() + 1; + final int ex = (sx + dpw.ROAD_WIDTH) - 1; + final int sz = pos1.getBlockZ(); + final int ez = pos2.getBlockZ() + 1; + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); + PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT + 1, ez + 1), dpw.TOP_BLOCK); + + return true; + } + + @Override + public boolean removeRoadSouth(final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final World w = Bukkit.getWorld(plot.world); + + final Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + final Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + final int sz = pos2.getBlockZ() + 1; + final int ez = (sz + dpw.ROAD_WIDTH) - 1; + final int sx = pos1.getBlockX(); + final int ex = pos2.getBlockX() + 1; + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); + PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT + 1, ez + 1), dpw.TOP_BLOCK); + + return true; + } + + @Override + public boolean removeRoadSouthEast(final PlotWorld plotworld, final Plot plot) { + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + final World world = Bukkit.getWorld(plot.world); + + final Location loc = getPlotTopLocAbs(dpw, plot.id); + + final int sx = loc.getBlockX() + 1; + final int ex = (sx + dpw.ROAD_WIDTH) - 1; + final int sz = loc.getBlockZ() + 1; + final int ez = (sz + dpw.ROAD_WIDTH) - 1; + + PlotHelper.setSimpleCuboid(world, new Location(world, sx, dpw.ROAD_HEIGHT + 1, sz), new Location(world, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); + + PlotHelper.setCuboid(world, new Location(world, sx + 1, 1, sz + 1), new Location(world, ex, dpw.ROAD_HEIGHT, ez), dpw.MAIN_BLOCK); + PlotHelper.setCuboid(world, new Location(world, sx + 1, dpw.ROAD_HEIGHT, sz + 1), new Location(world, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.TOP_BLOCK); + return true; + } + + /** + * Finishing off plot merging by adding in the walls surrounding the plot + * (OPTIONAL)(UNFINISHED) + */ + @Override + public boolean finishPlotMerge(final World world, final PlotWorld plotworld, final ArrayList plotIds) { + + // TODO set plot wall + + final DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + + final PlotId pos1 = plotIds.get(0); + final PlotId pos2 = plotIds.get(plotIds.size() - 1); + + final PlotBlock block = dpw.WALL_BLOCK; + + final Location megaPlotBot = PlotHelper.getPlotBottomLoc(world, pos1); + final Location megaPlotTop = PlotHelper.getPlotTopLoc(world, pos2).add(1, 0, 1); + for (int x = megaPlotBot.getBlockX(); x <= megaPlotTop.getBlockX(); x++) { + for (int z = megaPlotBot.getBlockZ(); z <= megaPlotTop.getBlockZ(); z++) { + if ((z == megaPlotBot.getBlockZ()) || (z == megaPlotTop.getBlockZ()) || (x == megaPlotBot.getBlockX()) || (x == megaPlotTop.getBlockX())) { + world.getBlockAt(x, dpw.WALL_HEIGHT + 1, z).setTypeIdAndData(block.id, block.data, false); + } + } + } + return true; + } + + @Override + public boolean finishPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList plotIds) { + return true; + } + + @Override + public boolean startPlotMerge(final World world, final PlotWorld plotworld, final ArrayList plotIds) { + return true; + } + + @Override + public boolean startPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList plotIds) { return true; } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java index afa6333d9..50b073540 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java @@ -11,177 +11,163 @@ import com.intellectualcrafters.plot.PlotWorld; public class DefaultPlotWorld extends PlotWorld { - /* - * These variables are set to ensure fast access to config settings Strings - * are used as little as possible to optimize math performance in many of - * the functions/algorithms - */ + /* + * These variables are set to ensure fast access to config settings Strings + * are used as little as possible to optimize math performance in many of + * the functions/algorithms + */ - /** - * Road Height - */ - public int ROAD_HEIGHT; - /** - * Default Road Height: 64 - */ - public static int ROAD_HEIGHT_DEFAULT = 64; + /** + * Road Height + */ + public int ROAD_HEIGHT; + /** + * Default Road Height: 64 + */ + public static int ROAD_HEIGHT_DEFAULT = 64; - /** - * plot height - */ - public int PLOT_HEIGHT; - /** - * Default plot height: 64 - */ - public static int PLOT_HEIGHT_DEFAULT = 64; + /** + * plot height + */ + public int PLOT_HEIGHT; + /** + * Default plot height: 64 + */ + public static int PLOT_HEIGHT_DEFAULT = 64; - /** - * Wall height - */ - public int WALL_HEIGHT; - /** - * Default Wall Height: 64 - */ - public static int WALL_HEIGHT_DEFAULT = 64; + /** + * Wall height + */ + public int WALL_HEIGHT; + /** + * Default Wall Height: 64 + */ + public static int WALL_HEIGHT_DEFAULT = 64; - /** - * plot width - */ - public int PLOT_WIDTH; - /** - * Default plot width: 32 - */ - public static int PLOT_WIDTH_DEFAULT = 32; + /** + * plot width + */ + public int PLOT_WIDTH; + /** + * Default plot width: 32 + */ + public static int PLOT_WIDTH_DEFAULT = 32; - /** - * Road width - */ - public int ROAD_WIDTH; - /** - * Default road width: 7 - */ - public static int ROAD_WIDTH_DEFAULT = 7; + /** + * Road width + */ + public int ROAD_WIDTH; + /** + * Default road width: 7 + */ + public static int ROAD_WIDTH_DEFAULT = 7; - /** - * Plot main block - */ - public PlotBlock[] MAIN_BLOCK; - /** - * Default main block: 1 - */ - public static PlotBlock[] MAIN_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 1, (byte) 0) }; - /** - * Top blocks - */ - public PlotBlock[] TOP_BLOCK; - /** - * Default top blocks: {"2"} - */ - public static PlotBlock[] TOP_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 2, (byte) 0) }; + /** + * Plot main block + */ + public PlotBlock[] MAIN_BLOCK; + /** + * Default main block: 1 + */ + public static PlotBlock[] MAIN_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 1, (byte) 0) }; + /** + * Top blocks + */ + public PlotBlock[] TOP_BLOCK; + /** + * Default top blocks: {"2"} + */ + public static PlotBlock[] TOP_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 2, (byte) 0) }; - /** - * Wall block - */ - public PlotBlock WALL_BLOCK; - /** - * Default wall block: 44 - */ - public static PlotBlock WALL_BLOCK_DEFAULT = new PlotBlock((short) 44, (byte) 0); - public PlotBlock CLAIMED_WALL_BLOCK; - public static PlotBlock CLAIMED_WALL_BLOCK_DEFAULT = new PlotBlock((short) 44, (byte) 1); + /** + * Wall block + */ + public PlotBlock WALL_BLOCK; + /** + * Default wall block: 44 + */ + public static PlotBlock WALL_BLOCK_DEFAULT = new PlotBlock((short) 44, (byte) 0); + public PlotBlock CLAIMED_WALL_BLOCK; + public static PlotBlock CLAIMED_WALL_BLOCK_DEFAULT = new PlotBlock((short) 44, (byte) 1); - /** - * Wall filling - */ - public PlotBlock WALL_FILLING; - /** - * Default wall filling: 1 - */ - public static PlotBlock WALL_FILLING_DEFAULT = new PlotBlock((short) 1, (byte) 0); + /** + * Wall filling + */ + public PlotBlock WALL_FILLING; + /** + * Default wall filling: 1 + */ + public static PlotBlock WALL_FILLING_DEFAULT = new PlotBlock((short) 1, (byte) 0); - /** - * Road stripes - */ - public PlotBlock ROAD_STRIPES; - /** - * Default road stripes: 35 - */ - public static PlotBlock ROAD_STRIPES_DEFAULT = new PlotBlock((short) 98, (byte) 0); - /** - * enable road stripes - */ - public boolean ROAD_STRIPES_ENABLED; - public static boolean ROAD_STRIPES_ENABLED_DEFAULT = false; - /** - * Road block - */ - public PlotBlock ROAD_BLOCK; - /** - * Default road block: 155 - */ - public static PlotBlock ROAD_BLOCK_DEFAULT = new PlotBlock((short) 155, (byte) 0); + /** + * Road stripes + */ + public PlotBlock ROAD_STRIPES; + /** + * Default road stripes: 35 + */ + public static PlotBlock ROAD_STRIPES_DEFAULT = new PlotBlock((short) 98, (byte) 0); + /** + * enable road stripes + */ + public boolean ROAD_STRIPES_ENABLED; + public static boolean ROAD_STRIPES_ENABLED_DEFAULT = false; + /** + * Road block + */ + public PlotBlock ROAD_BLOCK; + /** + * Default road block: 155 + */ + public static PlotBlock ROAD_BLOCK_DEFAULT = new PlotBlock((short) 155, (byte) 0); - /* - * Here we are just calling the super method, nothing special - */ - public DefaultPlotWorld(String worldname) { - super(worldname); - } + /* + * Here we are just calling the super method, nothing special + */ + public DefaultPlotWorld(final String worldname) { + super(worldname); + } - /** - * CONFIG NODE | DEFAULT VALUE | DESCRIPTION | CONFIGURATION TYPE | REQUIRED - * FOR INITIAL SETUP - * - * Set the last boolean to false if you do not require a specific config - * node to be set while using the setup command - this may be useful if a - * config value can be changed at a later date, and has no impact on the - * actual world generation - */ - @Override - public ConfigurationNode[] getSettingNodes() { - // TODO return a set of configuration nodes (used for setup command) - return new ConfigurationNode[] { - new ConfigurationNode("plot.height", DefaultPlotWorld.PLOT_HEIGHT_DEFAULT, "Plot height", Configuration.INTEGER, true), - new ConfigurationNode("plot.size", DefaultPlotWorld.PLOT_WIDTH_DEFAULT, "Plot width", Configuration.INTEGER, true), - new ConfigurationNode("plot.filling", DefaultPlotWorld.MAIN_BLOCK_DEFAULT, "Plot block", Configuration.BLOCKLIST, true), - new ConfigurationNode("plot.floor", DefaultPlotWorld.TOP_BLOCK_DEFAULT, "Plot floor block", Configuration.BLOCKLIST, true), - new ConfigurationNode("wall.block", DefaultPlotWorld.WALL_BLOCK_DEFAULT, "Top wall block", Configuration.BLOCK, true), - new ConfigurationNode("wall.block_claimed", DefaultPlotWorld.CLAIMED_WALL_BLOCK_DEFAULT, "Wall block (claimed)", Configuration.BLOCK, true), - new ConfigurationNode("road.width", DefaultPlotWorld.ROAD_WIDTH_DEFAULT, "Road width", Configuration.INTEGER, true), - new ConfigurationNode("road.height", DefaultPlotWorld.ROAD_HEIGHT_DEFAULT, "Road height", Configuration.INTEGER, true), - new ConfigurationNode("road.enable_stripes", DefaultPlotWorld.ROAD_STRIPES_ENABLED_DEFAULT, "Enable road stripes", Configuration.BOOLEAN, true), - new ConfigurationNode("road.block", DefaultPlotWorld.ROAD_BLOCK_DEFAULT, "Road block", Configuration.BLOCK, true), - new ConfigurationNode("road.stripes", DefaultPlotWorld.ROAD_STRIPES_DEFAULT, "Road stripe block", Configuration.BLOCK, true), - new ConfigurationNode("wall.filling", DefaultPlotWorld.WALL_FILLING_DEFAULT, "Wall filling block", Configuration.BLOCK, true), - new ConfigurationNode("wall.height", DefaultPlotWorld.WALL_HEIGHT_DEFAULT, "Wall height", Configuration.INTEGER, true), }; - } + /** + * CONFIG NODE | DEFAULT VALUE | DESCRIPTION | CONFIGURATION TYPE | REQUIRED + * FOR INITIAL SETUP + * + * Set the last boolean to false if you do not require a specific config + * node to be set while using the setup command - this may be useful if a + * config value can be changed at a later date, and has no impact on the + * actual world generation + */ + @Override + public ConfigurationNode[] getSettingNodes() { + // TODO return a set of configuration nodes (used for setup command) + return new ConfigurationNode[] { new ConfigurationNode("plot.height", DefaultPlotWorld.PLOT_HEIGHT_DEFAULT, "Plot height", Configuration.INTEGER, true), new ConfigurationNode("plot.size", DefaultPlotWorld.PLOT_WIDTH_DEFAULT, "Plot width", Configuration.INTEGER, true), new ConfigurationNode("plot.filling", DefaultPlotWorld.MAIN_BLOCK_DEFAULT, "Plot block", Configuration.BLOCKLIST, true), new ConfigurationNode("plot.floor", DefaultPlotWorld.TOP_BLOCK_DEFAULT, "Plot floor block", Configuration.BLOCKLIST, true), new ConfigurationNode("wall.block", DefaultPlotWorld.WALL_BLOCK_DEFAULT, "Top wall block", Configuration.BLOCK, true), new ConfigurationNode("wall.block_claimed", DefaultPlotWorld.CLAIMED_WALL_BLOCK_DEFAULT, "Wall block (claimed)", Configuration.BLOCK, true), new ConfigurationNode("road.width", DefaultPlotWorld.ROAD_WIDTH_DEFAULT, "Road width", Configuration.INTEGER, true), + new ConfigurationNode("road.height", DefaultPlotWorld.ROAD_HEIGHT_DEFAULT, "Road height", Configuration.INTEGER, true), new ConfigurationNode("road.enable_stripes", DefaultPlotWorld.ROAD_STRIPES_ENABLED_DEFAULT, "Enable road stripes", Configuration.BOOLEAN, true), new ConfigurationNode("road.block", DefaultPlotWorld.ROAD_BLOCK_DEFAULT, "Road block", Configuration.BLOCK, true), new ConfigurationNode("road.stripes", DefaultPlotWorld.ROAD_STRIPES_DEFAULT, "Road stripe block", Configuration.BLOCK, true), new ConfigurationNode("wall.filling", DefaultPlotWorld.WALL_FILLING_DEFAULT, "Wall filling block", Configuration.BLOCK, true), new ConfigurationNode("wall.height", DefaultPlotWorld.WALL_HEIGHT_DEFAULT, "Wall height", Configuration.INTEGER, true), }; + } - /** - * 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. - */ - @Override - public void loadConfiguration(ConfigurationSection config) { - this.PLOT_HEIGHT = config.getInt("plot.height"); - - if (!config.contains("plot.height")) { - PlotMain.sendConsoleSenderMessage(" - &Configuration is null? ("+config.getCurrentPath()+")"); - } - - this.PLOT_WIDTH = config.getInt("plot.size"); - this.MAIN_BLOCK = - (PlotBlock[]) Configuration.BLOCKLIST.parseString(StringUtils.join(config.getStringList("plot.filling"), ',')); - this.TOP_BLOCK = - (PlotBlock[]) Configuration.BLOCKLIST.parseString(StringUtils.join(config.getStringList("plot.floor"), ',')); - this.WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.block")); - this.ROAD_WIDTH = config.getInt("road.width"); - this.ROAD_HEIGHT = config.getInt("road.height"); - this.ROAD_STRIPES_ENABLED = config.getBoolean("road.enable_stripes"); - this.ROAD_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.block")); - this.ROAD_STRIPES = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.stripes")); - this.WALL_FILLING = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.filling")); - this.WALL_HEIGHT = config.getInt("wall.height"); + /** + * 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. + */ + @Override + public void loadConfiguration(final ConfigurationSection config) { + this.PLOT_HEIGHT = config.getInt("plot.height"); + + if (!config.contains("plot.height")) { + PlotMain.sendConsoleSenderMessage(" - &Configuration is null? (" + config.getCurrentPath() + ")"); + } + + this.PLOT_WIDTH = config.getInt("plot.size"); + this.MAIN_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST.parseString(StringUtils.join(config.getStringList("plot.filling"), ',')); + this.TOP_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST.parseString(StringUtils.join(config.getStringList("plot.floor"), ',')); + this.WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.block")); + this.ROAD_WIDTH = config.getInt("road.width"); + this.ROAD_HEIGHT = config.getInt("road.height"); + this.ROAD_STRIPES_ENABLED = config.getBoolean("road.enable_stripes"); + this.ROAD_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.block")); + this.ROAD_STRIPES = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.stripes")); + this.WALL_FILLING = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.filling")); + this.WALL_HEIGHT = config.getInt("wall.height"); this.CLAIMED_WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.block_claimed")); - } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/WorldGenerator.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/WorldGenerator.java index 331594518..50f151d2c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/WorldGenerator.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/WorldGenerator.java @@ -11,7 +11,6 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.generator.BlockPopulator; -import com.intellectualcrafters.plot.ConfigurationNode; import com.intellectualcrafters.plot.PlotBlock; import com.intellectualcrafters.plot.PlotGenerator; import com.intellectualcrafters.plot.PlotMain; @@ -27,552 +26,552 @@ import com.intellectualcrafters.plot.PlotWorld; * somewhat longer */ public class WorldGenerator extends PlotGenerator { - /** - * result object is returned for each generated chunk, do stuff to it - */ - short[][] result; + /** + * result object is returned for each generated chunk, do stuff to it + */ + short[][] result; - /** - * plotworld object - */ - DefaultPlotWorld plotworld; - /** - * Set to static to re-use the same managet for all Default World Generators - */ - private static PlotManager manager = null; + /** + * plotworld object + */ + DefaultPlotWorld plotworld; + /** + * Set to static to re-use the same managet for all Default World Generators + */ + private static PlotManager manager = null; - /** - * Some generator specific variables (implementation dependent) - */ - final int plotsize; - final int pathsize; - final PlotBlock wall; - final PlotBlock wallfilling; - final PlotBlock floor1; - final PlotBlock floor2; - final int size; - final Biome biome; - final int roadheight; - final int wallheight; - final int plotheight; - final PlotBlock[] plotfloors; - final PlotBlock[] filling; + /** + * Some generator specific variables (implementation dependent) + */ + final int plotsize; + final int pathsize; + final PlotBlock wall; + final PlotBlock wallfilling; + final PlotBlock floor1; + final PlotBlock floor2; + final int size; + final Biome biome; + final int roadheight; + final int wallheight; + final int plotheight; + final PlotBlock[] plotfloors; + final PlotBlock[] filling; - /** - * Return the plot manager for this type of generator, or create one For - * square plots you may as well use the default plot manager which comes - * with PlotSquared - */ - @Override - public PlotManager getPlotManager() { - if (manager == null) { - manager = new DefaultPlotManager(); - } - return manager; - } - /** - * Allow spawning everywhere - */ - @Override - public boolean canSpawn(World world, int x, int z) { + /** + * Return the plot manager for this type of generator, or create one For + * square plots you may as well use the default plot manager which comes + * with PlotSquared + */ + @Override + public PlotManager getPlotManager() { + if (manager == null) { + manager = new DefaultPlotManager(); + } + return manager; + } + + /** + * Allow spawning everywhere + */ + @Override + public boolean canSpawn(final World world, final int x, final int z) { return true; } - /** - * Get a new plotworld class For square plots you can use the - * DefaultPlotWorld class which comes with PlotSquared - */ - @Override - public PlotWorld getNewPlotWorld(String world) { - this.plotworld = new DefaultPlotWorld(world); - return this.plotworld; - } - /** - * Faster sudo-random number generator than java.util.random - */ - private long state; + /** + * Get a new plotworld class For square plots you can use the + * DefaultPlotWorld class which comes with PlotSquared + */ + @Override + public PlotWorld getNewPlotWorld(final String world) { + this.plotworld = new DefaultPlotWorld(world); + return this.plotworld; + } - public final long nextLong() { - long a = this.state; - this.state = xorShift64(a); - return a; - } + /** + * Faster sudo-random number generator than java.util.random + */ + private long state; - public final long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } + public final long nextLong() { + final long a = this.state; + this.state = xorShift64(a); + return a; + } - public final int random(int n) { - long r = ((nextLong() >>> 32) * n) >> 32; - return (int) r; - } + public final long xorShift64(long a) { + a ^= (a << 21); + a ^= (a >>> 35); + a ^= (a << 4); + return a; + } - /** - * Cuboid based plot generation is quick, as it requires no calculations - * inside the loop - You don't have to use this this method, but you may - * find it useful. - */ - public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock block) { - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - setBlock(this.result, x, y, z, block.id); - } - } - } - } + public final int random(final int n) { + final long r = ((nextLong() >>> 32) * n) >> 32; + return (int) r; + } - private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock[] blocks) { - if (blocks.length == 1) { - setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0]); - } - else { - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - int i = random(blocks.length); - setBlock(this.result, x, y, z, blocks[i].id); - } - } - } - } - } + /** + * Cuboid based plot generation is quick, as it requires no calculations + * inside the loop - You don't have to use this this method, but you may + * find it useful. + */ + public void setCuboidRegion(final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock block) { + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + setBlock(this.result, x, y, z, block.id); + } + } + } + } - /** - * Standard setblock method for world generation - */ - private void setBlock(short[][] result, int x, int y, int z, short blkid) { - if (result[y >> 4] == null) { - result[y >> 4] = new short[4096]; - } - result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid; - } + private void setCuboidRegion(final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks) { + if (blocks.length == 1) { + setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0]); + } + else { + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + final int i = random(blocks.length); + setBlock(this.result, x, y, z, blocks[i].id); + } + } + } + } + } - /** - * Initialize variables, and create plotworld object used in calculations - */ - public WorldGenerator(String world) { - super(world); - - if (this.plotworld == null) { - this.plotworld = new DefaultPlotWorld(world); - if (!PlotMain.config.contains("worlds."+world)) { - PlotMain.config = YamlConfiguration.loadConfiguration(PlotMain.configFile); - PlotMain.config.createSection("worlds."+world); - } - ConfigurationSection section = PlotMain.config.getConfigurationSection("worlds."+world); - this.plotworld.saveConfiguration(section); - this.plotworld.loadDefaultConfiguration(section); - this.plotworld.loadConfiguration(section); - PlotMain.sendConsoleSenderMessage("&cFailed to load the plotworld settings from the configuration. Attempting to reload it"); - } - - this.plotsize = this.plotworld.PLOT_WIDTH; + /** + * Standard setblock method for world generation + */ + private void setBlock(final short[][] result, final int x, final int y, final int z, final short blkid) { + if (result[y >> 4] == null) { + result[y >> 4] = new short[4096]; + } + result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid; + } - this.pathsize = this.plotworld.ROAD_WIDTH; + /** + * Initialize variables, and create plotworld object used in calculations + */ + public WorldGenerator(final String world) { + super(world); - this.floor1 = this.plotworld.ROAD_BLOCK; - this.floor2 = this.plotworld.ROAD_STRIPES; + if (this.plotworld == null) { + this.plotworld = new DefaultPlotWorld(world); + if (!PlotMain.config.contains("worlds." + world)) { + PlotMain.config = YamlConfiguration.loadConfiguration(PlotMain.configFile); + PlotMain.config.createSection("worlds." + world); + } + final ConfigurationSection section = PlotMain.config.getConfigurationSection("worlds." + world); + this.plotworld.saveConfiguration(section); + this.plotworld.loadDefaultConfiguration(section); + this.plotworld.loadConfiguration(section); + PlotMain.sendConsoleSenderMessage("&cFailed to load the plotworld settings from the configuration. Attempting to reload it"); + } - this.wallfilling = this.plotworld.WALL_FILLING; - this.size = this.pathsize + this.plotsize; - this.wall = this.plotworld.WALL_BLOCK; + this.plotsize = this.plotworld.PLOT_WIDTH; - this.plotfloors = this.plotworld.TOP_BLOCK; - this.filling = this.plotworld.MAIN_BLOCK; - this.wallheight = this.plotworld.WALL_HEIGHT; - this.roadheight = this.plotworld.ROAD_HEIGHT; - this.plotheight = this.plotworld.PLOT_HEIGHT; + this.pathsize = this.plotworld.ROAD_WIDTH; - this.biome = this.plotworld.PLOT_BIOME; - } + this.floor1 = this.plotworld.ROAD_BLOCK; + this.floor2 = this.plotworld.ROAD_STRIPES; - /** - * Return the block populator - */ - @Override - public List getDefaultPopulators(World world) { - // disabling spawning for this world - if (!this.plotworld.MOB_SPAWNING) { - world.setSpawnFlags(false, false); - world.setAmbientSpawnLimit(0); - world.setAnimalSpawnLimit(0); - world.setMonsterSpawnLimit(0); - world.setWaterAnimalSpawnLimit(0); - } - // You can have as many populators as you would like, e.g. tree - // populator, ore populator - return Arrays.asList((BlockPopulator) new XPopulator(this.plotworld)); - } + this.wallfilling = this.plotworld.WALL_FILLING; + this.size = this.pathsize + this.plotsize; + this.wall = this.plotworld.WALL_BLOCK; - /** - * Return the default spawn location for this world - */ - @Override - public Location getFixedSpawnLocation(World world, Random random) { - return new Location(world, 0, this.plotworld.ROAD_HEIGHT + 2, 0); - } + this.plotfloors = this.plotworld.TOP_BLOCK; + this.filling = this.plotworld.MAIN_BLOCK; + this.wallheight = this.plotworld.WALL_HEIGHT; + this.roadheight = this.plotworld.ROAD_HEIGHT; + this.plotheight = this.plotworld.PLOT_HEIGHT; - /** - * This part is a fucking mess. - Refer to a proper tutorial if you would - * like to learn how to make a world generator - */ - @Override - public short[][] generateExtBlockSections(World world, Random random, int cx, int cz, BiomeGrid biomes) { + this.biome = this.plotworld.PLOT_BIOME; + } - int maxY = world.getMaxHeight(); - this.result = new short[maxY / 16][]; + /** + * Return the block populator + */ + @Override + public List getDefaultPopulators(final World world) { + // disabling spawning for this world + if (!this.plotworld.MOB_SPAWNING) { + world.setSpawnFlags(false, false); + world.setAmbientSpawnLimit(0); + world.setAnimalSpawnLimit(0); + world.setMonsterSpawnLimit(0); + world.setWaterAnimalSpawnLimit(0); + } + // You can have as many populators as you would like, e.g. tree + // populator, ore populator + return Arrays.asList((BlockPopulator) new XPopulator(this.plotworld)); + } - final int prime = 31; - int h = 1; - h = (prime * h) + cx; - h = (prime * h) + cz; - this.state = h; + /** + * Return the default spawn location for this world + */ + @Override + public Location getFixedSpawnLocation(final World world, final Random random) { + return new Location(world, 0, this.plotworld.ROAD_HEIGHT + 2, 0); + } - double pathWidthLower; - if ((this.pathsize % 2) == 0) { - pathWidthLower = Math.floor(this.pathsize / 2) - 1; - } - else { - pathWidthLower = Math.floor(this.pathsize / 2); - } - cx = (cx % this.size) + (8 * this.size); - cz = (cz % this.size) + (8 * this.size); - int absX = (int) ((((cx * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); - int absZ = (int) ((((cz * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); - int plotMinX = (((absX) % this.size)); - int plotMinZ = (((absZ) % this.size)); - int roadStartX = (plotMinX + this.pathsize); - int roadStartZ = (plotMinZ + this.pathsize); - if (roadStartX >= this.size) { - roadStartX -= this.size; - } - if (roadStartZ >= this.size) { - roadStartZ -= this.size; - } + /** + * This part is a fucking mess. - Refer to a proper tutorial if you would + * like to learn how to make a world generator + */ + @Override + public short[][] generateExtBlockSections(final World world, final Random random, int cx, int cz, final BiomeGrid biomes) { - // BOTTOM (1/1 cuboids) - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - setBlock(this.result, x, 0, z, (short) 7); - biomes.setBiome(x, z, this.biome); - } - } - // ROAD (0/24) The following is an inefficient placeholder as it is too - // much work to finish it - if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) - && !((roadStartX < 16) && (roadStartZ < 16)) - && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { - setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1); - return this.result; - } - if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { - int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); - int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1); - } - if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { - int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); - int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1); - } + final int maxY = world.getMaxHeight(); + this.result = new short[maxY / 16][]; - // ROAD STRIPES - if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { - if ((plotMinZ + 2) <= 16) { - int value = (plotMinZ + 2); - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } - else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); // - setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); // - } - if ((plotMinX + 2) <= 16) { - int value = (plotMinX + 2); - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } - else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, 0, end, this.floor2); // - setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, start, 16, this.floor2); // - } - if ((roadStartZ <= 16) && (roadStartZ > 1)) { - int val = roadStartZ; - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } - else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2); - setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2); - } - if ((roadStartX <= 16) && (roadStartX > 1)) { - int val = roadStartX; - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } - else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, 0, end, this.floor2); // - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, start, 16, this.floor2); // - } - } + final int prime = 31; + int h = 1; + h = (prime * h) + cx; + h = (prime * h) + cz; + this.state = h; - // Plot filling (28/28 cuboids) (10x2 + 4x2) - if (this.plotsize > 16) { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - } - else { - if (roadStartZ <= 16) { - if (plotMinX > 16) { - setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - else { - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - else { - if (roadStartX <= 16) { - if (plotMinZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors); - } - } - } - } - else { - if (plotMinZ <= 16) { - if (roadStartX > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - } - else { - if (roadStartZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - if (roadStartX > 16) { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); - } - else { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); - } - } - } - } - } - else { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - } - } + double pathWidthLower; + if ((this.pathsize % 2) == 0) { + pathWidthLower = Math.floor(this.pathsize / 2) - 1; + } + else { + pathWidthLower = Math.floor(this.pathsize / 2); + } + cx = (cx % this.size) + (8 * this.size); + cz = (cz % this.size) + (8 * this.size); + final int absX = (int) ((((cx * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); + final int absZ = (int) ((((cz * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); + final int plotMinX = (((absX) % this.size)); + final int plotMinZ = (((absZ) % this.size)); + int roadStartX = (plotMinX + this.pathsize); + int roadStartZ = (plotMinZ + this.pathsize); + if (roadStartX >= this.size) { + roadStartX -= this.size; + } + if (roadStartZ >= this.size) { + roadStartZ -= this.size; + } - // WALLS (16/16 cuboids) - if (this.pathsize > 0) { - if ((plotMinZ + 1) <= 16) { - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } - else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall); - } - if ((plotMinX + 1) <= 16) { - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } - else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall); - } - if ((roadStartZ <= 16) && (roadStartZ > 0)) { - int start, end; - if ((plotMinX + 1) <= 16) { - start = 16 - plotMinX; - } - else { - start = 16; - } - if ((roadStartX + 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall); - } - if ((roadStartX <= 16) && (roadStartX > 0)) { - int start, end; - if ((plotMinZ + 1) <= 16) { - start = 16 - plotMinZ; - } - else { - start = 16; - } - if ((roadStartZ + 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall); - } - } - // Return the chunk - return this.result; - } + // BOTTOM (1/1 cuboids) + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + setBlock(this.result, x, 0, z, (short) 7); + biomes.setBiome(x, z, this.biome); + } + } + // ROAD (0/24) The following is an inefficient placeholder as it is too + // much work to finish it + if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) && !((roadStartX < 16) && (roadStartZ < 16)) && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { + setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1); + return this.result; + } + if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { + final int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); + int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1); + } + if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { + final int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); + int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1); + } + + // ROAD STRIPES + if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { + if ((plotMinZ + 2) <= 16) { + final int value = (plotMinZ + 2); + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } + else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); // + setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); // + } + if ((plotMinX + 2) <= 16) { + final int value = (plotMinX + 2); + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } + else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, 0, end, this.floor2); // + setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, start, 16, this.floor2); // + } + if ((roadStartZ <= 16) && (roadStartZ > 1)) { + final int val = roadStartZ; + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } + else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2); + setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2); + } + if ((roadStartX <= 16) && (roadStartX > 1)) { + final int val = roadStartX; + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } + else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, 0, end, this.floor2); // + setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, start, 16, this.floor2); // + } + } + + // Plot filling (28/28 cuboids) (10x2 + 4x2) + if (this.plotsize > 16) { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); + } + } + else { + if (roadStartZ <= 16) { + if (plotMinX > 16) { + setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); + setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); + } + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); + } + else { + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); + } + else { + if (roadStartX <= 16) { + if (plotMinZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors); + } + } + } + } + else { + if (plotMinZ <= 16) { + if (roadStartX > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); + } + } + else { + if (roadStartZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + if (roadStartX > 16) { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); + } + else { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); + } + } + } + } + } + else { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); + } + } + } + + // WALLS (16/16 cuboids) + if (this.pathsize > 0) { + if ((plotMinZ + 1) <= 16) { + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } + else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); + setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall); + setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); + setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall); + } + if ((plotMinX + 1) <= 16) { + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } + else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall); + } + if ((roadStartZ <= 16) && (roadStartZ > 0)) { + int start, end; + if ((plotMinX + 1) <= 16) { + start = 16 - plotMinX; + } + else { + start = 16; + } + if ((roadStartX + 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling); + setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall); + setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling); + setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall); + } + if ((roadStartX <= 16) && (roadStartX > 0)) { + int start, end; + if ((plotMinZ + 1) <= 16) { + start = 16 - plotMinZ; + } + else { + start = 16; + } + if ((roadStartZ + 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall); + } + } + // Return the chunk + return this.result; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/XPopulator.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/XPopulator.java index 5bdbdd5fb..7f8d70134 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/XPopulator.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/generator/XPopulator.java @@ -15,464 +15,460 @@ import com.intellectualcrafters.plot.PlotWorld; */ public class XPopulator extends BlockPopulator { - /* - * Sorry, this isn't well documented at the moment. - * - * We advise you to take a look at a world generation tutorial for - * information about how a BlockPopulator works. - */ + /* + * Sorry, this isn't well documented at the moment. + * We advise you to take a look at a world generation tutorial for + * information about how a BlockPopulator works. + */ - private int X; - private int Z; - private long state; + private int X; + private int Z; + private long state; - public final long nextLong() { - long a = this.state; - this.state = xorShift64(a); - return a; - } + public final long nextLong() { + final long a = this.state; + this.state = xorShift64(a); + return a; + } - public final long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } + public final long xorShift64(long a) { + a ^= (a << 21); + a ^= (a >>> 35); + a ^= (a << 4); + return a; + } - public final int random(int n) { - long result = ((nextLong() >>> 32) * n) >> 32; - return (int) result; - } + public final int random(final int n) { + final long result = ((nextLong() >>> 32) * n) >> 32; + return (int) result; + } - public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock block, World w) { - if (block.data == 0) { - return; - } - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - setBlock(w, x, y, z, block.id, block.data); - } - } - } - } + public void setCuboidRegion(final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock block, final World w) { + if (block.data == 0) { + return; + } + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + setBlock(w, x, y, z, block.id, block.data); + } + } + } + } - private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock[] blocks, World w) { - if (blocks.length == 1) { - setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0], w); - } - else { - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - int i = random(blocks.length); - if (blocks[i].data != 0) { - setBlock(w, x, y, z, blocks[i].id, blocks[i].data); - } - } - } - } - } + private void setCuboidRegion(final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks, final World w) { + if (blocks.length == 1) { + setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0], w); + } + else { + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + final int i = random(blocks.length); + if (blocks[i].data != 0) { + setBlock(w, x, y, z, blocks[i].id, blocks[i].data); + } + } + } + } + } - } + } - public short[] getBlock(String block) { - if (block.contains(":")) { - String[] split = block.split(":"); - return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; - } - return new short[] { Short.parseShort(block), 0 }; - } + public short[] getBlock(final String block) { + if (block.contains(":")) { + final String[] split = block.split(":"); + return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; + } + return new short[] { Short.parseShort(block), 0 }; + } - int plotsize; - int pathsize; - PlotBlock wall; - PlotBlock wallfilling; - PlotBlock floor1; - PlotBlock floor2; - int size; - Biome biome; - int roadheight; - int wallheight; - int plotheight; - PlotBlock[] plotfloors; - PlotBlock[] filling; + int plotsize; + int pathsize; + PlotBlock wall; + PlotBlock wallfilling; + PlotBlock floor1; + PlotBlock floor2; + int size; + Biome biome; + int roadheight; + int wallheight; + int plotheight; + PlotBlock[] plotfloors; + PlotBlock[] filling; - private double pathWidthLower; - private DefaultPlotWorld plotworld; + private double pathWidthLower; + private final DefaultPlotWorld plotworld; - public XPopulator(PlotWorld pw) { - this.plotworld = (DefaultPlotWorld) pw; + public XPopulator(final PlotWorld pw) { + this.plotworld = (DefaultPlotWorld) pw; - // save configuration + // save configuration - this.plotsize = this.plotworld.PLOT_WIDTH; - this.pathsize = this.plotworld.ROAD_WIDTH; + this.plotsize = this.plotworld.PLOT_WIDTH; + this.pathsize = this.plotworld.ROAD_WIDTH; - this.floor1 = this.plotworld.ROAD_BLOCK; - this.floor2 = this.plotworld.ROAD_STRIPES; + this.floor1 = this.plotworld.ROAD_BLOCK; + this.floor2 = this.plotworld.ROAD_STRIPES; - this.wallfilling = this.plotworld.WALL_FILLING; - this.size = this.pathsize + this.plotsize; - this.wall = this.plotworld.WALL_BLOCK; + this.wallfilling = this.plotworld.WALL_FILLING; + this.size = this.pathsize + this.plotsize; + this.wall = this.plotworld.WALL_BLOCK; - this.plotfloors = this.plotworld.TOP_BLOCK; - this.filling = this.plotworld.MAIN_BLOCK; + this.plotfloors = this.plotworld.TOP_BLOCK; + this.filling = this.plotworld.MAIN_BLOCK; - this.wallheight = this.plotworld.WALL_HEIGHT; - this.roadheight = this.plotworld.ROAD_HEIGHT; - this.plotheight = this.plotworld.PLOT_HEIGHT; + this.wallheight = this.plotworld.WALL_HEIGHT; + this.roadheight = this.plotworld.ROAD_HEIGHT; + this.plotheight = this.plotworld.PLOT_HEIGHT; - if ((this.pathsize % 2) == 0) { - this.pathWidthLower = Math.floor(this.pathsize / 2) - 1; - } - else { - this.pathWidthLower = Math.floor(this.pathsize / 2); - } - } + if ((this.pathsize % 2) == 0) { + this.pathWidthLower = Math.floor(this.pathsize / 2) - 1; + } + else { + this.pathWidthLower = Math.floor(this.pathsize / 2); + } + } - @Override - public void populate(World w, Random r, Chunk c) { - int cx = c.getX(), cz = c.getZ(); + @Override + public void populate(final World w, final Random r, final Chunk c) { + int cx = c.getX(), cz = c.getZ(); - final int prime = 31; - int h = 1; - h = (prime * h) + cx; - h = (prime * h) + cz; - this.state = h; + final int prime = 31; + int h = 1; + h = (prime * h) + cx; + h = (prime * h) + cz; + this.state = h; - this.X = cx << 4; - this.Z = cz << 4; - cx = (cx % this.size) + (8 * this.size); - cz = (cz % this.size) + (8 * this.size); - double absX = ((((cx * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)), absZ = - ((((cz * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)); - int plotMinX = (int) (((absX) % this.size)); - int plotMinZ = (int) (((absZ) % this.size)); - int roadStartX = (plotMinX + this.pathsize); - int roadStartZ = (plotMinZ + this.pathsize); - if (roadStartX >= this.size) { - roadStartX -= this.size; - } - if (roadStartZ >= this.size) { - roadStartZ -= this.size; - } + this.X = cx << 4; + this.Z = cz << 4; + cx = (cx % this.size) + (8 * this.size); + cz = (cz % this.size) + (8 * this.size); + final double absX = ((((cx * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)), absZ = ((((cz * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)); + final int plotMinX = (int) (((absX) % this.size)); + final int plotMinZ = (int) (((absZ) % this.size)); + int roadStartX = (plotMinX + this.pathsize); + int roadStartZ = (plotMinZ + this.pathsize); + if (roadStartX >= this.size) { + roadStartX -= this.size; + } + if (roadStartZ >= this.size) { + roadStartZ -= this.size; + } - // ROADS + // ROADS - if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) - && !((roadStartX < 16) && (roadStartZ < 16)) - && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { - setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1, w); - return; - } + if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) && !((roadStartX < 16) && (roadStartZ < 16)) && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { + setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1, w); + return; + } - if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { - int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); - int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1, w); - } - if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { - int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); - int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1, w); - } + if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { + final int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); + int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1, w); + } + if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { + final int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); + int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1, w); + } - // STRIPES - if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { - if ((plotMinZ + 2) <= 16) { - int value = (plotMinZ + 2); - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } - else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // - setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // - } - if ((plotMinX + 2) <= 16) { - int value = (plotMinX + 2); - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } - else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // - setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // - } - if ((roadStartZ <= 16) && (roadStartZ > 1)) { - int val = roadStartZ; - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } - else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); - setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); - } - if ((roadStartX <= 16) && (roadStartX > 1)) { - int val = roadStartX; - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } - else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // - } - } - // WALLS - if (this.pathsize > 0) { - if ((plotMinZ + 1) <= 16) { - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } - else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); - } - if ((plotMinX + 1) <= 16) { - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } - else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling, w); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall, w); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling, w); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); - } - if ((roadStartZ <= 16) && (roadStartZ > 0)) { - int start, end; - if ((plotMinX + 1) <= 16) { - start = 16 - plotMinX; - } - else { - start = 16; - } - if ((roadStartX + 1) <= 16) { - end = (16 - roadStartX) + 1; - } - else { - end = 0; - } - if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); - } - if ((roadStartX <= 16) && (roadStartX > 0)) { - int start, end; - if ((plotMinZ + 1) <= 16) { - start = 16 - plotMinZ; - } - else { - start = 16; - } - if ((roadStartZ + 1) <= 16) { - end = (16 - roadStartZ) + 1; - } - else { - end = 0; - } - if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling, w); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall, w); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling, w); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); - } - } + // STRIPES + if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { + if ((plotMinZ + 2) <= 16) { + final int value = (plotMinZ + 2); + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } + else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // + setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // + } + if ((plotMinX + 2) <= 16) { + final int value = (plotMinX + 2); + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } + else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // + setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // + } + if ((roadStartZ <= 16) && (roadStartZ > 1)) { + final int val = roadStartZ; + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } + else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); + setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); + } + if ((roadStartX <= 16) && (roadStartX > 1)) { + final int val = roadStartX; + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } + else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // + setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // + } + } + // WALLS + if (this.pathsize > 0) { + if ((plotMinZ + 1) <= 16) { + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } + else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); + setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); + setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); + setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); + } + if ((plotMinX + 1) <= 16) { + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } + else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling, w); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall, w); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling, w); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); + } + if ((roadStartZ <= 16) && (roadStartZ > 0)) { + int start, end; + if ((plotMinX + 1) <= 16) { + start = 16 - plotMinX; + } + else { + start = 16; + } + if ((roadStartX + 1) <= 16) { + end = (16 - roadStartX) + 1; + } + else { + end = 0; + } + if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); + setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); + setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); + setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); + } + if ((roadStartX <= 16) && (roadStartX > 0)) { + int start, end; + if ((plotMinZ + 1) <= 16) { + start = 16 - plotMinZ; + } + else { + start = 16; + } + if ((roadStartZ + 1) <= 16) { + end = (16 - roadStartZ) + 1; + } + else { + end = 0; + } + if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling, w); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall, w); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling, w); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); + } + } - // PLOT + // PLOT - if (this.plotsize > 16) { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - } - else { - if (roadStartZ <= 16) { - if (plotMinX > 16) { - setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - else { - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - else { - if (roadStartX <= 16) { - if (plotMinZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors, w); - } - } - } - } - else { - if (plotMinZ <= 16) { - if (roadStartX > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - } - else { - if (roadStartZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - if (roadStartX > 16) { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); - } - else { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); - } - } - } - } - } - else { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - } - } - } + if (this.plotsize > 16) { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); + } + } + else { + if (roadStartZ <= 16) { + if (plotMinX > 16) { + setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); + setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); + } + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); + } + else { + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); + } + else { + if (roadStartX <= 16) { + if (plotMinZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling, w); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors, w); + } + } + } + } + else { + if (plotMinZ <= 16) { + if (roadStartX > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); + } + } + else { + if (roadStartZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + if (roadStartX > 16) { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); + } + else { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); + setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); + } + } + } + } + } + else { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); + } + } + } + } - private void setBlock(World w, int x, int y, int z, short id, byte val) { - w.getBlockAt(this.X + x, y, this.Z + z).setData(val, false); - } + private void setBlock(final World w, final int x, final int y, final int z, final short id, final byte val) { + w.getBlockAt(this.X + x, y, this.Z + z).setData(val, false); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/ForceFieldListener.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/ForceFieldListener.java index 2786a94b2..962090bb5 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/ForceFieldListener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/ForceFieldListener.java @@ -1,7 +1,8 @@ package com.intellectualcrafters.plot.listeners; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.Plot; +import java.util.HashSet; +import java.util.Set; + import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -11,84 +12,94 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.Vector; -import java.util.HashSet; -import java.util.Set; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; + /** * Created by Citymonstret on 2014-10-24. */ public class ForceFieldListener implements Listener { - private JavaPlugin plugin; - public ForceFieldListener(JavaPlugin plugin) { - this.plugin = plugin; + public ForceFieldListener(final JavaPlugin plugin) { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - private Set getNearbyPlayers(Player player, Plot plot) { - Set players = new HashSet<>(); + + private Set getNearbyPlayers(final Player player, final Plot plot) { + final Set players = new HashSet<>(); Player oPlayer = null; - for(Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { - if(!(entity instanceof Player) || (oPlayer = (Player) entity) == null || !PlayerFunctions.isInPlot(oPlayer) || !PlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) { + for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { + if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !PlayerFunctions.isInPlot(oPlayer) || !PlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) { continue; } - if(!plot.hasRights(oPlayer)) + if (!plot.hasRights(oPlayer)) { players.add(oPlayer); + } } return players; } - private Player hasNearbyPermitted(Player player, Plot plot) { + + private Player hasNearbyPermitted(final Player player, final Plot plot) { Player oPlayer = null; - for(Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { - if(!(entity instanceof Player) || (oPlayer = (Player) entity) == null || !PlayerFunctions.isInPlot(oPlayer) || !PlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) { + for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) { + if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !PlayerFunctions.isInPlot(oPlayer) || !PlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) { continue; } - if(plot.hasRights(oPlayer)) + if (plot.hasRights(oPlayer)) { return oPlayer; + } } return null; } - public Vector calculateVelocity(Player p, Player e) { - Location playerLocation = p.getLocation(); - Location oPlayerLocation = e.getLocation(); - double - playerX = playerLocation.getX(), - playerY = playerLocation.getY(), - playerZ = playerLocation.getZ(), - oPlayerX = oPlayerLocation.getX(), - oPlayerY = oPlayerLocation.getY(), - oPlayerZ = oPlayerLocation.getZ(), - x = 0d, y = 0d, z = 0d; - if(playerX < oPlayerX) + + public Vector calculateVelocity(final Player p, final Player e) { + final Location playerLocation = p.getLocation(); + final Location oPlayerLocation = e.getLocation(); + final double playerX = playerLocation.getX(), playerY = playerLocation.getY(), playerZ = playerLocation.getZ(), oPlayerX = oPlayerLocation.getX(), oPlayerY = oPlayerLocation.getY(), oPlayerZ = oPlayerLocation.getZ(); + double x = 0d, y = 0d, z = 0d; + if (playerX < oPlayerX) { x = 1.0d; - else if(playerX > oPlayerX) + } + else if (playerX > oPlayerX) { x = -1.0d; - if(playerY < oPlayerY) + } + if (playerY < oPlayerY) { y = 0.5d; - else if(playerY > oPlayerY) + } + else if (playerY > oPlayerY) { y = -0.5d; - if(playerZ < oPlayerZ) + } + if (playerZ < oPlayerZ) { z = 1.0d; - else if(playerZ > oPlayerZ) + } + else if (playerZ > oPlayerZ) { z = -1.0d; + } return new Vector(x, y, z); } + @EventHandler - public void onPlotEntry(PlayerMoveEvent event){ - Player player = event.getPlayer(); - if(!PlayerFunctions.isInPlot(player)) + public void onPlotEntry(final PlayerMoveEvent event) { + final Player player = event.getPlayer(); + if (!PlayerFunctions.isInPlot(player)) { return; - Plot plot = PlayerFunctions.getCurrentPlot(player); - if (plot.settings.getFlag("forcefield") != null && plot.settings.getFlag("forcefield").getValue().equals("true")) { - if(!PlotListener.booleanFlag(plot, "forcefield")) - if(plot.hasRights(player)) { - Set players = getNearbyPlayers(player, plot); - for(Player oPlayer : players) { + } + final Plot plot = PlayerFunctions.getCurrentPlot(player); + if ((plot.settings.getFlag("forcefield") != null) && plot.settings.getFlag("forcefield").getValue().equals("true")) { + if (!PlotListener.booleanFlag(plot, "forcefield")) { + if (plot.hasRights(player)) { + final Set players = getNearbyPlayers(player, plot); + for (final Player oPlayer : players) { oPlayer.setVelocity(calculateVelocity(player, oPlayer)); } - } else { - Player oPlayer = hasNearbyPermitted(player, plot); - if(oPlayer == null) return; + } + else { + final Player oPlayer = hasNearbyPermitted(player, plot); + if (oPlayer == null) { + return; + } player.setVelocity(calculateVelocity(oPlayer, player)); } + } } } -} \ No newline at end of file +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlayerEvents.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlayerEvents.java index 773dc1c56..6e7b1019b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlayerEvents.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlayerEvents.java @@ -2,17 +2,20 @@ * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. - * + * * >> File = PlayerEvents.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot.listeners; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.commands.Setup; -import com.intellectualcrafters.plot.database.DBFunc; +import java.util.List; +import java.util.Set; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; @@ -21,7 +24,18 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.*; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; @@ -29,12 +43,31 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerEggThrowEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.WorldLoadEvent; -import java.util.List; -import java.util.Set; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotManager; +import com.intellectualcrafters.plot.PlotSelection; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.Settings; +import com.intellectualcrafters.plot.commands.Setup; +import com.intellectualcrafters.plot.database.DBFunc; /** * Player Events involving plots @@ -44,535 +77,511 @@ import java.util.Set; @SuppressWarnings("unused") public class PlayerEvents extends com.intellectualcrafters.plot.listeners.PlotListener implements Listener { - @EventHandler - public static void onWorldLoad(WorldLoadEvent event) { - PlotMain.loadWorld(event.getWorld()); - } + @EventHandler + public static void onWorldLoad(final WorldLoadEvent event) { + PlotMain.loadWorld(event.getWorld()); + } - @EventHandler - public static void onJoin(PlayerJoinEvent event) { - if (!event.getPlayer().hasPlayedBefore()) { - event.getPlayer().saveData(); - } - //textures(event.getPlayer()); - if(isInPlot(event.getPlayer().getLocation())) { + @EventHandler + public static void onJoin(final PlayerJoinEvent event) { + if (!event.getPlayer().hasPlayedBefore()) { + event.getPlayer().saveData(); + } + // textures(event.getPlayer()); + if (isInPlot(event.getPlayer().getLocation())) { plotEntry(event.getPlayer(), getCurrentPlot(event.getPlayer().getLocation())); } - } + } - @EventHandler - public void onChangeWorld(PlayerChangedWorldEvent event) { - /*if (isPlotWorld(event.getFrom()) && (Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1)) { - event.getPlayer().setResourcePack(""); - } - else { - textures(event.getPlayer()); - }*/ - } + @EventHandler + public void onChangeWorld(final PlayerChangedWorldEvent event) { + /* + * if (isPlotWorld(event.getFrom()) && + * (Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1)) { + * event.getPlayer().setResourcePack(""); + * } + * else { + * textures(event.getPlayer()); + * } + */ + } - @EventHandler( - priority = EventPriority.HIGHEST, ignoreCancelled = true) - public static void PlayerMove(PlayerMoveEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public static void PlayerMove(final PlayerMoveEvent event) { try { - Player player = event.getPlayer(); - Location from = event.getFrom(); - Location to = event.getTo(); + final Player player = event.getPlayer(); + final Location from = event.getFrom(); + final Location to = event.getTo(); if ((from.getBlockX() != to.getBlockX()) || (from.getBlockZ() != to.getBlockZ())) { if (!isPlotWorld(player.getWorld())) { return; } if (enteredPlot(from, to)) { - Plot plot = getCurrentPlot(event.getTo()); - boolean admin = PlotMain.hasPermission(player,"plots.admin"); + final Plot plot = getCurrentPlot(event.getTo()); + final boolean admin = PlotMain.hasPermission(player, "plots.admin"); if (plot.deny_entry(player) && !admin) { event.setCancelled(true); return; } plotEntry(player, plot); - } else if (leftPlot(event.getFrom(), event.getTo())) { - Plot plot = getCurrentPlot(event.getFrom()); + } + else if (leftPlot(event.getFrom(), event.getTo())) { + final Plot plot = getCurrentPlot(event.getFrom()); plotExit(player, plot); } } - } catch (Exception e) { + } + catch (final Exception e) { // Gotta catch 'em all. } } - - - @EventHandler( - priority = EventPriority.HIGHEST) - public static void onChat(AsyncPlayerChatEvent event) { - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - if (!plotworld.PLOT_CHAT) { - return; - } - if (getCurrentPlot(event.getPlayer().getLocation()) == null) { - return; - } - String message = event.getMessage(); - String format = C.PLOT_CHAT_FORMAT.s(); - String sender = event.getPlayer().getDisplayName(); - Plot plot = getCurrentPlot(event.getPlayer().getLocation()); - PlotId id = plot.id; - Set recipients = event.getRecipients(); - recipients.clear(); - for (Player p : Bukkit.getOnlinePlayers()) { - if (getCurrentPlot(p.getLocation()) == plot) { - recipients.add(p); - } - } - format = - format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", sender).replaceAll("%msg%", message); - format = ChatColor.translateAlternateColorCodes('&', format); - event.setFormat(format); - } - - @EventHandler( - priority = EventPriority.HIGH) - public static void BlockDestroy(BlockBreakEvent event) { - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (PlotMain.hasPermission(event.getPlayer(),"plots.admin")) { - return; - } - if (isInPlot(event.getBlock().getLocation())) { - Plot plot = getCurrentPlot(event.getBlock().getLocation()); - if (!plot.hasRights(event.getPlayer())) { - event.setCancelled(true); - } - } - if (PlayerFunctions.getPlot(event.getBlock().getLocation()) == null) { - event.setCancelled(true); - } - } - - @EventHandler( - priority = EventPriority.HIGH) - public void BlockCreate(BlockPlaceEvent event) { - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (PlotMain.hasPermission(event.getPlayer(),"plots.admin")) { - return; - } - if (isInPlot(event.getBlock().getLocation())) { - Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation()); - if (!plot.hasRights(event.getPlayer())) { - event.setCancelled(true); - } - } - if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()) == null) { - event.setCancelled(true); - } - } - - @EventHandler - public static void onBigBoom(EntityExplodeEvent event) { - World world = event.getLocation().getWorld(); - if (!isPlotWorld(world)) { - return; - } - event.setCancelled(true); - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL! - EntityChangeBlockEvent event) { - World world = event.getBlock().getWorld(); - if (!isPlotWorld(world)) { - return; - } - Entity e = event.getEntity(); - if (!(e instanceof Player)) { - if (!(e instanceof org.bukkit.entity.FallingBlock)) { - event.setCancelled(true); - } - } - else { - Block b = event.getBlock(); - Player p = (Player) e; - if (!isInPlot(b.getLocation())) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - event.setCancelled(true); - } - } - else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - event.setCancelled(true); - } - } - else - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onEntityBlockForm(final EntityBlockFormEvent event) { - World world = event.getBlock().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if ((!(event.getEntity() instanceof Player))) { - event.setCancelled(true); - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBS(final BlockSpreadEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBF(final BlockFormEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBD(final BlockDamageEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onFade(final BlockFadeEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onChange(final BlockFromToEvent e) { - Block b = e.getToBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onGrow(final BlockGrowEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBlockPistonExtend(final BlockPistonExtendEvent e) { - if (isInPlot(e.getBlock().getLocation())) { - - e.getDirection(); - int modifier = e.getBlocks().size(); - Location l = e.getBlock().getLocation(); - { - if (e.getDirection() == BlockFace.EAST) { - l = e.getBlock().getLocation().subtract(modifier, 0, 0); - } - else - if (e.getDirection() == BlockFace.NORTH) { - l = e.getBlock().getLocation().subtract(0, 0, modifier); - } - else - if (e.getDirection() == BlockFace.SOUTH) { - l = e.getBlock().getLocation().add(0, 0, modifier); - } - else - if (e.getDirection() == BlockFace.WEST) { - l = e.getBlock().getLocation().add(modifier, 0, 0); - } - - if (!isInPlot(l)) { - e.setCancelled(true); - return; - } - } - for (Block b : e.getBlocks()) { - if (!isInPlot(b.getLocation())) { - return; - } - { - if (e.getDirection() == BlockFace.EAST) { - if (!isInPlot(b.getLocation().subtract(1, 0, 0))) { - e.setCancelled(true); - } - } - else - if (e.getDirection() == BlockFace.NORTH) { - if (!isInPlot(b.getLocation().subtract(0, 0, 1))) { - e.setCancelled(true); - } - } - else - if (e.getDirection() == BlockFace.SOUTH) { - if (!isInPlot(b.getLocation().add(0, 0, 1))) { - e.setCancelled(true); - } - } - else - if (e.getDirection() == BlockFace.WEST) { - if (!isInPlot(b.getLocation().add(1, 0, 0))) { - e.setCancelled(true); - } - } - } - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBlockPistonRetract(final BlockPistonRetractEvent e) { - Block b = e.getRetractLocation().getBlock(); - if (isPlotWorld(b.getLocation()) && (e.getBlock().getType() == Material.PISTON_STICKY_BASE)) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onStructureGrow(final StructureGrowEvent e) { - List blocks = e.getBlocks(); - boolean remove = false; - for (int i = blocks.size() - 1; i >= 0; i--) { - if (remove || isPlotWorld(blocks.get(i).getLocation())) { - remove = true; - if (!isInPlot(blocks.get(i).getLocation())) { - e.getBlocks().remove(i); - } - } - } - } - - @EventHandler - public static void onInteract(PlayerInteractEvent event) { - if (event.getClickedBlock() == null) { - return; - } - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (PlotMain.hasPermission(event.getPlayer(),"plots.admin")) { - return; - } - if (isInPlot(event.getClickedBlock().getLocation())) { - Plot plot = getCurrentPlot(event.getClickedBlock().getLocation()); - - // They shouldn't be allowed to access other people's chests - - // if (new ArrayList<>(Arrays.asList(new Material[] { - // Material.STONE_BUTTON, Material.WOOD_BUTTON, - // Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, - // Material.CHEST, Material.TRAPPED_CHEST, Material.TRAP_DOOR, - // Material.WOOD_DOOR, Material.WOODEN_DOOR, - // Material.DISPENSER, Material.DROPPER - // - // })).contains(event.getClickedBlock().getType())) { - // return; - // } - - if(PlotMain.booleanFlags.containsKey(event.getClickedBlock().getType())) { - String flag = PlotMain.booleanFlags.get(event.getClickedBlock().getType()); - if(plot.settings.getFlag(flag) != null && getFlagValue(plot.settings.getFlag(flag).getValue())) - return; - } - - if (!plot.hasRights(event.getPlayer())) { - event.setCancelled(true); - } - } - if (PlayerFunctions.getPlot(event.getClickedBlock().getLocation()) == null) { - event.setCancelled(true); - } - } - - @EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true) - public static void MobSpawn(CreatureSpawnEvent event) { - World world = event.getLocation().getWorld(); + @EventHandler(priority = EventPriority.HIGHEST) + public static void onChat(final AsyncPlayerChatEvent event) { + final World world = event.getPlayer().getWorld(); if (!isPlotWorld(world)) { return; } - PlotWorld pW = getPlotWorld(world); - CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); - if (reason == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && pW.SPAWN_EGGS) { - return; - } else if (reason == CreatureSpawnEvent.SpawnReason.BREEDING && pW.SPAWN_BREEDING) { - return; - } else if (reason == CreatureSpawnEvent.SpawnReason.CUSTOM && pW.SPAWN_CUSTOM) { + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + if (!plotworld.PLOT_CHAT) { return; } - if (event.getEntity() instanceof Player) { - return; - } - if (!isInPlot(event.getLocation())) { - event.setCancelled(true); - } - } + if (getCurrentPlot(event.getPlayer().getLocation()) == null) { + return; + } + final String message = event.getMessage(); + String format = C.PLOT_CHAT_FORMAT.s(); + final String sender = event.getPlayer().getDisplayName(); + final Plot plot = getCurrentPlot(event.getPlayer().getLocation()); + final PlotId id = plot.id; + final Set recipients = event.getRecipients(); + recipients.clear(); + for (final Player p : Bukkit.getOnlinePlayers()) { + if (getCurrentPlot(p.getLocation()) == plot) { + recipients.add(p); + } + } + format = format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", sender).replaceAll("%msg%", message); + format = ChatColor.translateAlternateColorCodes('&', format); + event.setFormat(format); + } - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBlockIgnite(final BlockIgniteEvent e) { - if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { - e.setCancelled(true); - return; - } - Block b = e.getBlock(); - if (b != null) { - if (e.getPlayer() != null) { - Player p = e.getPlayer(); - if (!isInPlot(b.getLocation())) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - e.setCancelled(true); - } - } - else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - e.setCancelled(true); - } - } - else - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - e.setCancelled(true); - } - } - } - } - else { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH) + public static void BlockDestroy(final BlockBreakEvent event) { + final World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (PlotMain.hasPermission(event.getPlayer(), "plots.admin")) { + return; + } + if (isInPlot(event.getBlock().getLocation())) { + final Plot plot = getCurrentPlot(event.getBlock().getLocation()); + if (!plot.hasRights(event.getPlayer())) { + event.setCancelled(true); + } + } + if (PlayerFunctions.getPlot(event.getBlock().getLocation()) == null) { + event.setCancelled(true); + } + } - @EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true) - public static void onTeleport(PlayerTeleportEvent event) { - Location f = event.getFrom(); - Location t = event.getTo(); - Location q = new Location(t.getWorld(),t.getBlockX(), 64, t.getZ()); - - - if (isPlotWorld(q)) { - if (isInPlot(q)) { - Plot plot = getCurrentPlot(event.getTo()); - if (plot.deny_entry(event.getPlayer())) { - PlayerFunctions.sendMessage(event.getPlayer(), C.YOU_BE_DENIED); - event.setCancelled(true); - } - else { - if (enteredPlot(f, t)) { - plotEntry(event.getPlayer(), plot); - } - } - } - else { - if (leftPlot(f, t)) { - Plot plot = getCurrentPlot(event.getFrom()); - plotExit(event.getPlayer(), plot); - } - } - if ((event.getTo().getBlockX() >= 29999999) || (event.getTo().getBlockX() <= -29999999) - || (event.getTo().getBlockZ() >= 29999999) || (event.getTo().getBlockZ() <= -29999999)) { - event.setCancelled(true); - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBucketEmpty(PlayerBucketEmptyEvent e) { - if (!PlotMain.hasPermission(e.getPlayer(),"plots.admin")) { - BlockFace bf = e.getBlockFace(); - Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); - e.setCancelled(true); - } - else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); - e.setCancelled(true); - } - else - if (!plot.hasRights(e.getPlayer())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - } - } - } - - @EventHandler( - priority = EventPriority.HIGHEST) - public static void onInventoryClick(InventoryClickEvent event) { - if (event.getInventory().getName().equalsIgnoreCase("PlotSquared Commands")) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGH) + public void BlockCreate(final BlockPlaceEvent event) { + final World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (PlotMain.hasPermission(event.getPlayer(), "plots.admin")) { + return; + } + if (isInPlot(event.getBlock().getLocation())) { + final Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation()); + if (!plot.hasRights(event.getPlayer())) { + event.setCancelled(true); + } + } + if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()) == null) { + event.setCancelled(true); + } + } @EventHandler - public static void onLeave(PlayerQuitEvent event) { - if(PlotSelection.currentSelection.containsKey(event.getPlayer().getName())) { + public static void onBigBoom(final EntityExplodeEvent event) { + final World world = event.getLocation().getWorld(); + if (!isPlotWorld(world)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL! + final EntityChangeBlockEvent event) { + final World world = event.getBlock().getWorld(); + if (!isPlotWorld(world)) { + return; + } + final Entity e = event.getEntity(); + if (!(e instanceof Player)) { + if (!(e instanceof org.bukkit.entity.FallingBlock)) { + event.setCancelled(true); + } + } + else { + final Block b = event.getBlock(); + final Player p = (Player) e; + if (!isInPlot(b.getLocation())) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + event.setCancelled(true); + } + } + else { + final Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + event.setCancelled(true); + } + } + else if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + event.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onEntityBlockForm(final EntityBlockFormEvent event) { + final World world = event.getBlock().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if ((!(event.getEntity() instanceof Player))) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBS(final BlockSpreadEvent e) { + final Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBF(final BlockFormEvent e) { + final Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBD(final BlockDamageEvent e) { + final Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onFade(final BlockFadeEvent e) { + final Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onChange(final BlockFromToEvent e) { + final Block b = e.getToBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onGrow(final BlockGrowEvent e) { + final Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBlockPistonExtend(final BlockPistonExtendEvent e) { + if (isInPlot(e.getBlock().getLocation())) { + + e.getDirection(); + final int modifier = e.getBlocks().size(); + Location l = e.getBlock().getLocation(); + { + if (e.getDirection() == BlockFace.EAST) { + l = e.getBlock().getLocation().subtract(modifier, 0, 0); + } + else if (e.getDirection() == BlockFace.NORTH) { + l = e.getBlock().getLocation().subtract(0, 0, modifier); + } + else if (e.getDirection() == BlockFace.SOUTH) { + l = e.getBlock().getLocation().add(0, 0, modifier); + } + else if (e.getDirection() == BlockFace.WEST) { + l = e.getBlock().getLocation().add(modifier, 0, 0); + } + + if (!isInPlot(l)) { + e.setCancelled(true); + return; + } + } + for (final Block b : e.getBlocks()) { + if (!isInPlot(b.getLocation())) { + return; + } + { + if (e.getDirection() == BlockFace.EAST) { + if (!isInPlot(b.getLocation().subtract(1, 0, 0))) { + e.setCancelled(true); + } + } + else if (e.getDirection() == BlockFace.NORTH) { + if (!isInPlot(b.getLocation().subtract(0, 0, 1))) { + e.setCancelled(true); + } + } + else if (e.getDirection() == BlockFace.SOUTH) { + if (!isInPlot(b.getLocation().add(0, 0, 1))) { + e.setCancelled(true); + } + } + else if (e.getDirection() == BlockFace.WEST) { + if (!isInPlot(b.getLocation().add(1, 0, 0))) { + e.setCancelled(true); + } + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBlockPistonRetract(final BlockPistonRetractEvent e) { + final Block b = e.getRetractLocation().getBlock(); + if (isPlotWorld(b.getLocation()) && (e.getBlock().getType() == Material.PISTON_STICKY_BASE)) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onStructureGrow(final StructureGrowEvent e) { + final List blocks = e.getBlocks(); + boolean remove = false; + for (int i = blocks.size() - 1; i >= 0; i--) { + if (remove || isPlotWorld(blocks.get(i).getLocation())) { + remove = true; + if (!isInPlot(blocks.get(i).getLocation())) { + e.getBlocks().remove(i); + } + } + } + } + + @EventHandler + public static void onInteract(final PlayerInteractEvent event) { + if (event.getClickedBlock() == null) { + return; + } + final World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (PlotMain.hasPermission(event.getPlayer(), "plots.admin")) { + return; + } + if (isInPlot(event.getClickedBlock().getLocation())) { + final Plot plot = getCurrentPlot(event.getClickedBlock().getLocation()); + + // They shouldn't be allowed to access other people's chests + + // if (new ArrayList<>(Arrays.asList(new Material[] { + // Material.STONE_BUTTON, Material.WOOD_BUTTON, + // Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, + // Material.CHEST, Material.TRAPPED_CHEST, Material.TRAP_DOOR, + // Material.WOOD_DOOR, Material.WOODEN_DOOR, + // Material.DISPENSER, Material.DROPPER + // + // })).contains(event.getClickedBlock().getType())) { + // return; + // } + + if (PlotMain.booleanFlags.containsKey(event.getClickedBlock().getType())) { + final String flag = PlotMain.booleanFlags.get(event.getClickedBlock().getType()); + if ((plot.settings.getFlag(flag) != null) && getFlagValue(plot.settings.getFlag(flag).getValue())) { + return; + } + } + + if (!plot.hasRights(event.getPlayer())) { + event.setCancelled(true); + } + } + if (PlayerFunctions.getPlot(event.getClickedBlock().getLocation()) == null) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public static void MobSpawn(final CreatureSpawnEvent event) { + final World world = event.getLocation().getWorld(); + if (!isPlotWorld(world)) { + return; + } + final PlotWorld pW = getPlotWorld(world); + final CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); + if ((reason == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG) && pW.SPAWN_EGGS) { + return; + } + else if ((reason == CreatureSpawnEvent.SpawnReason.BREEDING) && pW.SPAWN_BREEDING) { + return; + } + else if ((reason == CreatureSpawnEvent.SpawnReason.CUSTOM) && pW.SPAWN_CUSTOM) { + return; + } + if (event.getEntity() instanceof Player) { + return; + } + if (!isInPlot(event.getLocation())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBlockIgnite(final BlockIgniteEvent e) { + if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { + e.setCancelled(true); + return; + } + final Block b = e.getBlock(); + if (b != null) { + if (e.getPlayer() != null) { + final Player p = e.getPlayer(); + if (!isInPlot(b.getLocation())) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + e.setCancelled(true); + } + } + else { + final Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + e.setCancelled(true); + } + } + else if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + e.setCancelled(true); + } + } + } + } + else { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public static void onTeleport(final PlayerTeleportEvent event) { + final Location f = event.getFrom(); + final Location t = event.getTo(); + final Location q = new Location(t.getWorld(), t.getBlockX(), 64, t.getZ()); + + if (isPlotWorld(q)) { + if (isInPlot(q)) { + final Plot plot = getCurrentPlot(event.getTo()); + if (plot.deny_entry(event.getPlayer())) { + PlayerFunctions.sendMessage(event.getPlayer(), C.YOU_BE_DENIED); + event.setCancelled(true); + } + else { + if (enteredPlot(f, t)) { + plotEntry(event.getPlayer(), plot); + } + } + } + else { + if (leftPlot(f, t)) { + final Plot plot = getCurrentPlot(event.getFrom()); + plotExit(event.getPlayer(), plot); + } + } + if ((event.getTo().getBlockX() >= 29999999) || (event.getTo().getBlockX() <= -29999999) || (event.getTo().getBlockZ() >= 29999999) || (event.getTo().getBlockZ() <= -29999999)) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBucketEmpty(final PlayerBucketEmptyEvent e) { + if (!PlotMain.hasPermission(e.getPlayer(), "plots.admin")) { + final BlockFace bf = e.getBlockFace(); + final Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); + e.setCancelled(true); + } + else { + final Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); + e.setCancelled(true); + } + else if (!plot.hasRights(e.getPlayer())) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public static void onInventoryClick(final InventoryClickEvent event) { + if (event.getInventory().getName().equalsIgnoreCase("PlotSquared Commands")) { + event.setCancelled(true); + } + } + + @EventHandler + public static void onLeave(final PlayerQuitEvent event) { + if (PlotSelection.currentSelection.containsKey(event.getPlayer().getName())) { PlotSelection.currentSelection.remove(event.getPlayer().getName()); } - if(Setup.setupMap.containsKey(event.getPlayer().getName())) { + if (Setup.setupMap.containsKey(event.getPlayer().getName())) { Setup.setupMap.remove(event.getPlayer().getName()); } - if(Settings.DELETE_PLOTS_ON_BAN && event.getPlayer().isBanned()) { - Set plots = PlotMain.getPlots(event.getPlayer()); - for(Plot plot : plots) { - PlotManager manager = PlotMain.getPlotManager(plot.getWorld()); + if (Settings.DELETE_PLOTS_ON_BAN && event.getPlayer().isBanned()) { + final Set plots = PlotMain.getPlots(event.getPlayer()); + for (final Plot plot : plots) { + final PlotManager manager = PlotMain.getPlotManager(plot.getWorld()); manager.clearPlot(null, plot); DBFunc.delete(plot.getWorld().getName(), plot); PlotMain.sendConsoleSenderMessage(String.format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned", plot.getId(), event.getPlayer().getName())); @@ -580,204 +589,195 @@ public class PlayerEvents extends com.intellectualcrafters.plot.listeners.PlotLi } } - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onBucketFill(PlayerBucketFillEvent e) { - if (!PlotMain.hasPermission(e.getPlayer(),"plots.admin")) { - Block b = e.getBlockClicked(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); - e.setCancelled(true); - } - else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); - e.setCancelled(true); - } - else - if (!plot.hasRights(e.getPlayer())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onBucketFill(final PlayerBucketFillEvent e) { + if (!PlotMain.hasPermission(e.getPlayer(), "plots.admin")) { + final Block b = e.getBlockClicked(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); + e.setCancelled(true); + } + else { + final Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); + e.setCancelled(true); + } + else if (!plot.hasRights(e.getPlayer())) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + } + } + } - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onHangingPlace(final HangingPlaceEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - Player p = e.getPlayer(); - if (!isInPlot(b.getLocation())) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onHangingPlace(final HangingPlaceEvent e) { + final Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + final Player p = e.getPlayer(); + if (!isInPlot(b.getLocation())) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else { + final Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + } + } + } - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { - Entity r = e.getRemover(); - if (r instanceof Player) { - Player p = (Player) r; - Location l = e.getEntity().getLocation(); - if (isPlotWorld(l)) { - if (!isInPlot(l)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { + final Entity r = e.getRemover(); + if (r instanceof Player) { + final Player p = (Player) r; + final Location l = e.getEntity().getLocation(); + if (isPlotWorld(l)) { + if (!isInPlot(l)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else { + final Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + } + } + } + } - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { - Location l = e.getRightClicked().getLocation(); - if (isPlotWorld(l)) { - Player p = e.getPlayer(); - if (!isInPlot(l)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - } - } - } - - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { - Location l = e.getEntity().getLocation(); - Entity d = e.getDamager(); - Entity a = e.getEntity(); + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { + final Location l = e.getRightClicked().getLocation(); if (isPlotWorld(l)) { - if (d instanceof Player) { - Player p = (Player) d; - boolean aPlr = a instanceof Player; - PlotWorld pW = getPlotWorld(l.getWorld()); - if(!aPlr && pW.PVE) { - return; - } else if(aPlr && pW.PVP) { + final Player p = e.getPlayer(); + if (!isInPlot(l)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else { + final Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { + final Location l = e.getEntity().getLocation(); + final Entity d = e.getDamager(); + final Entity a = e.getEntity(); + if (isPlotWorld(l)) { + if (d instanceof Player) { + final Player p = (Player) d; + final boolean aPlr = a instanceof Player; + final PlotWorld pW = getPlotWorld(l.getWorld()); + if (!aPlr && pW.PVE) { return; } - if (!isInPlot(l)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); + else if (aPlr && pW.PVP) { + return; + } + if (!isInPlot(l)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + else { + final Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); return; - } - } - else - if(aPlr && !booleanFlag(plot, "pvp")) - return; - if(!aPlr && !booleanFlag(plot, "pve")) - return; - assert plot != null; - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setCancelled(true); - } - } - } - } - } - } + } + } + else if (aPlr && !booleanFlag(plot, "pvp")) { + return; + } + if (!aPlr && !booleanFlag(plot, "pve")) { + return; + } + assert plot != null; + if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setCancelled(true); + } + } + } + } + } + } - @EventHandler( - priority = EventPriority.HIGH, ignoreCancelled = true) - public static void onPlayerEggThrow(final PlayerEggThrowEvent e) { - Location l = e.getEgg().getLocation(); - if (isPlotWorld(l)) { - Player p = e.getPlayer(); - if (!isInPlot(l)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setHatching(false); - } - } - else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setHatching(false); - } - } - else - if (!plot.hasRights(p)) { - if (!PlotMain.hasPermission(p,"plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); - e.setHatching(false); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public static void onPlayerEggThrow(final PlayerEggThrowEvent e) { + final Location l = e.getEgg().getLocation(); + if (isPlotWorld(l)) { + final Player p = e.getPlayer(); + if (!isInPlot(l)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setHatching(false); + } + } + else { + final Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setHatching(false); + } + } + else if (!plot.hasRights(p)) { + if (!PlotMain.hasPermission(p, "plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PLOT_PERMS); + e.setHatching(false); + } + } + } + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotListener.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotListener.java index 69ccf568b..6c441f46b 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotListener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotListener.java @@ -1,72 +1,87 @@ package com.intellectualcrafters.plot.listeners; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.events.PlayerEnterPlotEvent; -import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.UUID; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.WeatherType; +import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.UUID; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.FlagManager; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotManager; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.Settings; +import com.intellectualcrafters.plot.Title; +import com.intellectualcrafters.plot.UUIDHandler; +import com.intellectualcrafters.plot.events.PlayerEnterPlotEvent; +import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent; /** * Created by Citymonstret on 2014-10-21. */ public class PlotListener { - public static void textures(Player p) { + public static void textures(final Player p) { if ((Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1) && isPlotWorld(p.getWorld())) { p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); } } - public static boolean isInPlot(Player player) { + public static boolean isInPlot(final Player player) { return PlayerFunctions.isInPlot(player); } - public static Plot getPlot(Player player) { + public static Plot getPlot(final Player player) { return PlayerFunctions.getCurrentPlot(player); } - public static boolean isPlotWorld(World world) { + public static boolean isPlotWorld(final World world) { return PlotMain.isPlotWorld(world); } - public static PlotWorld getPlotWorld(World world) { + public static PlotWorld getPlotWorld(final World world) { return PlotMain.getWorldSettings(world); } - public static String getName(UUID uuid) { + public static String getName(final UUID uuid) { return UUIDHandler.getName(uuid); } - public static UUID getUUID(String name) { + public static UUID getUUID(final String name) { return UUIDHandler.getUUID(name); } - + // unused - public static void blockChange(Block block, Cancellable event) { - Location loc = block.getLocation(); - String world = loc.getWorld().getName(); - PlotManager manager = PlotMain.getPlotManager(world); - if (manager!=null) { - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotId id = manager.getPlotId(plotworld, loc); - if (id==null) { + public static void blockChange(final Block block, final Cancellable event) { + final Location loc = block.getLocation(); + final String world = loc.getWorld().getName(); + final PlotManager manager = PlotMain.getPlotManager(world); + if (manager != null) { + final PlotWorld plotworld = PlotMain.getWorldSettings(world); + final PlotId id = manager.getPlotId(plotworld, loc); + if (id == null) { event.setCancelled(true); } } return; } - public static boolean enteredPlot(Location l1, Location l2) { - PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(), l1.getBlockX(), 64, l1.getBlockZ())); - PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(), l2.getBlockX(), 64, l2.getBlockZ())); + public static boolean enteredPlot(final Location l1, final Location l2) { + final PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(), l1.getBlockX(), 64, l1.getBlockZ())); + final PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(), l2.getBlockX(), 64, l2.getBlockZ())); if (p2 == null) { return false; } @@ -79,9 +94,9 @@ public class PlotListener { return true; } - public static boolean leftPlot(Location l1, Location l2) { - PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(), l1.getBlockX(), 64, l1.getBlockZ())); - PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(), l2.getBlockX(), 64, l2.getBlockZ())); + public static boolean leftPlot(final Location l1, final Location l2) { + final PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(), l1.getBlockX(), 64, l1.getBlockZ())); + final PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(), l2.getBlockX(), 64, l2.getBlockZ())); if (p1 == null) { return false; } @@ -94,20 +109,20 @@ public class PlotListener { return true; } - public static boolean isPlotWorld(Location l) { + public static boolean isPlotWorld(final Location l) { return PlotMain.isPlotWorld(l.getWorld()); } - public static boolean isInPlot(Location loc) { + public static boolean isInPlot(final Location loc) { return getCurrentPlot(loc) != null; } - public static Plot getCurrentPlot(Location loc) { - PlotId id = PlayerFunctions.getPlot(loc); + public static Plot getCurrentPlot(final Location loc) { + final PlotId id = PlayerFunctions.getPlot(loc); if (id == null) { return null; } - World world = loc.getWorld(); + final World world = loc.getWorld(); if (PlotMain.getPlots(world).containsKey(id)) { return PlotMain.getPlots(world).get(id); } @@ -116,19 +131,20 @@ public class PlotListener { private static WeatherType getWeatherType(String str) { str = str.toLowerCase(); - if(str.equals("rain")) { + if (str.equals("rain")) { return WeatherType.DOWNFALL; - } else { + } + else { return WeatherType.CLEAR; } } - public static boolean booleanFlag(Plot plot, String flag) { - return plot.settings.getFlag(flag) != null && getBooleanFlag(plot.settings.getFlag(flag).getValue()).equals("true"); + public static boolean booleanFlag(final Plot plot, final String flag) { + return (plot.settings.getFlag(flag) != null) && getBooleanFlag(plot.settings.getFlag(flag).getValue()).equals("true"); } - private static String getBooleanFlag(String value) { - switch(value) { + private static String getBooleanFlag(final String value) { + switch (value) { case "on": case "1": case "true": @@ -144,7 +160,7 @@ public class PlotListener { } } - private static GameMode getGameMode(String str) { + private static GameMode getGameMode(final String str) { switch (str) { case "creative": return GameMode.CREATIVE; @@ -157,65 +173,66 @@ public class PlotListener { } } - public static void plotEntry(Player player, Plot plot) { + public static void plotEntry(final Player player, final Plot plot) { if (plot.hasOwner()) { - if(plot.settings.getFlag("gamemode") != null) { + if (plot.settings.getFlag("gamemode") != null) { player.setGameMode(getGameMode(plot.settings.getFlag("gamemode").getValue())); } - if(plot.settings.getFlag("fly") != null) { + if (plot.settings.getFlag("fly") != null) { player.setAllowFlight(getFlagValue(plot.settings.getFlag("fly").getValue())); } - if(plot.settings.getFlag("time") != null) { + if (plot.settings.getFlag("time") != null) { try { - Long time = Long.parseLong(plot.settings.getFlag("time").getValue()); + final Long time = Long.parseLong(plot.settings.getFlag("time").getValue()); player.setPlayerTime(time, true); - } catch(Exception e) { + } + catch (final Exception e) { plot.settings.setFlags(FlagManager.removeFlag(plot.settings.getFlags(), "time")); } } - if(plot.settings.getFlag("weather") != null) { + if (plot.settings.getFlag("weather") != null) { player.setPlayerWeather(getWeatherType(plot.settings.getFlag("weather").getValue())); } - if (booleanFlag(plot, "titles") && Settings.TITLES && C.TITLE_ENTERED_PLOT.s().length() > 2) { - String sTitleMain = C.TITLE_ENTERED_PLOT.s().replaceFirst("%s", plot.getDisplayName()); - String sTitleSub = C.TITLE_ENTERED_PLOT_SUB.s().replaceFirst("%s", getName(plot.owner)); - ChatColor sTitleMainColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_COLOR.s()); - ChatColor sTitleSubColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_SUB_COLOR.s()); - Title title = new Title(sTitleMain, sTitleSub, 10, 20, 10); + if (booleanFlag(plot, "titles") && Settings.TITLES && (C.TITLE_ENTERED_PLOT.s().length() > 2)) { + final String sTitleMain = C.TITLE_ENTERED_PLOT.s().replaceFirst("%s", plot.getDisplayName()); + final String sTitleSub = C.TITLE_ENTERED_PLOT_SUB.s().replaceFirst("%s", getName(plot.owner)); + final ChatColor sTitleMainColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_COLOR.s()); + final ChatColor sTitleSubColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_SUB_COLOR.s()); + final Title title = new Title(sTitleMain, sTitleSub, 10, 20, 10); title.setTitleColor(sTitleMainColor); title.setSubtitleColor(sTitleSubColor); title.setTimingsToTicks(); title.send(player); } { - PlayerEnterPlotEvent callEvent = new PlayerEnterPlotEvent(player, plot); + final PlayerEnterPlotEvent callEvent = new PlayerEnterPlotEvent(player, plot); Bukkit.getPluginManager().callEvent(callEvent); } PlayerFunctions.sendMessage(player, plot.settings.getJoinMessage()); } } - public static void plotExit(Player player, Plot plot) { + public static void plotExit(final Player player, final Plot plot) { { - PlayerLeavePlotEvent callEvent = new PlayerLeavePlotEvent(player, plot); + final PlayerLeavePlotEvent callEvent = new PlayerLeavePlotEvent(player, plot); Bukkit.getPluginManager().callEvent(callEvent); } - if(plot.settings.getFlag("fly") != null) { + if (plot.settings.getFlag("fly") != null) { player.setAllowFlight(Bukkit.getAllowFlight()); } - if(plot.settings.getFlag("gamemode") != null) { + if (plot.settings.getFlag("gamemode") != null) { player.setGameMode(Bukkit.getDefaultGameMode()); } - if(plot.settings.getFlag("time") != null) { + if (plot.settings.getFlag("time") != null) { player.resetPlayerTime(); } - if(plot.settings.getFlag("weather") != null) { + if (plot.settings.getFlag("weather") != null) { player.resetPlayerWeather(); } PlayerFunctions.sendMessage(player, plot.settings.getLeaveMessage()); } - public static boolean getFlagValue(String value) { + public static boolean getFlagValue(final String value) { return Arrays.asList("true", "on", "enabled", "yes").contains(value.toLowerCase()); } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotPlusListener.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotPlusListener.java index 1b7afeca2..c504f5d26 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotPlusListener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/PlotPlusListener.java @@ -1,11 +1,17 @@ package com.intellectualcrafters.plot.listeners; -import com.intellectualcrafters.plot.C; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.events.PlayerEnterPlotEvent; -import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent; -import org.bukkit.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Effect; +import org.bukkit.GameMode; +import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -19,7 +25,11 @@ import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; -import java.util.*; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.events.PlayerEnterPlotEvent; +import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent; /** * Created by Citymonstret on 2014-10-30. @@ -29,30 +39,30 @@ public class PlotPlusListener extends PlotListener implements Listener { private static HashMap feedRunnable = new HashMap<>(); private static HashMap healRunnable = new HashMap<>(); - public static void startRunnable(JavaPlugin plugin) { + public static void startRunnable(final JavaPlugin plugin) { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { @Override public void run() { - for(Map.Entry entry : feedRunnable.entrySet()) { - Interval value = entry.getValue(); + for (final Map.Entry entry : feedRunnable.entrySet()) { + final Interval value = entry.getValue(); ++value.count; - if(value.count == value.interval) { + if (value.count == value.interval) { value.count = 0; - Player player = Bukkit.getPlayer(entry.getKey()); - int level = player.getFoodLevel(); - if(level != value.max) { + final Player player = Bukkit.getPlayer(entry.getKey()); + final int level = player.getFoodLevel(); + if (level != value.max) { player.setFoodLevel(Math.min(level + value.amount, value.max)); } } } - for(Map.Entry entry : healRunnable.entrySet()) { - Interval value = entry.getValue(); + for (final Map.Entry entry : healRunnable.entrySet()) { + final Interval value = entry.getValue(); ++value.count; - if(value.count == value.interval) { - value.count = 0; - Player player = Bukkit.getPlayer(entry.getKey()); - double level = player.getHealth(); - if(level != value.max) { + if (value.count == value.interval) { + value.count = 0; + final Player player = Bukkit.getPlayer(entry.getKey()); + final double level = player.getHealth(); + if (level != value.max) { player.setHealth(Math.min(level + value.amount, value.max)); } } @@ -62,35 +72,38 @@ public class PlotPlusListener extends PlotListener implements Listener { } @EventHandler - public void onInventoryClick(InventoryClickEvent event) { - Player player = (Player) event.getWhoClicked(); - if(!event.getInventory().getName().equals(ChatColor.RED + "Plot Jukebox")) + public void onInventoryClick(final InventoryClickEvent event) { + final Player player = (Player) event.getWhoClicked(); + if (!event.getInventory().getName().equals(ChatColor.RED + "Plot Jukebox")) { return; + } event.setCancelled(true); - if(!isInPlot(player)) { + if (!isInPlot(player)) { PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); return; } - Plot plot = getPlot(player); - if(!plot.hasRights(player)) { + final Plot plot = getPlot(player); + if (!plot.hasRights(player)) { PlayerFunctions.sendMessage(player, C.NO_PLOT_PERMS); return; } - Set plotPlayers = new HashSet<>(); - for(Player p : player.getWorld().getPlayers()) { - if(isInPlot(p) && getPlot(p).equals(plot)) + final Set plotPlayers = new HashSet<>(); + for (final Player p : player.getWorld().getPlayers()) { + if (isInPlot(p) && getPlot(p).equals(plot)) { plotPlayers.add(p); + } } RecordMeta meta = null; - for(RecordMeta m : RecordMeta.metaList) { - if(m.getMaterial() == event.getCurrentItem().getType()) { + for (final RecordMeta m : RecordMeta.metaList) { + if (m.getMaterial() == event.getCurrentItem().getType()) { meta = m; break; } } - if(meta == null) + if (meta == null) { return; - for(Player p : plotPlayers) { + } + for (final Player p : plotPlayers) { p.playEffect(p.getLocation(), Effect.RECORD_PLAY, meta.getMaterial()); PlayerFunctions.sendMessage(p, C.RECORD_PLAY.s().replaceAll("%player", player.getName()).replaceAll("%name", meta.toString())); } @@ -98,85 +111,104 @@ public class PlotPlusListener extends PlotListener implements Listener { } @EventHandler(priority = EventPriority.HIGH) - public void onInteract(BlockDamageEvent event) { - Player player = event.getPlayer(); - if(player.getGameMode() != GameMode.SURVIVAL) return; - if(!isInPlot(player)) return; - Plot plot = getPlot(player); - if(booleanFlag(plot, "instabreak")) + public void onInteract(final BlockDamageEvent event) { + final Player player = event.getPlayer(); + if (player.getGameMode() != GameMode.SURVIVAL) { + return; + } + if (!isInPlot(player)) { + return; + } + final Plot plot = getPlot(player); + if (booleanFlag(plot, "instabreak")) { event.getBlock().breakNaturally(); + } } @EventHandler(priority = EventPriority.HIGH) - public void onDamage(EntityDamageEvent event) { - if(event.getEntityType() != EntityType.PLAYER) + public void onDamage(final EntityDamageEvent event) { + if (event.getEntityType() != EntityType.PLAYER) { return; - Player player = (Player) event.getEntity(); - if(!isInPlot(player)) return; - if(booleanFlag(getPlot(player), "invincible")) + } + final Player player = (Player) event.getEntity(); + if (!isInPlot(player)) { + return; + } + if (booleanFlag(getPlot(player), "invincible")) { event.setCancelled(true); + } } - @EventHandler public void onItemPickup(PlayerPickupItemEvent event) { if(isInPlot(event.getPlayer()) && !getPlot(event.getPlayer()).hasRights(event.getPlayer()) && booleanFlag(getPlot(event.getPlayer()), "drop-protection")) event.setCancelled(true); } - - @EventHandler public void onItemDrop(PlayerDropItemEvent event) { if(isInPlot(event.getPlayer()) && !getPlot(event.getPlayer()).hasRights(event.getPlayer()) && booleanFlag(getPlot(event.getPlayer()), "item-drop")) event.setCancelled(true);} + @EventHandler + public void onItemPickup(final PlayerPickupItemEvent event) { + if (isInPlot(event.getPlayer()) && !getPlot(event.getPlayer()).hasRights(event.getPlayer()) && booleanFlag(getPlot(event.getPlayer()), "drop-protection")) { + event.setCancelled(true); + } + } @EventHandler - public void onPlotEnter(PlayerEnterPlotEvent event) { - Plot plot = event.getPlot(); - if(plot.settings.getFlag("greeting") != null) { + public void onItemDrop(final PlayerDropItemEvent event) { + if (isInPlot(event.getPlayer()) && !getPlot(event.getPlayer()).hasRights(event.getPlayer()) && booleanFlag(getPlot(event.getPlayer()), "item-drop")) { + event.setCancelled(true); + } + } + + @EventHandler + public void onPlotEnter(final PlayerEnterPlotEvent event) { + final Plot plot = event.getPlot(); + if (plot.settings.getFlag("greeting") != null) { event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', plot.settings.getFlag("greeting").getValue())); } - if(booleanFlag(plot, "notify-enter")) { - if(plot.hasOwner()) { - Player player = Bukkit.getPlayer(plot.getOwner()); - if(player == null) return; - if(player.getUniqueId().equals(event.getPlayer().getUniqueId())) + if (booleanFlag(plot, "notify-enter")) { + if (plot.hasOwner()) { + final Player player = Bukkit.getPlayer(plot.getOwner()); + if (player == null) { return; - if(player.isOnline()) { - PlayerFunctions.sendMessage(player, - C.NOTIFY_ENTER - .s() - .replace("%player", event.getPlayer().getName()) - .replace("%plot", plot.getId().toString())); + } + if (player.getUniqueId().equals(event.getPlayer().getUniqueId())) { + return; + } + if (player.isOnline()) { + PlayerFunctions.sendMessage(player, C.NOTIFY_ENTER.s().replace("%player", event.getPlayer().getName()).replace("%plot", plot.getId().toString())); } } } } + @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - if (feedRunnable.containsKey(event.getPlayer().getName()) ) { + public void onPlayerQuit(final PlayerQuitEvent event) { + if (feedRunnable.containsKey(event.getPlayer().getName())) { feedRunnable.remove(event.getPlayer().getName()); } - if (healRunnable.containsKey(event.getPlayer().getName()) ) { + if (healRunnable.containsKey(event.getPlayer().getName())) { healRunnable.remove(event.getPlayer().getName()); } } + @EventHandler - public void onPlotLeave(PlayerLeavePlotEvent event) { + public void onPlotLeave(final PlayerLeavePlotEvent event) { event.getPlayer().playEffect(event.getPlayer().getLocation(), Effect.RECORD_PLAY, 0); - Plot plot = event.getPlot(); - if(plot.settings.getFlag("farewell") != null) { + final Plot plot = event.getPlot(); + if (plot.settings.getFlag("farewell") != null) { event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', plot.settings.getFlag("farewell").getValue())); } - if (feedRunnable.containsKey(event.getPlayer().getName()) ) { + if (feedRunnable.containsKey(event.getPlayer().getName())) { feedRunnable.remove(event.getPlayer().getName()); } - if (healRunnable.containsKey(event.getPlayer().getName()) ) { + if (healRunnable.containsKey(event.getPlayer().getName())) { healRunnable.remove(event.getPlayer().getName()); } - if(booleanFlag(plot, "notify-leave")) { - if(plot.hasOwner()) { - Player player = Bukkit.getPlayer(plot.getOwner()); - if(player == null) return; - if(player.getUniqueId().equals(event.getPlayer().getUniqueId())) + if (booleanFlag(plot, "notify-leave")) { + if (plot.hasOwner()) { + final Player player = Bukkit.getPlayer(plot.getOwner()); + if (player == null) { return; - if(player.isOnline()) { - PlayerFunctions.sendMessage(player, - C.NOTIFY_LEAVE - .s() - .replace("%player", event.getPlayer().getName()) - .replace("%plot", plot.getId().toString())); + } + if (player.getUniqueId().equals(event.getPlayer().getUniqueId())) { + return; + } + if (player.isOnline()) { + PlayerFunctions.sendMessage(player, C.NOTIFY_LEAVE.s().replace("%player", event.getPlayer().getName()).replace("%plot", plot.getId().toString())); } } } @@ -187,7 +219,8 @@ public class PlotPlusListener extends PlotListener implements Listener { public int amount; public int count = 0; public int max; - public Interval(int interval, int amount, int max) { + + public Interval(final int interval, final int amount, final int max) { this.interval = interval; this.amount = amount; this.max = max; @@ -200,25 +233,23 @@ public class PlotPlusListener extends PlotListener implements Listener { public static class RecordMeta { public static List metaList = new ArrayList<>(); static { - for(int x = 3; x < 12; x++) { - metaList.add( - new RecordMeta( - x + "", - Material.valueOf("RECORD_" + x) - ) - ); + for (int x = 3; x < 12; x++) { + metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x))); } } - private String name; - private Material material; - public RecordMeta(String name, Material material) { + private final String name; + private final Material material; + + public RecordMeta(final String name, final Material material) { this.name = name; this.material = material; } + @Override public String toString() { return this.name; } + public Material getMaterial() { return this.material; } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldEditListener.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldEditListener.java index bb32274cd..71106d562 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldEditListener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldEditListener.java @@ -33,161 +33,153 @@ import com.intellectualcrafters.plot.events.PlotDeleteEvent; */ public class WorldEditListener implements Listener { - public final Set blockedcmds = new HashSet(Arrays.asList("/gmask", "//gmask", "/worldedit:gmask")); - public final Set restrictedcmds = new HashSet(Arrays.asList("/up", "//up", "/worldedit:up")); + public final Set blockedcmds = new HashSet(Arrays.asList("/gmask", "//gmask", "/worldedit:gmask")); + public final Set restrictedcmds = new HashSet(Arrays.asList("/up", "//up", "/worldedit:up")); - private boolean isPlotWorld(Location l) { - return (PlotMain.isPlotWorld(l.getWorld())); - } - - @EventHandler( - priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onDelete(PlotDeleteEvent e) { - String world = e.getWorld(); - PlotId id = e.getPlotId(); - Plot plot = PlotMain.getPlots(world).get(id); - if (plot==null || plot.owner == null) { - return; - } - Player player = Bukkit.getPlayer(plot.owner); - if (player == null) { - return; - } - if (!world.equals(player.getWorld().getName())) { - return; - } - if (PlotMain.hasPermission(player, "plots.worldedit.bypass")) { + private boolean isPlotWorld(final Location l) { + return (PlotMain.isPlotWorld(l.getWorld())); + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onDelete(final PlotDeleteEvent e) { + final String world = e.getWorld(); + final PlotId id = e.getPlotId(); + final Plot plot = PlotMain.getPlots(world).get(id); + if ((plot == null) || (plot.owner == null)) { return; } - PWE.setNoMask(player); - } + final Player player = Bukkit.getPlayer(plot.owner); + if (player == null) { + return; + } + if (!world.equals(player.getWorld().getName())) { + return; + } + if (PlotMain.hasPermission(player, "plots.worldedit.bypass")) { + return; + } + PWE.setNoMask(player); + } - @EventHandler( - priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent e) { - Block b = e.getClickedBlock(); - if (b == null) { - return; - } - Player p = e.getPlayer(); - Location l = b.getLocation(); - if (!isPlotWorld(l)) { - return; - } - p.getItemInHand(); - if ((p.getItemInHand() == null) || (p.getItemInHand().getType() == Material.AIR)) { - return; - } - Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); - if (plot != null) { - if ((plot != null) && plot.hasOwner() && (plot.helpers != null) - && (plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { - PWE.setMask(p, l); - } - } - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onInteract(final PlayerInteractEvent e) { + final Block b = e.getClickedBlock(); + if (b == null) { + return; + } + final Player p = e.getPlayer(); + final Location l = b.getLocation(); + if (!isPlotWorld(l)) { + return; + } + p.getItemInHand(); + if ((p.getItemInHand() == null) || (p.getItemInHand().getType() == Material.AIR)) { + return; + } + final Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); + if (plot != null) { + if ((plot != null) && plot.hasOwner() && (plot.helpers != null) && (plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { + PWE.setMask(p, l); + } + } + } - @EventHandler( - priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPlayerCommand(PlayerCommandPreprocessEvent e) { - Player p = e.getPlayer(); - if (PlotMain.hasPermission(p, "plots.worldedit.bypass") || !PlotMain.isPlotWorld(p.getWorld())) { - return; - } - String cmd = e.getMessage().toLowerCase(); + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerCommand(final PlayerCommandPreprocessEvent e) { + final Player p = e.getPlayer(); + if (PlotMain.hasPermission(p, "plots.worldedit.bypass") || !PlotMain.isPlotWorld(p.getWorld())) { + return; + } + String cmd = e.getMessage().toLowerCase(); - if (cmd.contains(" ")) { - cmd = cmd.substring(0, cmd.indexOf(" ")); - } - if (this.restrictedcmds.contains(cmd)) { - Plot plot = PlayerFunctions.getCurrentPlot(p); - if ((plot == null) || !(plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { - e.setCancelled(true); - } - } - else - if (this.blockedcmds.contains(cmd)) { - e.setCancelled(true); - } - } + if (cmd.contains(" ")) { + cmd = cmd.substring(0, cmd.indexOf(" ")); + } + if (this.restrictedcmds.contains(cmd)) { + final Plot plot = PlayerFunctions.getCurrentPlot(p); + if ((plot == null) || !(plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { + e.setCancelled(true); + } + } + else if (this.blockedcmds.contains(cmd)) { + e.setCancelled(true); + } + } - @EventHandler( - priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPlayerJoin(final PlayerJoinEvent e) { - Player p = e.getPlayer(); - if (PlotMain.hasPermission(p, "plots.worldedit.bypass")) { - return; - } - Location l = p.getLocation(); - if (isPlotWorld(l)) { - PWE.setMask(p, l); - } - else { - PWE.removeMask(p); - } - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerJoin(final PlayerJoinEvent e) { + final Player p = e.getPlayer(); + if (PlotMain.hasPermission(p, "plots.worldedit.bypass")) { + return; + } + final Location l = p.getLocation(); + if (isPlotWorld(l)) { + PWE.setMask(p, l); + } + else { + PWE.removeMask(p); + } + } - @EventHandler( - priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(final PlayerMoveEvent e) { - Location t = e.getTo(); - if (!isPlotWorld(t)) { - return; - } - Location f = e.getFrom(); - Player p = e.getPlayer(); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(final PlayerMoveEvent e) { + final Location t = e.getTo(); + if (!isPlotWorld(t)) { + return; + } + final Location f = e.getFrom(); + final Player p = e.getPlayer(); - if ((f.getBlockX() != t.getBlockX()) || (f.getBlockZ() != t.getBlockZ())) { - PlotId idF = PlayerFunctions.getPlot(f); - PlotId idT = PlayerFunctions.getPlot(t); - if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { - return; - } - if ((idT != null) && !(idF == idT)) { - PWE.setMask(p, t); - } - } - } + if ((f.getBlockX() != t.getBlockX()) || (f.getBlockZ() != t.getBlockZ())) { + final PlotId idF = PlayerFunctions.getPlot(f); + final PlotId idT = PlayerFunctions.getPlot(t); + if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { + return; + } + if ((idT != null) && !(idF == idT)) { + PWE.setMask(p, t); + } + } + } - @EventHandler( - priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPortal(PlayerPortalEvent e) { - if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { - return; - } - Player p = e.getPlayer(); - Location t = e.getTo(); - Location f = e.getFrom(); - if (t == null) { - PWE.removeMask(p); - return; - } - if (isPlotWorld(t)) { - PWE.setMask(p, t); - return; - } - if (f != null && isPlotWorld(f)) { - PWE.removeMask(p); - return; - } - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPortal(final PlayerPortalEvent e) { + if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { + return; + } + final Player p = e.getPlayer(); + final Location t = e.getTo(); + final Location f = e.getFrom(); + if (t == null) { + PWE.removeMask(p); + return; + } + if (isPlotWorld(t)) { + PWE.setMask(p, t); + return; + } + if ((f != null) && isPlotWorld(f)) { + PWE.removeMask(p); + return; + } + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onTeleport(final PlayerTeleportEvent e) { - if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { - return; - } - Player p = e.getPlayer(); - Location t = e.getTo(); - Location f = e.getFrom(); - if (!isPlotWorld(t)) { - if (isPlotWorld(f)) { - PWE.removeMask(p); - } - else { - return; - } - } - PWE.setMask(p, t); - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onTeleport(final PlayerTeleportEvent e) { + if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { + return; + } + final Player p = e.getPlayer(); + final Location t = e.getTo(); + final Location f = e.getFrom(); + if (!isPlotWorld(t)) { + if (isPlotWorld(f)) { + PWE.removeMask(p); + } + else { + return; + } + } + PWE.setMask(p, t); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldGuardListener.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldGuardListener.java index b8fcab40c..61a3b2970 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldGuardListener.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/listeners/WorldGuardListener.java @@ -1,6 +1,24 @@ package com.intellectualcrafters.plot.listeners; -import com.intellectualcrafters.plot.*; +import java.util.ArrayList; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.plugin.java.JavaPlugin; + +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; import com.intellectualcrafters.plot.events.PlotDeleteEvent; import com.intellectualcrafters.plot.events.PlotMergeEvent; @@ -12,213 +30,198 @@ import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.permissions.PermissionAttachment; - -import java.util.ArrayList; -import java.util.Map; -import java.util.UUID; /** * Created by Citymonstret on 2014-09-24. */ public class WorldGuardListener implements Listener { - public ArrayList str_flags = new ArrayList(); - public ArrayList> flags = new ArrayList>(); + public ArrayList str_flags = new ArrayList(); + public ArrayList> flags = new ArrayList>(); - public WorldGuardListener(PlotMain plugin) { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - for (Flag flag : DefaultFlag.getFlags()) { - this.str_flags.add(flag.getName()); - this.flags.add(flag); - } - } + public WorldGuardListener(final PlotMain plugin) { + plugin.getServer().getPluginManager().registerEvents(this, plugin); + for (final Flag flag : DefaultFlag.getFlags()) { + this.str_flags.add(flag.getName()); + this.flags.add(flag); + } + } - public void changeOwner(Player requester, UUID owner, World world, Plot plot) { - //boolean op = requester.isOp(); - //requester.setOp(true); + public void changeOwner(final Player requester, final UUID owner, final World world, final Plot plot) { + // boolean op = requester.isOp(); + // requester.setOp(true); - //10 ticks should be enough - PermissionAttachment add = requester.addAttachment(PlotMain.getPlugin(PlotMain.class), 10); + // 10 ticks should be enough + final PermissionAttachment add = requester.addAttachment(JavaPlugin.getPlugin(PlotMain.class), 10); add.setPermission("worldguard.region.addowner.own.*", true); - PermissionAttachment remove = requester.addAttachment(PlotMain.getPlugin(PlotMain.class), 10); + final PermissionAttachment remove = requester.addAttachment(JavaPlugin.getPlugin(PlotMain.class), 10); remove.setPermission("worldguard.region.removeowner.own.*", true); try { - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + final RegionManager manager = PlotMain.worldGuard.getRegionManager(world); manager.getRegion(plot.id.x + "-" + plot.id.y); requester.performCommand("region setowner " + (plot.id.x + "-" + plot.id.y) + " " + UUIDHandler.getName(owner)); requester.performCommand("region removeowner " + (plot.id.x + "-" + plot.id.y) + " " + UUIDHandler.getName(plot.getOwner())); } - catch (Exception e) { - //requester.setOp(op); + catch (final Exception e) { + // requester.setOp(op); } finally { add.remove(); remove.remove(); } - } + } - public void removeFlag(Player requester, World world, Plot plot, String key) { - boolean op = requester.isOp(); - requester.setOp(true); - try { - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - manager.getRegion(plot.id.x + "-" + plot.id.y); - for (Flag flag : this.flags) { - if (flag.getName().equalsIgnoreCase(key)) { - requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key); - } - } - } - catch (Exception e) { - requester.setOp(op); - } - finally { - requester.setOp(op); - } - } + public void removeFlag(final Player requester, final World world, final Plot plot, final String key) { + final boolean op = requester.isOp(); + requester.setOp(true); + try { + final RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + manager.getRegion(plot.id.x + "-" + plot.id.y); + for (final Flag flag : this.flags) { + if (flag.getName().equalsIgnoreCase(key)) { + requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key); + } + } + } + catch (final Exception e) { + requester.setOp(op); + } + finally { + requester.setOp(op); + } + } - public void addFlag(Player requester, World world, Plot plot, String key, String value) { - boolean op = requester.isOp(); - requester.setOp(true); - try { - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - manager.getRegion(plot.id.x + "-" + plot.id.y); - for (Flag flag : this.flags) { - if (flag.getName().equalsIgnoreCase(key)) { - requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key + " " + value); - } - } - } - catch (Exception e) { - requester.setOp(op); - } - finally { - requester.setOp(op); - } - } + public void addFlag(final Player requester, final World world, final Plot plot, final String key, final String value) { + final boolean op = requester.isOp(); + requester.setOp(true); + try { + final RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + manager.getRegion(plot.id.x + "-" + plot.id.y); + for (final Flag flag : this.flags) { + if (flag.getName().equalsIgnoreCase(key)) { + requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key + " " + value); + } + } + } + catch (final Exception e) { + requester.setOp(op); + } + finally { + requester.setOp(op); + } + } - @EventHandler( - priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMerge(PlotMergeEvent event) { - Plot main = event.getPlot(); - ArrayList plots = event.getPlots(); - World world = event.getWorld(); - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - for (PlotId plot : plots) { - if (!plot.equals(main)) { - manager.removeRegion(plot.x + "-" + plot.y); - } - } - ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); - DefaultDomain owner = region.getOwners(); - Map, Object> flags = region.getFlags(); - DefaultDomain members = region.getMembers(); - manager.removeRegion(main.id.x + "-" + main.id.y); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMerge(final PlotMergeEvent event) { + final Plot main = event.getPlot(); + final ArrayList plots = event.getPlots(); + final World world = event.getWorld(); + final RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + for (final PlotId plot : plots) { + if (!plot.equals(main)) { + manager.removeRegion(plot.x + "-" + plot.y); + } + } + final ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); + final DefaultDomain owner = region.getOwners(); + final Map, Object> flags = region.getFlags(); + final DefaultDomain members = region.getMembers(); + manager.removeRegion(main.id.x + "-" + main.id.y); - Location location1 = PlotHelper.getPlotBottomLocAbs(world, plots.get(0)); - Location location2 = PlotHelper.getPlotTopLocAbs(world, plots.get(plots.size() - 1)); + final Location location1 = PlotHelper.getPlotBottomLocAbs(world, plots.get(0)); + final Location location2 = PlotHelper.getPlotTopLocAbs(world, plots.get(plots.size() - 1)); - BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); - BlockVector vector2 = new BlockVector(location2.getBlockX(), world.getMaxHeight(), location2.getBlockZ()); - ProtectedRegion rg = new ProtectedCuboidRegion(main.id.x + "-" + main.id.y, vector1, vector2); + final BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); + final BlockVector vector2 = new BlockVector(location2.getBlockX(), world.getMaxHeight(), location2.getBlockZ()); + final ProtectedRegion rg = new ProtectedCuboidRegion(main.id.x + "-" + main.id.y, vector1, vector2); - rg.setFlags(flags); + rg.setFlags(flags); - rg.setOwners(owner); + rg.setOwners(owner); - rg.setMembers(members); + rg.setMembers(members); - manager.addRegion(rg); - } + manager.addRegion(rg); + } - @EventHandler( - priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUnlink(PlotUnlinkEvent event) { - try { - World w = event.getWorld(); - ArrayList plots = event.getPlots(); - Plot main = PlotMain.getPlots(w).get(plots.get(0)); - - RegionManager manager = PlotMain.worldGuard.getRegionManager(w); - ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); - - DefaultDomain owner = region.getOwners(); - Map, Object> flags = region.getFlags(); - DefaultDomain members = region.getMembers(); - - manager.removeRegion(main.id.x + "-" + main.id.y); - for (int i = 1; i < plots.size(); i++) { - PlotId id = plots.get(i); - Location location1 = PlotHelper.getPlotBottomLocAbs(w, id); - Location location2 = PlotHelper.getPlotTopLocAbs(w, id); - - BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); - BlockVector vector2 = new BlockVector(location2.getBlockX(), w.getMaxHeight(), location2.getBlockZ()); - ProtectedRegion rg = new ProtectedCuboidRegion(id.x + "-" + id.y, vector1, vector2); - - rg.setFlags(flags); - - rg.setOwners(owner); - - rg.setMembers(members); - - manager.addRegion(rg); - } - } - catch (Exception e) { - - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUnlink(final PlotUnlinkEvent event) { + try { + final World w = event.getWorld(); + final ArrayList plots = event.getPlots(); + final Plot main = PlotMain.getPlots(w).get(plots.get(0)); - @EventHandler - public void onPlotClaim(PlayerClaimPlotEvent event) { - try { - Player player = event.getPlayer(); - Plot plot = event.getPlot(); - RegionManager manager = PlotMain.worldGuard.getRegionManager(plot.getWorld()); - - Location location1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); - Location location2 = PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); - - BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); - BlockVector vector2 = - new BlockVector(location2.getBlockX(), plot.getWorld().getMaxHeight(), location2.getBlockZ()); - - ProtectedRegion region = new ProtectedCuboidRegion(plot.getId().x + "-" + plot.getId().y, vector1, vector2); - - DefaultDomain owner = new DefaultDomain(); - owner.addPlayer(PlotMain.worldGuard.wrapPlayer(player)); - - region.setOwners(owner); - - manager.addRegion(region); - } - catch (Exception e) { - - } - } + final RegionManager manager = PlotMain.worldGuard.getRegionManager(w); + final ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); - @EventHandler - public void onPlotDelete(PlotDeleteEvent event) { - try { - PlotId plot = event.getPlotId(); - World world = Bukkit.getWorld(event.getWorld()); - - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - manager.removeRegion(plot.x + "-" + plot.y); - } - catch (Exception e) { - - } - } + final DefaultDomain owner = region.getOwners(); + final Map, Object> flags = region.getFlags(); + final DefaultDomain members = region.getMembers(); + + manager.removeRegion(main.id.x + "-" + main.id.y); + for (int i = 1; i < plots.size(); i++) { + final PlotId id = plots.get(i); + final Location location1 = PlotHelper.getPlotBottomLocAbs(w, id); + final Location location2 = PlotHelper.getPlotTopLocAbs(w, id); + + final BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); + final BlockVector vector2 = new BlockVector(location2.getBlockX(), w.getMaxHeight(), location2.getBlockZ()); + final ProtectedRegion rg = new ProtectedCuboidRegion(id.x + "-" + id.y, vector1, vector2); + + rg.setFlags(flags); + + rg.setOwners(owner); + + rg.setMembers(members); + + manager.addRegion(rg); + } + } + catch (final Exception e) { + + } + } + + @EventHandler + public void onPlotClaim(final PlayerClaimPlotEvent event) { + try { + final Player player = event.getPlayer(); + final Plot plot = event.getPlot(); + final RegionManager manager = PlotMain.worldGuard.getRegionManager(plot.getWorld()); + + final Location location1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); + final Location location2 = PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); + + final BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); + final BlockVector vector2 = new BlockVector(location2.getBlockX(), plot.getWorld().getMaxHeight(), location2.getBlockZ()); + + final ProtectedRegion region = new ProtectedCuboidRegion(plot.getId().x + "-" + plot.getId().y, vector1, vector2); + + final DefaultDomain owner = new DefaultDomain(); + owner.addPlayer(PlotMain.worldGuard.wrapPlayer(player)); + + region.setOwners(owner); + + manager.addRegion(region); + } + catch (final Exception e) { + + } + } + + @EventHandler + public void onPlotDelete(final PlotDeleteEvent event) { + try { + final PlotId plot = event.getPlotId(); + final World world = Bukkit.getWorld(event.getWorld()); + + final RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + manager.removeRegion(plot.x + "-" + plot.y); + } + catch (final Exception e) { + + } + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/NameFetcher.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/NameFetcher.java index e891d9ab5..6172d1dfa 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/NameFetcher.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/NameFetcher.java @@ -18,36 +18,34 @@ import com.google.common.collect.ImmutableList; * @author */ public class NameFetcher implements Callable> { - private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; - private final JSONParser jsonParser = new JSONParser(); - private final List uuids; + private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; + private final JSONParser jsonParser = new JSONParser(); + private final List uuids; - public NameFetcher(List uuids) { - this.uuids = ImmutableList.copyOf(uuids); - } + public NameFetcher(final List uuids) { + this.uuids = ImmutableList.copyOf(uuids); + } - @Override - public Map call() throws Exception { - Map uuidStringMap = new HashMap(); - for (UUID uuid : this.uuids) { - if (uuidStringMap.containsKey(uuid)) { - continue; - } - HttpURLConnection connection = - (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); - JSONObject response = - (JSONObject) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); - String name = (String) response.get("name"); - if (name == null) { - continue; - } - String cause = (String) response.get("cause"); - String errorMessage = (String) response.get("errorMessage"); - if ((cause != null) && (cause.length() > 0)) { - throw new IllegalStateException(errorMessage); - } - uuidStringMap.put(uuid, name); - } - return uuidStringMap; - } + @Override + public Map call() throws Exception { + final Map uuidStringMap = new HashMap(); + for (final UUID uuid : this.uuids) { + if (uuidStringMap.containsKey(uuid)) { + continue; + } + final HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); + final JSONObject response = (JSONObject) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); + final String name = (String) response.get("name"); + if (name == null) { + continue; + } + final String cause = (String) response.get("cause"); + final String errorMessage = (String) response.get("errorMessage"); + if ((cause != null) && (cause.length() > 0)) { + throw new IllegalStateException(errorMessage); + } + uuidStringMap.put(uuid, name); + } + return uuidStringMap; + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/PlotUUIDSaver.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/PlotUUIDSaver.java index 5790cabac..90891f0dc 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/PlotUUIDSaver.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/PlotUUIDSaver.java @@ -1,5 +1,13 @@ package com.intellectualcrafters.plot.uuid; +import java.net.URL; +import java.net.URLConnection; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.java.JavaPlugin; + import com.google.common.collect.BiMap; import com.intellectualcrafters.json.JSONObject; import com.intellectualcrafters.json.JSONTokener; @@ -7,30 +15,24 @@ import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.Settings; import com.intellectualcrafters.plot.StringWrapper; import com.intellectualcrafters.plot.UUIDHandler; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.plugin.java.JavaPlugin; - -import java.net.URL; -import java.net.URLConnection; -import java.util.UUID; /** * Created by Citymonstret on 2014-10-13. */ public class PlotUUIDSaver extends UUIDSaver { + @Override public void globalPopulate() { JavaPlugin.getPlugin(PlotMain.class).getServer().getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(PlotMain.class), new Runnable() { @Override public void run() { - OfflinePlayer[] offlinePlayers = Bukkit.getOfflinePlayers(); - int length = offlinePlayers.length; - long start = System.currentTimeMillis(); + final OfflinePlayer[] offlinePlayers = Bukkit.getOfflinePlayers(); + final int length = offlinePlayers.length; + final long start = System.currentTimeMillis(); String name; UUID uuid; - for (OfflinePlayer player : offlinePlayers) { + for (final OfflinePlayer player : offlinePlayers) { uuid = player.getUniqueId(); if (!UUIDHandler.uuidExists(uuid)) { name = player.getName(); @@ -38,55 +40,58 @@ public class PlotUUIDSaver extends UUIDSaver { } } - long time = System.currentTimeMillis() - start; - int size = UUIDHandler.getUuidMap().size(); + final long time = System.currentTimeMillis() - start; + final int size = UUIDHandler.getUuidMap().size(); double ups; - if(time == 0l || size == 0) { + if ((time == 0l) || (size == 0)) { ups = size; - } else { + } + else { ups = size / time; } - //Plot Squared Only... - PlotMain.sendConsoleSenderMessage("&cFinished caching of offline player UUIDs! Took &6" + time + "&cms (&6" + ups + "&c per millisecond), &6" - + length + " &cUUIDs were cached" + " and there is now a grand total of &6" + size - + " &ccached."); + // Plot Squared Only... + PlotMain.sendConsoleSenderMessage("&cFinished caching of offline player UUIDs! Took &6" + time + "&cms (&6" + ups + "&c per millisecond), &6" + length + " &cUUIDs were cached" + " and there is now a grand total of &6" + size + " &ccached."); } }); } - public void globalSave(BiMap map) { + @Override + public void globalSave(final BiMap map) { } - public void save(UUIDSet set) { + @Override + public void save(final UUIDSet set) { } - public UUID mojangUUID(String name) throws Exception { - URLConnection connection = new URL(Settings.API_URL + "?user=" + name).openConnection(); + @Override + public UUID mojangUUID(final String name) throws Exception { + final URLConnection connection = new URL(Settings.API_URL + "?user=" + name).openConnection(); connection.addRequestProperty("User-Agent", "Mozilla/4.0"); - JSONTokener tokener = new JSONTokener(connection.getInputStream()); - JSONObject root = new JSONObject(tokener); - String uuid = root.getJSONObject(name).getString("dashed"); + final JSONTokener tokener = new JSONTokener(connection.getInputStream()); + final JSONObject root = new JSONObject(tokener); + final String uuid = root.getJSONObject(name).getString("dashed"); return UUID.fromString(uuid); } - public String mojangName(UUID uuid) throws Exception { - URLConnection connection = new URL( - Settings.API_URL + "?user=" - + uuid.toString().replace("-", "")).openConnection(); + @Override + public String mojangName(final UUID uuid) throws Exception { + final URLConnection connection = new URL(Settings.API_URL + "?user=" + uuid.toString().replace("-", "")).openConnection(); connection.addRequestProperty("User-Agent", "Mozilla/4.0"); - JSONTokener tokener = new JSONTokener(connection.getInputStream()); - JSONObject root = new JSONObject(tokener); + final JSONTokener tokener = new JSONTokener(connection.getInputStream()); + final JSONObject root = new JSONObject(tokener); return root.getJSONObject(uuid.toString().replace("-", "")).getString("username"); } - public UUIDSet get(String name) { + @Override + public UUIDSet get(final String name) { return null; } - public UUIDSet get(UUID uuid) { + @Override + public UUIDSet get(final UUID uuid) { return null; } -} \ No newline at end of file +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDFetcher.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDFetcher.java index 002de2a2d..9ece35217 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDFetcher.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDFetcher.java @@ -22,86 +22,84 @@ import com.google.common.collect.ImmutableList; * @author */ public class UUIDFetcher implements Callable> { - private static final double PROFILES_PER_REQUEST = 100; - private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; - private final JSONParser jsonParser = new JSONParser(); - private final List names; - private final boolean rateLimiting; + private static final double PROFILES_PER_REQUEST = 100; + private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; + private final JSONParser jsonParser = new JSONParser(); + private final List names; + private final boolean rateLimiting; - public UUIDFetcher(List names, boolean rateLimiting) { - this.names = ImmutableList.copyOf(names); - this.rateLimiting = rateLimiting; - } + public UUIDFetcher(final List names, final boolean rateLimiting) { + this.names = ImmutableList.copyOf(names); + this.rateLimiting = rateLimiting; + } - public UUIDFetcher(List names) { - this(names, true); - } + public UUIDFetcher(final List names) { + this(names, true); + } - @Override - public Map call() throws Exception { - Map uuidMap = new HashMap(); - int requests = (int) Math.ceil(this.names.size() / PROFILES_PER_REQUEST); - for (int i = 0; i < requests; i++) { - HttpURLConnection connection = createConnection(); - String body = - JSONArray.toJSONString(this.names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()))); - writeBody(connection, body); - JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); - for (Object profile : array) { - JSONObject jsonProfile = (JSONObject) profile; - String id = (String) jsonProfile.get("id"); - String name = (String) jsonProfile.get("name"); - UUID uuid = UUIDFetcher.getUUID(id); - uuidMap.put(name, uuid); - } - if (this.rateLimiting && (i != (requests - 1))) { - Thread.sleep(100L); - } - } - return uuidMap; - } + @Override + public Map call() throws Exception { + final Map uuidMap = new HashMap(); + final int requests = (int) Math.ceil(this.names.size() / PROFILES_PER_REQUEST); + for (int i = 0; i < requests; i++) { + final HttpURLConnection connection = createConnection(); + final String body = JSONArray.toJSONString(this.names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()))); + writeBody(connection, body); + final JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); + for (final Object profile : array) { + final JSONObject jsonProfile = (JSONObject) profile; + final String id = (String) jsonProfile.get("id"); + final String name = (String) jsonProfile.get("name"); + final UUID uuid = UUIDFetcher.getUUID(id); + uuidMap.put(name, uuid); + } + if (this.rateLimiting && (i != (requests - 1))) { + Thread.sleep(100L); + } + } + return uuidMap; + } - private static void writeBody(HttpURLConnection connection, String body) throws Exception { - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - } + private static void writeBody(final HttpURLConnection connection, final String body) throws Exception { + final OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + } - private static HttpURLConnection createConnection() throws Exception { - URL url = new URL(PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - return connection; - } + private static HttpURLConnection createConnection() throws Exception { + final URL url = new URL(PROFILE_URL); + final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + return connection; + } - public static UUID getUUID(String id) { - return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" - + id.substring(16, 20) + "-" + id.substring(20, 32)); - } + public static UUID getUUID(final String id) { + return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); + } - public static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getMostSignificantBits()); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - return byteBuffer.array(); - } + public static byte[] toBytes(final UUID uuid) { + final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } - public static UUID fromBytes(byte[] array) { - if (array.length != 16) { - throw new IllegalArgumentException("Illegal byte array length: " + array.length); - } - ByteBuffer byteBuffer = ByteBuffer.wrap(array); - long mostSignificant = byteBuffer.getLong(); - long leastSignificant = byteBuffer.getLong(); - return new UUID(mostSignificant, leastSignificant); - } + public static UUID fromBytes(final byte[] array) { + if (array.length != 16) { + throw new IllegalArgumentException("Illegal byte array length: " + array.length); + } + final ByteBuffer byteBuffer = ByteBuffer.wrap(array); + final long mostSignificant = byteBuffer.getLong(); + final long leastSignificant = byteBuffer.getLong(); + return new UUID(mostSignificant, leastSignificant); + } - public static UUID getUUIDOf(String name) throws Exception { - return new UUIDFetcher(Arrays.asList(name)).call().get(name); - } + public static UUID getUUIDOf(final String name) throws Exception { + return new UUIDFetcher(Arrays.asList(name)).call().get(name); + } } diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSaver.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSaver.java index 190278245..9f81bda0c 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSaver.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSaver.java @@ -1,19 +1,25 @@ package com.intellectualcrafters.plot.uuid; +import java.util.UUID; + import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.StringWrapper; -import java.util.UUID; - /** * Created by Citymonstret on 2014-10-13. */ public abstract class UUIDSaver { public abstract void globalPopulate(); - public abstract void globalSave(BiMap biMap); - public abstract void save(UUIDSet set); - public abstract UUIDSet get(String name); - public abstract UUIDSet get(UUID uuid); - public abstract UUID mojangUUID(String name) throws Exception; - public abstract String mojangName(UUID uuid) throws Exception; -} \ No newline at end of file + + public abstract void globalSave(final BiMap biMap); + + public abstract void save(final UUIDSet set); + + public abstract UUIDSet get(final String name); + + public abstract UUIDSet get(final UUID uuid); + + public abstract UUID mojangUUID(final String name) throws Exception; + + public abstract String mojangName(final UUID uuid) throws Exception; +} diff --git a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSet.java b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSet.java index 703b96441..811ccb44f 100644 --- a/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSet.java +++ b/PlotSquared/src/main/java/com/intellectualcrafters/plot/uuid/UUIDSet.java @@ -6,10 +6,10 @@ import java.util.UUID; * Created by Citymonstret on 2014-10-13. */ public class UUIDSet { - private String name; - private UUID uuid; + private final String name; + private final UUID uuid; - public UUIDSet(String name, UUID uuid) { + public UUIDSet(final String name, final UUID uuid) { this.name = name; this.uuid = uuid; } @@ -20,10 +20,10 @@ public class UUIDSet { } public String getName() { - return name; + return this.name; } public UUID getUUID() { - return uuid; + return this.uuid; } -} \ No newline at end of file +} diff --git a/PlotSquared/src/test/java/Test1.java b/PlotSquared/src/test/java/Test1.java index a15165bd5..bdec27c3c 100644 --- a/PlotSquared/src/test/java/Test1.java +++ b/PlotSquared/src/test/java/Test1.java @@ -1,47 +1,47 @@ +import org.junit.Assert; +import org.junit.Test; + import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotManager; import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.generator.DefaultPlotManager; import com.intellectualcrafters.plot.generator.DefaultPlotWorld; -import org.junit.Assert; -import org.junit.Test; public class Test1 { - + // I have no idea what I should actually test :p - + @Test public void testSquare() { Assert.assertEquals(PlotHelper.square(5), 25); } - + @Test public void testPlots() { Assert.assertNotNull(PlotMain.getAllPlotsRaw()); } - + @Test public void testAddPlotWorld() { boolean passed = false; try { - PlotWorld plotworld = new DefaultPlotWorld("poop"); - PlotManager manager = new DefaultPlotManager(); + final PlotWorld plotworld = new DefaultPlotWorld("poop"); + final PlotManager manager = new DefaultPlotManager(); PlotMain.addPlotWorld("poop", plotworld, manager); - passed = PlotMain.getPlotManager("poop")!=null && PlotMain.getWorldSettings("poop")!=null; + passed = (PlotMain.getPlotManager("poop") != null) && (PlotMain.getWorldSettings("poop") != null); } - catch (Throwable e) { - + catch (final Throwable e) { + } finally { Assert.assertTrue(passed); } } - + @Test public void testCanSetFast() { Assert.assertTrue(PlotHelper.canSetFast); } - - + }