weekly code cleanup

This commit is contained in:
boy0001 2014-11-05 14:42:08 +11:00
parent aaa5d54085
commit bddaadd31d
154 changed files with 17956 additions and 17295 deletions

1
PlotSquared/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

View File

@ -10,9 +10,10 @@ public final class ByteArrayTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -20,32 +21,34 @@ public final class ByteArrayTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public byte[] getValue() { public byte[] getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder hex = new StringBuilder(); final StringBuilder hex = new StringBuilder();
for (byte b : value) { for (final byte b : this.value) {
String hexDigits = Integer.toHexString(b).toUpperCase(); final String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) { if (hexDigits.length() == 1) {
hex.append("0"); hex.append("0");
} }
hex.append(hexDigits).append(" "); hex.append(hexDigits).append(" ");
} }
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Byte_Array" + append + ": " + hex; return "TAG_Byte_Array" + append + ": " + hex;

View File

@ -10,9 +10,10 @@ public final class ByteTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -20,27 +21,29 @@ public final class ByteTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Byte getValue() { public Byte getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Byte" + append + ": " + value; return "TAG_Byte" + append + ": " + this.value;
} }
} }

View File

@ -15,9 +15,10 @@ public final class CompoundTag extends Tag {
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
* @param value the value of the tag * @param value
* the value of the tag
*/ */
public CompoundTag(Map<String, Tag> value) { public CompoundTag(final Map<String, Tag> value) {
super(); super();
this.value = Collections.unmodifiableMap(value); this.value = Collections.unmodifiableMap(value);
} }
@ -25,10 +26,12 @@ public final class CompoundTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * the name of the tag
* @param value
* the value of the tag
*/ */
public CompoundTag(String name, Map<String, Tag> value) { public CompoundTag(final String name, final Map<String, Tag> value) {
super(name); super(name);
this.value = Collections.unmodifiableMap(value); this.value = Collections.unmodifiableMap(value);
} }
@ -36,25 +39,27 @@ public final class CompoundTag extends Tag {
/** /**
* Returns whether this compound tag contains the given key. * 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 * @return true if the tag contains the given key
*/ */
public boolean containsKey(String key) { public boolean containsKey(final String key) {
return value.containsKey(key); return this.value.containsKey(key);
} }
@Override @Override
public Map<String, Tag> getValue() { public Map<String, Tag> getValue() {
return value; return this.value;
} }
/** /**
* Return a new compound tag with the given values. * Return a new compound tag with the given values.
* *
* @param value the value * @param value
* the value
* @return the new compound tag * @return the new compound tag
*/ */
public CompoundTag setValue(Map<String, Tag> value) { public CompoundTag setValue(final Map<String, Tag> value) {
return new CompoundTag(getName(), value); return new CompoundTag(getName(), value);
} }
@ -64,23 +69,27 @@ public final class CompoundTag extends Tag {
* @return the builder * @return the builder
*/ */
public CompoundTagBuilder createBuilder() { public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(value)); return new CompoundTagBuilder(new HashMap<String, Tag>(this.value));
} }
/** /**
* Get a byte array named with the given key. * Get a byte array named with the given key.
* *
* <p>If the key does not exist or its value is not a byte array tag, * <p>
* then an empty byte array will be returned.</p> * If the key does not exist or its value is not a byte array tag, then an
* empty byte array will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a byte array * @return a byte array
*/ */
public byte[] getByteArray(String key) { public byte[] getByteArray(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ByteArrayTag) { if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue(); return ((ByteArrayTag) tag).getValue();
} else { }
else {
return new byte[0]; return new byte[0];
} }
} }
@ -88,17 +97,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a byte named with the given key. * Get a byte named with the given key.
* *
* <p>If the key does not exist or its value is not a byte tag, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a byte tag, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a byte * @return a byte
*/ */
public byte getByte(String key) { public byte getByte(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else { }
else {
return (byte) 0; return (byte) 0;
} }
} }
@ -106,17 +119,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a double named with the given key. * Get a double named with the given key.
* *
* <p>If the key does not exist or its value is not a double tag, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a double tag, then
* {@code 0} will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a double * @return a double
*/ */
public double getDouble(String key) { public double getDouble(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof DoubleTag) { if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue(); return ((DoubleTag) tag).getValue();
} else { }
else {
return 0; 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 * Get a double named with the given key, even if it's another
* type of number. * type of number.
* *
* <p>If the key does not exist or its value is not a number, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a number, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a double * @return a double
*/ */
public double asDouble(String key) { public double asDouble(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { }
else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) { }
else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) { }
else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) { }
else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue(); return ((FloatTag) tag).getValue();
} else if (tag instanceof DoubleTag) { }
else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue(); return ((DoubleTag) tag).getValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -159,17 +185,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a float named with the given key. * Get a float named with the given key.
* *
* <p>If the key does not exist or its value is not a float tag, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a float tag, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a float * @return a float
*/ */
public float getFloat(String key) { public float getFloat(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof FloatTag) { if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue(); return ((FloatTag) tag).getValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -177,17 +207,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a {@code int[]} named with the given key. * Get a {@code int[]} named with the given key.
* *
* <p>If the key does not exist or its value is not an int array tag, * <p>
* then an empty array will be returned.</p> * If the key does not exist or its value is not an int array tag, then an
* empty array will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return an int array * @return an int array
*/ */
public int[] getIntArray(String key) { public int[] getIntArray(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof IntArrayTag) { if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue(); return ((IntArrayTag) tag).getValue();
} else { }
else {
return new int[0]; return new int[0];
} }
} }
@ -195,17 +229,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get an int named with the given key. * Get an int named with the given key.
* *
* <p>If the key does not exist or its value is not an int tag, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not an int tag, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return an int * @return an int
*/ */
public int getInt(String key) { public int getInt(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof IntTag) { if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else { }
else {
return 0; 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 * Get an int named with the given key, even if it's another
* type of number. * type of number.
* *
* <p>If the key does not exist or its value is not a number, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a number, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return an int * @return an int
*/ */
public int asInt(String key) { public int asInt(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { }
else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) { }
else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) { }
else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue().intValue(); return ((LongTag) tag).getValue().intValue();
} else if (tag instanceof FloatTag) { }
else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().intValue(); return ((FloatTag) tag).getValue().intValue();
} else if (tag instanceof DoubleTag) { }
else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().intValue(); return ((DoubleTag) tag).getValue().intValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -248,17 +295,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a list of tags named with the given key. * Get a list of tags named with the given key.
* *
* <p>If the key does not exist or its value is not a list tag, * <p>
* then an empty list will be returned.</p> * If the key does not exist or its value is not a list tag, then an empty
* list will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a list of tags * @return a list of tags
*/ */
public List<Tag> getList(String key) { public List<Tag> getList(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
return ((ListTag) tag).getValue(); return ((ListTag) tag).getValue();
} else { }
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@ -266,45 +317,55 @@ public final class CompoundTag extends Tag {
/** /**
* Get a {@code TagList} named with the given key. * Get a {@code TagList} named with the given key.
* *
* <p>If the key does not exist or its value is not a list tag, * <p>
* then an empty tag list will be returned.</p> * If the key does not exist or its value is not a list tag, then an empty
* tag list will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a tag list instance * @return a tag list instance
*/ */
public ListTag getListTag(String key) { public ListTag getListTag(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
return (ListTag) tag; return (ListTag) tag;
} else { }
return new ListTag(key, StringTag.class, Collections.<Tag>emptyList()); else {
return new ListTag(key, StringTag.class, Collections.<Tag> emptyList());
} }
} }
/** /**
* Get a list of tags named with the given key. * Get a list of tags named with the given key.
* *
* <p>If the key does not exist or its value is not a list tag, * <p>
* then an empty list will be returned. If the given key references * If the key does not exist or its value is not a list tag, then an empty
* a list but the list of of a different type, then an empty * list will be returned. If the given key references a list but the list of
* list will also be returned.</p> * of a different type, then an empty list will also be returned.
* </p>
* *
* @param key the key * @param key
* @param listType the class of the contained type * the key
* @param listType
* the class of the contained type
* @return a list of tags * @return a list of tags
* @param <T> the type of list * @param <T>
* the type of list
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) { public <T extends Tag> List<T> getList(final String key, final Class<T> listType) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag; final ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) { if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue(); return (List<T>) listTag.getValue();
} else { }
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} else { }
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@ -312,17 +373,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a long named with the given key. * Get a long named with the given key.
* *
* <p>If the key does not exist or its value is not a long tag, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a long tag, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a long * @return a long
*/ */
public long getLong(String key) { public long getLong(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof LongTag) { if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else { }
else {
return 0L; 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 * Get a long named with the given key, even if it's another
* type of number. * type of number.
* *
* <p>If the key does not exist or its value is not a number, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a number, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a long * @return a long
*/ */
public long asLong(String key) { public long asLong(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { }
else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) { }
else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) { }
else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) { }
else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().longValue(); return ((FloatTag) tag).getValue().longValue();
} else if (tag instanceof DoubleTag) { }
else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().longValue(); return ((DoubleTag) tag).getValue().longValue();
} else { }
else {
return 0L; return 0L;
} }
} }
@ -365,17 +439,21 @@ public final class CompoundTag extends Tag {
/** /**
* Get a short named with the given key. * Get a short named with the given key.
* *
* <p>If the key does not exist or its value is not a short tag, * <p>
* then {@code 0} will be returned.</p> * If the key does not exist or its value is not a short tag, then {@code 0}
* will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a short * @return a short
*/ */
public short getShort(String key) { public short getShort(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof ShortTag) { if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -383,31 +461,35 @@ public final class CompoundTag extends Tag {
/** /**
* Get a string named with the given key. * Get a string named with the given key.
* *
* <p>If the key does not exist or its value is not a string tag, * <p>
* then {@code ""} will be returned.</p> * If the key does not exist or its value is not a string tag, then
* {@code ""} will be returned.
* </p>
* *
* @param key the key * @param key
* the key
* @return a string * @return a string
*/ */
public String getString(String key) { public String getString(final String key) {
Tag tag = value.get(key); final Tag tag = this.value.get(key);
if (tag instanceof StringTag) { if (tag instanceof StringTag) {
return ((StringTag) tag).getValue(); return ((StringTag) tag).getValue();
} else { }
else {
return ""; return "";
} }
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
StringBuilder bldr = new StringBuilder(); final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n"); bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n");
for (Map.Entry<String, Tag> entry : value.entrySet()) { for (final Map.Entry<String, Tag> entry : this.value.entrySet()) {
bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
} }
bldr.append("}"); bldr.append("}");

View File

@ -1,10 +1,10 @@
package com.intellectualcrafters.jnbt; package com.intellectualcrafters.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Helps create compound tags. * Helps create compound tags.
*/ */
@ -22,9 +22,10 @@ public class CompoundTagBuilder {
/** /**
* Create a new instance and use the given map (which will be modified). * Create a new instance and use the given map (which will be modified).
* *
* @param value the value * @param value
* the value
*/ */
CompoundTagBuilder(Map<String, Tag> value) { CompoundTagBuilder(final Map<String, Tag> value) {
checkNotNull(value); checkNotNull(value);
this.entries = value; this.entries = value;
} }
@ -32,14 +33,16 @@ public class CompoundTagBuilder {
/** /**
* Put the given key and tag into the compound tag. * Put the given key and tag into the compound tag.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @return this object
*/ */
public CompoundTagBuilder put(String key, Tag value) { public CompoundTagBuilder put(final String key, final Tag value) {
checkNotNull(key); checkNotNull(key);
checkNotNull(value); checkNotNull(value);
entries.put(key, value); this.entries.put(key, value);
return this; return this;
} }
@ -47,47 +50,52 @@ public class CompoundTagBuilder {
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a
* {@code ByteArrayTag}. * {@code ByteArrayTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new ByteArrayTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a {@code ByteTag}.
* {@code ByteTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new ByteTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a {@code DoubleTag}.
* {@code DoubleTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new DoubleTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a {@code FloatTag}.
* {@code FloatTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); 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 * Put the given key and value into the compound tag as a
* {@code IntArrayTag}. * {@code IntArrayTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new IntArrayTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as an {@code IntTag}. * Put the given key and value into the compound tag as an {@code IntTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new IntTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a {@code LongTag}.
* {@code LongTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new LongTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a {@code ShortTag}.
* {@code ShortTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new ShortTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a * Put the given key and value into the compound tag as a {@code StringTag}.
* {@code StringTag}.
* *
* @param key they key * @param key
* @param value the value * they key
* @param value
* the value
* @return this object * @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)); return put(key, new StringTag(key, value));
} }
/** /**
* Put all the entries from the given map into this map. * 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 * @return this object
*/ */
public CompoundTagBuilder putAll(Map<String, ? extends Tag> value) { public CompoundTagBuilder putAll(final Map<String, ? extends Tag> value) {
checkNotNull(value); checkNotNull(value);
for (Map.Entry<String, ? extends Tag> entry : value.entrySet()) { for (final Map.Entry<String, ? extends Tag> entry : value.entrySet()) {
put(entry.getKey(), entry.getValue()); put(entry.getKey(), entry.getValue());
} }
return this; return this;
@ -170,17 +186,18 @@ public class CompoundTagBuilder {
* @return the new compound tag * @return the new compound tag
*/ */
public CompoundTag build() { public CompoundTag build() {
return new CompoundTag(new HashMap<String, Tag>(entries)); return new CompoundTag(new HashMap<String, Tag>(this.entries));
} }
/** /**
* Build a new compound tag with this builder's 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 * @return the created compound tag
*/ */
public CompoundTag build(String name) { public CompoundTag build(final String name) {
return new CompoundTag(name, new HashMap<String, Tag>(entries)); return new CompoundTag(name, new HashMap<String, Tag>(this.entries));
} }
/** /**

View File

@ -11,9 +11,10 @@ public final class DoubleTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -21,27 +22,29 @@ public final class DoubleTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Double getValue() { public Double getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Double" + append + ": " + value; return "TAG_Double" + append + ": " + this.value;
} }
} }

View File

@ -10,9 +10,10 @@ public final class FloatTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -20,27 +21,29 @@ public final class FloatTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Float getValue() { public Float getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Float" + append + ": " + value; return "TAG_Float" + append + ": " + this.value;
} }
} }

View File

@ -12,9 +12,10 @@ public final class IntArrayTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
@ -23,10 +24,12 @@ public final class IntArrayTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
@ -34,22 +37,22 @@ public final class IntArrayTag extends Tag {
@Override @Override
public int[] getValue() { public int[] getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder hex = new StringBuilder(); final StringBuilder hex = new StringBuilder();
for (int b : value) { for (final int b : this.value) {
String hexDigits = Integer.toHexString(b).toUpperCase(); final String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) { if (hexDigits.length() == 1) {
hex.append("0"); hex.append("0");
} }
hex.append(hexDigits).append(" "); hex.append(hexDigits).append(" ");
} }
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Int_Array" + append + ": " + hex; return "TAG_Int_Array" + append + ": " + hex;

View File

@ -10,9 +10,10 @@ public final class IntTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -20,27 +21,29 @@ public final class IntTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Integer getValue() { public Integer getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Int" + append + ": " + value; return "TAG_Int" + append + ": " + this.value;
} }
} }

View File

@ -1,11 +1,12 @@
package com.intellectualcrafters.jnbt; package com.intellectualcrafters.jnbt;
import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Nullable;
/** /**
* The {@code TAG_List} tag. * The {@code TAG_List} tag.
@ -18,10 +19,12 @@ public final class ListTag extends Tag {
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
* @param type the type of tag * @param type
* @param value the value of the tag * the type of tag
* @param value
* the value of the tag
*/ */
public ListTag(Class<? extends Tag> type, List<? extends Tag> value) { public ListTag(final Class<? extends Tag> type, final List<? extends Tag> value) {
super(); super();
checkNotNull(value); checkNotNull(value);
this.type = type; this.type = type;
@ -31,11 +34,14 @@ public final class ListTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param type the type of tag * the name of the tag
* @param value the value of the tag * @param type
* the type of tag
* @param value
* the value of the tag
*/ */
public ListTag(String name, Class<? extends Tag> type, List<? extends Tag> value) { public ListTag(final String name, final Class<? extends Tag> type, final List<? extends Tag> value) {
super(name); super(name);
checkNotNull(value); checkNotNull(value);
this.type = type; this.type = type;
@ -48,35 +54,38 @@ public final class ListTag extends Tag {
* @return The type of item in this list. * @return The type of item in this list.
*/ */
public Class<? extends Tag> getType() { public Class<? extends Tag> getType() {
return type; return this.type;
} }
@Override @Override
public List<Tag> getValue() { public List<Tag> getValue() {
return value; return this.value;
} }
/** /**
* Create a new list tag with this tag's name and type. * 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 * @return a new list tag
*/ */
public ListTag setValue(List<Tag> list) { public ListTag setValue(final List<Tag> list) {
return new ListTag(getName(), getType(), list); return new ListTag(getName(), getType(), list);
} }
/** /**
* Get the tag if it exists at the given index. * Get the tag if it exists at the given index.
* *
* @param index the index * @param index
* the index
* @return the tag or null * @return the tag or null
*/ */
@Nullable @Nullable
public Tag getIfExists(int index) { public Tag getIfExists(final int index) {
try { try {
return value.get(index); return this.value.get(index);
} catch (NoSuchElementException e) { }
catch (final NoSuchElementException e) {
return null; return null;
} }
} }
@ -84,17 +93,21 @@ public final class ListTag extends Tag {
/** /**
* Get a byte array named with the given index. * Get a byte array named with the given index.
* *
* <p>If the index does not exist or its value is not a byte array tag, * <p>
* then an empty byte array will be returned.</p> * If the index does not exist or its value is not a byte array tag, then an
* empty byte array will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a byte array * @return a byte array
*/ */
public byte[] getByteArray(int index) { public byte[] getByteArray(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ByteArrayTag) { if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue(); return ((ByteArrayTag) tag).getValue();
} else { }
else {
return new byte[0]; return new byte[0];
} }
} }
@ -102,17 +115,21 @@ public final class ListTag extends Tag {
/** /**
* Get a byte named with the given index. * Get a byte named with the given index.
* *
* <p>If the index does not exist or its value is not a byte tag, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a byte tag, then
* {@code 0} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a byte * @return a byte
*/ */
public byte getByte(int index) { public byte getByte(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else { }
else {
return (byte) 0; return (byte) 0;
} }
} }
@ -120,17 +137,21 @@ public final class ListTag extends Tag {
/** /**
* Get a double named with the given index. * Get a double named with the given index.
* *
* <p>If the index does not exist or its value is not a double tag, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a double tag, then
* {@code 0} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a double * @return a double
*/ */
public double getDouble(int index) { public double getDouble(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof DoubleTag) { if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue(); return ((DoubleTag) tag).getValue();
} else { }
else {
return 0; 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 * Get a double named with the given index, even if it's another
* type of number. * type of number.
* *
* <p>If the index does not exist or its value is not a number, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a number, then {@code 0}
* will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a double * @return a double
*/ */
public double asDouble(int index) { public double asDouble(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { }
else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) { }
else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) { }
else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) { }
else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue(); return ((FloatTag) tag).getValue();
} else if (tag instanceof DoubleTag) { }
else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue(); return ((DoubleTag) tag).getValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -173,17 +203,21 @@ public final class ListTag extends Tag {
/** /**
* Get a float named with the given index. * Get a float named with the given index.
* *
* <p>If the index does not exist or its value is not a float tag, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a float tag, then
* {@code 0} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a float * @return a float
*/ */
public float getFloat(int index) { public float getFloat(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof FloatTag) { if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue(); return ((FloatTag) tag).getValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -191,17 +225,21 @@ public final class ListTag extends Tag {
/** /**
* Get a {@code int[]} named with the given index. * Get a {@code int[]} named with the given index.
* *
* <p>If the index does not exist or its value is not an int array tag, * <p>
* then an empty array will be returned.</p> * If the index does not exist or its value is not an int array tag, then an
* empty array will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return an int array * @return an int array
*/ */
public int[] getIntArray(int index) { public int[] getIntArray(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof IntArrayTag) { if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue(); return ((IntArrayTag) tag).getValue();
} else { }
else {
return new int[0]; return new int[0];
} }
} }
@ -209,17 +247,21 @@ public final class ListTag extends Tag {
/** /**
* Get an int named with the given index. * Get an int named with the given index.
* *
* <p>If the index does not exist or its value is not an int tag, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not an int tag, then
* {@code 0} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return an int * @return an int
*/ */
public int getInt(int index) { public int getInt(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof IntTag) { if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else { }
else {
return 0; 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 * Get an int named with the given index, even if it's another
* type of number. * type of number.
* *
* <p>If the index does not exist or its value is not a number, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a number, then {@code 0}
* will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return an int * @return an int
*/ */
public int asInt(int index) { public int asInt(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { }
else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) { }
else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) { }
else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue().intValue(); return ((LongTag) tag).getValue().intValue();
} else if (tag instanceof FloatTag) { }
else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().intValue(); return ((FloatTag) tag).getValue().intValue();
} else if (tag instanceof DoubleTag) { }
else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().intValue(); return ((DoubleTag) tag).getValue().intValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -262,17 +313,21 @@ public final class ListTag extends Tag {
/** /**
* Get a list of tags named with the given index. * Get a list of tags named with the given index.
* *
* <p>If the index does not exist or its value is not a list tag, * <p>
* then an empty list will be returned.</p> * If the index does not exist or its value is not a list tag, then an empty
* list will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a list of tags * @return a list of tags
*/ */
public List<Tag> getList(int index) { public List<Tag> getList(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
return ((ListTag) tag).getValue(); return ((ListTag) tag).getValue();
} else { }
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@ -280,45 +335,55 @@ public final class ListTag extends Tag {
/** /**
* Get a {@code TagList} named with the given index. * Get a {@code TagList} named with the given index.
* *
* <p>If the index does not exist or its value is not a list tag, * <p>
* then an empty tag list will be returned.</p> * If the index does not exist or its value is not a list tag, then an empty
* tag list will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a tag list instance * @return a tag list instance
*/ */
public ListTag getListTag(int index) { public ListTag getListTag(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
return (ListTag) tag; return (ListTag) tag;
} else { }
return new ListTag(StringTag.class, Collections.<Tag>emptyList()); else {
return new ListTag(StringTag.class, Collections.<Tag> emptyList());
} }
} }
/** /**
* Get a list of tags named with the given index. * Get a list of tags named with the given index.
* *
* <p>If the index does not exist or its value is not a list tag, * <p>
* then an empty list will be returned. If the given index references * If the index does not exist or its value is not a list tag, then an empty
* a list but the list of of a different type, then an empty * list will be returned. If the given index references a list but the list
* list will also be returned.</p> * of of a different type, then an empty list will also be returned.
* </p>
* *
* @param index the index * @param index
* @param listType the class of the contained type * the index
* @param listType
* the class of the contained type
* @return a list of tags * @return a list of tags
* @param <T> the NBT type * @param <T>
* the NBT type
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(int index, Class<T> listType) { public <T extends Tag> List<T> getList(final int index, final Class<T> listType) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag; final ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) { if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue(); return (List<T>) listTag.getValue();
} else { }
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} else { }
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@ -326,17 +391,21 @@ public final class ListTag extends Tag {
/** /**
* Get a long named with the given index. * Get a long named with the given index.
* *
* <p>If the index does not exist or its value is not a long tag, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a long tag, then
* {@code 0} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a long * @return a long
*/ */
public long getLong(int index) { public long getLong(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof LongTag) { if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else { }
else {
return 0L; 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 * Get a long named with the given index, even if it's another
* type of number. * type of number.
* *
* <p>If the index does not exist or its value is not a number, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a number, then {@code 0}
* will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a long * @return a long
*/ */
public long asLong(int index) { public long asLong(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { }
else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) { }
else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) { }
else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) { }
else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().longValue(); return ((FloatTag) tag).getValue().longValue();
} else if (tag instanceof DoubleTag) { }
else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().longValue(); return ((DoubleTag) tag).getValue().longValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -379,17 +457,21 @@ public final class ListTag extends Tag {
/** /**
* Get a short named with the given index. * Get a short named with the given index.
* *
* <p>If the index does not exist or its value is not a short tag, * <p>
* then {@code 0} will be returned.</p> * If the index does not exist or its value is not a short tag, then
* {@code 0} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a short * @return a short
*/ */
public short getShort(int index) { public short getShort(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof ShortTag) { if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else { }
else {
return 0; return 0;
} }
} }
@ -397,31 +479,35 @@ public final class ListTag extends Tag {
/** /**
* Get a string named with the given index. * Get a string named with the given index.
* *
* <p>If the index does not exist or its value is not a string tag, * <p>
* then {@code ""} will be returned.</p> * If the index does not exist or its value is not a string tag, then
* {@code ""} will be returned.
* </p>
* *
* @param index the index * @param index
* the index
* @return a string * @return a string
*/ */
public String getString(int index) { public String getString(final int index) {
Tag tag = getIfExists(index); final Tag tag = getIfExists(index);
if (tag instanceof StringTag) { if (tag instanceof StringTag) {
return ((StringTag) tag).getValue(); return ((StringTag) tag).getValue();
} else { }
else {
return ""; return "";
} }
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
StringBuilder bldr = new StringBuilder(); final 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"); 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 (Tag t : value) { for (final Tag t : this.value) {
bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
} }
bldr.append("}"); bldr.append("}");

View File

@ -1,12 +1,12 @@
package com.intellectualcrafters.jnbt; package com.intellectualcrafters.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Helps create list tags. * Helps create list tags.
*/ */
@ -18,9 +18,10 @@ public class ListTagBuilder {
/** /**
* Create a new instance. * Create a new instance.
* *
* @param type of tag contained in this list * @param type
* of tag contained in this list
*/ */
ListTagBuilder(Class<? extends Tag> type) { ListTagBuilder(final Class<? extends Tag> type) {
checkNotNull(type); checkNotNull(type);
this.type = type; this.type = type;
this.entries = new ArrayList<Tag>(); this.entries = new ArrayList<Tag>();
@ -29,27 +30,29 @@ public class ListTagBuilder {
/** /**
* Add the given tag. * Add the given tag.
* *
* @param value the tag * @param value
* the tag
* @return this object * @return this object
*/ */
public ListTagBuilder add(Tag value) { public ListTagBuilder add(final Tag value) {
checkNotNull(value); checkNotNull(value);
if (!type.isInstance(value)) { if (!this.type.isInstance(value)) {
throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName()); throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + this.type.getCanonicalName());
} }
entries.add(value); this.entries.add(value);
return this; return this;
} }
/** /**
* Add all the tags in the given list. * Add all the tags in the given list.
* *
* @param value a list of tags * @param value
* a list of tags
* @return this object * @return this object
*/ */
public ListTagBuilder addAll(Collection<? extends Tag> value) { public ListTagBuilder addAll(final Collection<? extends Tag> value) {
checkNotNull(value); checkNotNull(value);
for (Tag v : value) { for (final Tag v : value) {
add(v); add(v);
} }
return this; return this;
@ -61,17 +64,18 @@ public class ListTagBuilder {
* @return the new list tag * @return the new list tag
*/ */
public ListTag build() { public ListTag build() {
return new ListTag(type, new ArrayList<Tag>(entries)); return new ListTag(this.type, new ArrayList<Tag>(this.entries));
} }
/** /**
* Build a new list tag with this builder's 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 * @return the created list tag
*/ */
public ListTag build(String name) { public ListTag build(final String name) {
return new ListTag(name, type, new ArrayList<Tag>(entries)); return new ListTag(name, this.type, new ArrayList<Tag>(this.entries));
} }
/** /**
@ -79,7 +83,7 @@ public class ListTagBuilder {
* *
* @return a new builder * @return a new builder
*/ */
public static ListTagBuilder create(Class<? extends Tag> type) { public static ListTagBuilder create(final Class<? extends Tag> type) {
return new ListTagBuilder(type); return new ListTagBuilder(type);
} }
@ -88,21 +92,21 @@ public class ListTagBuilder {
* *
* @return a new builder * @return a new builder
*/ */
public static <T extends Tag> ListTagBuilder createWith(T ... entries) { public static <T extends Tag> ListTagBuilder createWith(final T... entries) {
checkNotNull(entries); checkNotNull(entries);
if (entries.length == 0) { if (entries.length == 0) {
throw new IllegalArgumentException("This method needs an array of at least one entry"); throw new IllegalArgumentException("This method needs an array of at least one entry");
} }
Class<? extends Tag> type = entries[0].getClass(); final Class<? extends Tag> type = entries[0].getClass();
for (int i = 1; i < entries.length; i++) { for (int i = 1; i < entries.length; i++) {
if (!type.isInstance(entries[i])) { if (!type.isInstance(entries[i])) {
throw new IllegalArgumentException("An array of different tag types was provided"); 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)); builder.addAll(Arrays.asList(entries));
return builder; return builder;
} }

View File

@ -11,9 +11,10 @@ public final class LongTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -21,27 +22,29 @@ public final class LongTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Long getValue() { public Long getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Long" + append + ": " + value; return "TAG_Long" + append + ": " + this.value;
} }
} }

View File

@ -9,10 +9,7 @@ public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8"); public static final Charset CHARSET = Charset.forName("UTF-8");
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
TYPE_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. * Default private constructor.
@ -24,11 +21,13 @@ public final class NBTConstants {
/** /**
* Convert a type ID to its corresponding {@link Tag} class. * Convert a type ID to its corresponding {@link Tag} class.
* *
* @param id type ID * @param id
* type ID
* @return tag class * @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<? extends Tag> getClassFromType(int id) { public static Class<? extends Tag> getClassFromType(final int id) {
switch (id) { switch (id) {
case TYPE_END: case TYPE_END:
return EndTag.class; return EndTag.class;

View File

@ -14,9 +14,11 @@ import java.util.Map;
* streams, and produces an object graph of subclasses of the {@code Tag} * streams, and produces an object graph of subclasses of the {@code Tag}
* object. * object.
* *
* <p>The NBT format was created by Markus Persson, and the specification may be * <p>
* The NBT format was created by Markus Persson, and the specification may be
* found at <a href="http://www.minecraft.net/docs/NBT.txt"> * found at <a href="http://www.minecraft.net/docs/NBT.txt">
* http://www.minecraft.net/docs/NBT.txt</a>.</p> * http://www.minecraft.net/docs/NBT.txt</a>.
* </p>
*/ */
public final class NBTInputStream implements Closeable { public final class NBTInputStream implements Closeable {
@ -26,10 +28,12 @@ public final class NBTInputStream implements Closeable {
* Creates a new {@code NBTInputStream}, which will source its data * Creates a new {@code NBTInputStream}, which will source its data
* from the specified input stream. * from the specified input stream.
* *
* @param is the input stream * @param is
* @throws IOException if an I/O error occurs * 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); this.is = new DataInputStream(is);
} }
@ -37,7 +41,8 @@ public final class NBTInputStream implements Closeable {
* Reads an NBT tag from the stream. * Reads an NBT tag from the stream.
* *
* @return The tag that was read. * @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 { public Tag readTag() throws IOException {
return readTag(0); return readTag(0);
@ -46,20 +51,23 @@ public final class NBTInputStream implements Closeable {
/** /**
* Reads an NBT from the stream. * 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. * @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 { private Tag readTag(final int depth) throws IOException {
int type = is.readByte() & 0xFF; final int type = this.is.readByte() & 0xFF;
String name; String name;
if (type != NBTConstants.TYPE_END) { if (type != NBTConstants.TYPE_END) {
int nameLength = is.readShort() & 0xFFFF; final int nameLength = this.is.readShort() & 0xFFFF;
byte[] nameBytes = new byte[nameLength]; final byte[] nameBytes = new byte[nameLength];
is.readFully(nameBytes); this.is.readFully(nameBytes);
name = new String(nameBytes, NBTConstants.CHARSET); name = new String(nameBytes, NBTConstants.CHARSET);
} else { }
else {
name = ""; name = "";
} }
@ -69,50 +77,54 @@ public final class NBTInputStream implements Closeable {
/** /**
* Reads the payload of a tag, given the name and type. * Reads the payload of a tag, given the name and type.
* *
* @param type the type * @param type
* @param name the name * the type
* @param depth the depth * @param name
* the name
* @param depth
* the depth
* @return the tag * @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) { switch (type) {
case NBTConstants.TYPE_END: case NBTConstants.TYPE_END:
if (depth == 0) { if (depth == 0) {
throw new IOException( throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
"TAG_End found without a TAG_Compound/TAG_List tag preceding it."); }
} else { else {
return new EndTag(); return new EndTag();
} }
case NBTConstants.TYPE_BYTE: case NBTConstants.TYPE_BYTE:
return new ByteTag(name, is.readByte()); return new ByteTag(name, this.is.readByte());
case NBTConstants.TYPE_SHORT: case NBTConstants.TYPE_SHORT:
return new ShortTag(name, is.readShort()); return new ShortTag(name, this.is.readShort());
case NBTConstants.TYPE_INT: case NBTConstants.TYPE_INT:
return new IntTag(name, is.readInt()); return new IntTag(name, this.is.readInt());
case NBTConstants.TYPE_LONG: case NBTConstants.TYPE_LONG:
return new LongTag(name, is.readLong()); return new LongTag(name, this.is.readLong());
case NBTConstants.TYPE_FLOAT: case NBTConstants.TYPE_FLOAT:
return new FloatTag(name, is.readFloat()); return new FloatTag(name, this.is.readFloat());
case NBTConstants.TYPE_DOUBLE: case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(name, is.readDouble()); return new DoubleTag(name, this.is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY: case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt(); int length = this.is.readInt();
byte[] bytes = new byte[length]; byte[] bytes = new byte[length];
is.readFully(bytes); this.is.readFully(bytes);
return new ByteArrayTag(name, bytes); return new ByteArrayTag(name, bytes);
case NBTConstants.TYPE_STRING: case NBTConstants.TYPE_STRING:
length = is.readShort(); length = this.is.readShort();
bytes = new byte[length]; bytes = new byte[length];
is.readFully(bytes); this.is.readFully(bytes);
return new StringTag(name, new String(bytes, NBTConstants.CHARSET)); return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST: case NBTConstants.TYPE_LIST:
int childType = is.readByte(); final int childType = this.is.readByte();
length = is.readInt(); length = this.is.readInt();
List<Tag> tagList = new ArrayList<Tag>(); final List<Tag> tagList = new ArrayList<Tag>();
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
Tag tag = readTagPayload(childType, "", depth + 1); final Tag tag = readTagPayload(childType, "", depth + 1);
if (tag instanceof EndTag) { if (tag instanceof EndTag) {
throw new IOException("TAG_End not permitted in a list."); throw new IOException("TAG_End not permitted in a list.");
} }
@ -121,22 +133,23 @@ public final class NBTInputStream implements Closeable {
return new ListTag(name, NBTUtils.getTypeClass(childType), tagList); return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND: case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<String, Tag>(); final Map<String, Tag> tagMap = new HashMap<String, Tag>();
while (true) { while (true) {
Tag tag = readTag(depth + 1); final Tag tag = readTag(depth + 1);
if (tag instanceof EndTag) { if (tag instanceof EndTag) {
break; break;
} else { }
else {
tagMap.put(tag.getName(), tag); tagMap.put(tag.getName(), tag);
} }
} }
return new CompoundTag(name, tagMap); return new CompoundTag(name, tagMap);
case NBTConstants.TYPE_INT_ARRAY: case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt(); length = this.is.readInt();
int[] data = new int[length]; final int[] data = new int[length];
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
data[i] = is.readInt(); data[i] = this.is.readInt();
} }
return new IntArrayTag(name, data); return new IntArrayTag(name, data);
default: default:
@ -146,7 +159,7 @@ public final class NBTInputStream implements Closeable {
@Override @Override
public void close() throws IOException { public void close() throws IOException {
is.close(); this.is.close();
} }
} }

View File

@ -37,7 +37,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
public NBTOutputStream(OutputStream os) throws IOException { public NBTOutputStream(final OutputStream os) throws IOException {
this.os = new DataOutputStream(os); this.os = new DataOutputStream(os);
} }
@ -49,14 +49,14 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
public void writeTag(Tag tag) throws IOException { public void writeTag(final Tag tag) throws IOException {
int type = NBTUtils.getTypeCode(tag.getClass()); final int type = NBTUtils.getTypeCode(tag.getClass());
String name = tag.getName(); final String name = tag.getName();
byte[] nameBytes = name.getBytes(NBTConstants.CHARSET); final byte[] nameBytes = name.getBytes(NBTConstants.CHARSET);
os.writeByte(type); this.os.writeByte(type);
os.writeShort(nameBytes.length); this.os.writeShort(nameBytes.length);
os.write(nameBytes); this.os.write(nameBytes);
if (type == NBTConstants.TYPE_END) { if (type == NBTConstants.TYPE_END) {
throw new IOException("Named TAG_End not permitted."); throw new IOException("Named TAG_End not permitted.");
@ -73,8 +73,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeTagPayload(Tag tag) throws IOException { private void writeTagPayload(final Tag tag) throws IOException {
int type = NBTUtils.getTypeCode(tag.getClass()); final int type = NBTUtils.getTypeCode(tag.getClass());
switch (type) { switch (type) {
case NBTConstants.TYPE_END: case NBTConstants.TYPE_END:
writeEndTagPayload((EndTag) tag); writeEndTagPayload((EndTag) tag);
@ -125,8 +125,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeByteTagPayload(ByteTag tag) throws IOException { private void writeByteTagPayload(final ByteTag tag) throws IOException {
os.writeByte(tag.getValue()); this.os.writeByte(tag.getValue());
} }
/** /**
@ -137,10 +137,10 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeByteArrayTagPayload(ByteArrayTag tag) throws IOException { private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException {
byte[] bytes = tag.getValue(); final byte[] bytes = tag.getValue();
os.writeInt(bytes.length); this.os.writeInt(bytes.length);
os.write(bytes); this.os.write(bytes);
} }
/** /**
@ -151,11 +151,11 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeCompoundTagPayload(CompoundTag tag) throws IOException { private void writeCompoundTagPayload(final CompoundTag tag) throws IOException {
for (Tag childTag : tag.getValue().values()) { for (final Tag childTag : tag.getValue().values()) {
writeTag(childTag); writeTag(childTag);
} }
os.writeByte((byte) 0); // end tag - better way? this.os.writeByte((byte) 0); // end tag - better way?
} }
/** /**
@ -166,13 +166,13 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeListTagPayload(ListTag tag) throws IOException { private void writeListTagPayload(final ListTag tag) throws IOException {
Class<? extends Tag> clazz = tag.getType(); final Class<? extends Tag> clazz = tag.getType();
List<Tag> tags = tag.getValue(); final List<Tag> tags = tag.getValue();
int size = tags.size(); final int size = tags.size();
os.writeByte(NBTUtils.getTypeCode(clazz)); this.os.writeByte(NBTUtils.getTypeCode(clazz));
os.writeInt(size); this.os.writeInt(size);
for (int i = 0; i < size; ++i) { for (int i = 0; i < size; ++i) {
writeTagPayload(tags.get(i)); writeTagPayload(tags.get(i));
} }
@ -186,10 +186,10 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeStringTagPayload(StringTag tag) throws IOException { private void writeStringTagPayload(final StringTag tag) throws IOException {
byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET); final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET);
os.writeShort(bytes.length); this.os.writeShort(bytes.length);
os.write(bytes); this.os.write(bytes);
} }
/** /**
@ -200,8 +200,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeDoubleTagPayload(DoubleTag tag) throws IOException { private void writeDoubleTagPayload(final DoubleTag tag) throws IOException {
os.writeDouble(tag.getValue()); this.os.writeDouble(tag.getValue());
} }
/** /**
@ -212,8 +212,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeFloatTagPayload(FloatTag tag) throws IOException { private void writeFloatTagPayload(final FloatTag tag) throws IOException {
os.writeFloat(tag.getValue()); this.os.writeFloat(tag.getValue());
} }
/** /**
@ -224,8 +224,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeLongTagPayload(LongTag tag) throws IOException { private void writeLongTagPayload(final LongTag tag) throws IOException {
os.writeLong(tag.getValue()); this.os.writeLong(tag.getValue());
} }
/** /**
@ -236,8 +236,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeIntTagPayload(IntTag tag) throws IOException { private void writeIntTagPayload(final IntTag tag) throws IOException {
os.writeInt(tag.getValue()); this.os.writeInt(tag.getValue());
} }
/** /**
@ -248,8 +248,8 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeShortTagPayload(ShortTag tag) throws IOException { private void writeShortTagPayload(final ShortTag tag) throws IOException {
os.writeShort(tag.getValue()); this.os.writeShort(tag.getValue());
} }
/** /**
@ -260,20 +260,21 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException * @throws IOException
* if an I/O error occurs. * if an I/O error occurs.
*/ */
private void writeEndTagPayload(EndTag tag) { private void writeEndTagPayload(final EndTag tag) {
/* empty */ /* empty */
} }
private void writeIntArrayTagPayload(IntArrayTag tag) throws IOException { private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException {
int[] data = tag.getValue(); final int[] data = tag.getValue();
os.writeInt(data.length); this.os.writeInt(data.length);
for (int i = 0; i < data.length; i++) { for (final int element : data) {
os.writeInt(data[i]); this.os.writeInt(element);
} }
} }
@Override
public void close() throws IOException { public void close() throws IOException {
os.close(); this.os.close();
} }
} }

View File

@ -17,86 +17,113 @@ public final class NBTUtils {
/** /**
* Gets the type name of a tag. * Gets the type name of a tag.
* *
* @param clazz the tag class * @param clazz
* the tag class
* @return The type name. * @return The type name.
*/ */
public static String getTypeName(Class<? extends Tag> clazz) { public static String getTypeName(final Class<? extends Tag> clazz) {
if (clazz.equals(ByteArrayTag.class)) { if (clazz.equals(ByteArrayTag.class)) {
return "TAG_Byte_Array"; return "TAG_Byte_Array";
} else if (clazz.equals(ByteTag.class)) { }
else if (clazz.equals(ByteTag.class)) {
return "TAG_Byte"; return "TAG_Byte";
} else if (clazz.equals(CompoundTag.class)) { }
else if (clazz.equals(CompoundTag.class)) {
return "TAG_Compound"; return "TAG_Compound";
} else if (clazz.equals(DoubleTag.class)) { }
else if (clazz.equals(DoubleTag.class)) {
return "TAG_Double"; return "TAG_Double";
} else if (clazz.equals(EndTag.class)) { }
else if (clazz.equals(EndTag.class)) {
return "TAG_End"; return "TAG_End";
} else if (clazz.equals(FloatTag.class)) { }
else if (clazz.equals(FloatTag.class)) {
return "TAG_Float"; return "TAG_Float";
} else if (clazz.equals(IntTag.class)) { }
else if (clazz.equals(IntTag.class)) {
return "TAG_Int"; return "TAG_Int";
} else if (clazz.equals(ListTag.class)) { }
else if (clazz.equals(ListTag.class)) {
return "TAG_List"; return "TAG_List";
} else if (clazz.equals(LongTag.class)) { }
else if (clazz.equals(LongTag.class)) {
return "TAG_Long"; return "TAG_Long";
} else if (clazz.equals(ShortTag.class)) { }
else if (clazz.equals(ShortTag.class)) {
return "TAG_Short"; return "TAG_Short";
} else if (clazz.equals(StringTag.class)) { }
else if (clazz.equals(StringTag.class)) {
return "TAG_String"; return "TAG_String";
} else if (clazz.equals(IntArrayTag.class)) { }
else if (clazz.equals(IntArrayTag.class)) {
return "TAG_Int_Array"; return "TAG_Int_Array";
} else { }
throw new IllegalArgumentException("Invalid tag classs (" else {
+ clazz.getName() + ")."); throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ").");
} }
} }
/** /**
* Gets the type code of a tag class. * Gets the type code of a tag class.
* *
* @param clazz the tag class * @param clazz
* the tag class
* @return The type code. * @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<? extends Tag> clazz) { public static int getTypeCode(final Class<? extends Tag> clazz) {
if (clazz.equals(ByteArrayTag.class)) { if (clazz.equals(ByteArrayTag.class)) {
return NBTConstants.TYPE_BYTE_ARRAY; return NBTConstants.TYPE_BYTE_ARRAY;
} else if (clazz.equals(ByteTag.class)) { }
else if (clazz.equals(ByteTag.class)) {
return NBTConstants.TYPE_BYTE; return NBTConstants.TYPE_BYTE;
} else if (clazz.equals(CompoundTag.class)) { }
else if (clazz.equals(CompoundTag.class)) {
return NBTConstants.TYPE_COMPOUND; return NBTConstants.TYPE_COMPOUND;
} else if (clazz.equals(DoubleTag.class)) { }
else if (clazz.equals(DoubleTag.class)) {
return NBTConstants.TYPE_DOUBLE; return NBTConstants.TYPE_DOUBLE;
} else if (clazz.equals(EndTag.class)) { }
else if (clazz.equals(EndTag.class)) {
return NBTConstants.TYPE_END; return NBTConstants.TYPE_END;
} else if (clazz.equals(FloatTag.class)) { }
else if (clazz.equals(FloatTag.class)) {
return NBTConstants.TYPE_FLOAT; return NBTConstants.TYPE_FLOAT;
} else if (clazz.equals(IntTag.class)) { }
else if (clazz.equals(IntTag.class)) {
return NBTConstants.TYPE_INT; return NBTConstants.TYPE_INT;
} else if (clazz.equals(ListTag.class)) { }
else if (clazz.equals(ListTag.class)) {
return NBTConstants.TYPE_LIST; return NBTConstants.TYPE_LIST;
} else if (clazz.equals(LongTag.class)) { }
else if (clazz.equals(LongTag.class)) {
return NBTConstants.TYPE_LONG; return NBTConstants.TYPE_LONG;
} else if (clazz.equals(ShortTag.class)) { }
else if (clazz.equals(ShortTag.class)) {
return NBTConstants.TYPE_SHORT; return NBTConstants.TYPE_SHORT;
} else if (clazz.equals(StringTag.class)) { }
else if (clazz.equals(StringTag.class)) {
return NBTConstants.TYPE_STRING; return NBTConstants.TYPE_STRING;
} else if (clazz.equals(IntArrayTag.class)) { }
else if (clazz.equals(IntArrayTag.class)) {
return NBTConstants.TYPE_INT_ARRAY; return NBTConstants.TYPE_INT_ARRAY;
} else { }
throw new IllegalArgumentException("Invalid tag classs (" else {
+ clazz.getName() + ")."); throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ").");
} }
} }
/** /**
* Gets the class of a type of tag. * Gets the class of a type of tag.
* *
* @param type the type * @param type
* the type
* @return The class. * @return The class.
* @throws IllegalArgumentException if the tag type is invalid. * @throws IllegalArgumentException
* if the tag type is invalid.
*/ */
public static Class<? extends Tag> getTypeClass(int type) { public static Class<? extends Tag> getTypeClass(final int type) {
switch (type) { switch (type) {
case NBTConstants.TYPE_END: case NBTConstants.TYPE_END:
return EndTag.class; return EndTag.class;
@ -123,25 +150,27 @@ public final class NBTUtils {
case NBTConstants.TYPE_INT_ARRAY: case NBTConstants.TYPE_INT_ARRAY:
return IntArrayTag.class; return IntArrayTag.class;
default: default:
throw new IllegalArgumentException("Invalid tag type : " + type throw new IllegalArgumentException("Invalid tag type : " + type + ".");
+ ".");
} }
} }
/** /**
* Get child tag of a NBT structure. * Get child tag of a NBT structure.
* *
* @param items the map to read from * @param items
* @param key the key to look for * the map to read from
* @param expected the expected NBT class type * @param key
* the key to look for
* @param expected
* the expected NBT class type
* @return child tag * @return child tag
* @throws InvalidFormatException * @throws InvalidFormatException
*/ */
public static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws IllegalArgumentException { public static <T extends Tag> T getChildTag(final Map<String, Tag> items, final String key, final Class<T> expected) throws IllegalArgumentException {
if (!items.containsKey(key)) { if (!items.containsKey(key)) {
throw new IllegalArgumentException("Missing a \"" + key + "\" tag"); throw new IllegalArgumentException("Missing a \"" + key + "\" tag");
} }
Tag tag = items.get(key); final Tag tag = items.get(key);
if (!expected.isInstance(tag)) { if (!expected.isInstance(tag)) {
throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName()); throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName());
} }

View File

@ -10,9 +10,10 @@ public final class ShortTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
this.value = value; this.value = value;
} }
@ -20,27 +21,29 @@ public final class ShortTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Short getValue() { public Short getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_Short" + append + ": " + value; return "TAG_Short" + append + ": " + this.value;
} }
} }

View File

@ -12,9 +12,10 @@ public final class StringTag extends Tag {
/** /**
* Creates the tag with an empty name. * 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(); super();
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
@ -23,10 +24,12 @@ public final class StringTag extends Tag {
/** /**
* Creates the tag. * Creates the tag.
* *
* @param name the name of the tag * @param name
* @param value the value of the tag * 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); super(name);
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
@ -34,17 +37,17 @@ public final class StringTag extends Tag {
@Override @Override
public String getValue() { public String getValue() {
return value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
String name = getName(); final String name = getName();
String append = ""; String append = "";
if (name != null && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + this.getName() + "\")";
} }
return "TAG_String" + append + ": " + value; return "TAG_String" + append + ": " + this.value;
} }
} }

View File

@ -17,7 +17,8 @@ public abstract class Tag {
/** /**
* Creates the tag with the specified name. * Creates the tag with the specified name.
* *
* @param name the name * @param name
* the name
*/ */
Tag(String name) { Tag(String name) {
if (name == null) { if (name == null) {
@ -32,7 +33,7 @@ public abstract class Tag {
* @return the name of this tag * @return the name of this tag
*/ */
public final String getName() { public final String getName() {
return name; return this.name;
} }
/** /**

View File

@ -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();
// }
}
}

View File

@ -1,28 +1,28 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* This provides static methods to convert comma delimited text into a * 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 * delimited text is a very popular format for data interchange. It is
* understood by most database, spreadsheet, and organizer programs. * understood by most database, spreadsheet, and organizer programs.
* <p> * <p>
* Each row of text represents a row in a table or a data record. Each row * Each row of text represents a row in a table or a data record. Each row ends
* ends with a NEWLINE character. Each row contains one or more values. * with a NEWLINE character. Each row contains one or more values. Values are
* Values are separated by commas. A value can contain any character except * separated by commas. A value can contain any character except for comma,
* for comma, unless is is wrapped in single quotes or double quotes. * unless is is wrapped in single quotes or double quotes.
* <p> * <p>
* The first row usually contains the names of the columns. * The first row usually contains the names of the columns.
* <p> * <p>
* A comma delimited list can be converted into a JSONArray of JSONObjects. * A comma delimited list can be converted into a JSONArray of JSONObjects. The
* The names for the elements in the JSONObjects can be taken from the names * names for the elements in the JSONObjects can be taken from the names in the
* in the first row. * first row.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
@ -48,17 +49,21 @@ public class CDL {
/** /**
* Get the next value. The value can be wrapped in quotes. The value can * Get the next value. The value can be wrapped in quotes. The value can
* be empty. * 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. * @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 c;
char q; char q;
StringBuffer sb; StringBuffer sb;
do { do {
c = x.next(); c = x.next();
} while (c == ' ' || c == '\t'); }
while ((c == ' ') || (c == '\t'));
switch (c) { switch (c) {
case 0: case 0:
return null; return null;
@ -71,7 +76,7 @@ public class CDL {
if (c == q) { if (c == q) {
break; break;
} }
if (c == 0 || c == '\n' || c == '\r') { if ((c == 0) || (c == '\n') || (c == '\r')) {
throw x.syntaxError("Missing close quote '" + q + "'."); throw x.syntaxError("Missing close quote '" + q + "'.");
} }
sb.append(c); sb.append(c);
@ -88,17 +93,18 @@ public class CDL {
/** /**
* Produce a JSONArray of strings from a row of comma delimited values. * 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. * @return A JSONArray of strings.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray(); final JSONArray ja = new JSONArray();
for (;;) { for (;;) {
String value = getValue(x); final String value = getValue(x);
char c = x.next(); char c = x.next();
if (value == null || if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) {
(ja.length() == 0 && value.length() == 0 && c != ',')) {
return null; return null;
} }
ja.put(value); ja.put(value);
@ -107,11 +113,10 @@ public class CDL {
break; break;
} }
if (c != ' ') { if (c != ' ') {
if (c == '\n' || c == '\r' || c == 0) { if ((c == '\n') || (c == '\r') || (c == 0)) {
return ja; return ja;
} }
throw x.syntaxError("Bad character '" + c + "' (" + throw x.syntaxError("Bad character '" + c + "' (" + (int) c + ").");
(int)c + ").");
} }
c = x.next(); c = x.next();
} }
@ -121,16 +126,19 @@ public class CDL {
/** /**
* Produce a JSONObject from a row of comma delimited text, using a * Produce a JSONObject from a row of comma delimited text, using a
* parallel JSONArray of strings to provides the names of the elements. * 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 * @param names
* A JSONArray of names. This is commonly obtained from the
* first row of a comma delimited text file using the
* rowToJSONArray
* method. * method.
* @param x A JSONTokener of the source text. * @param x
* A JSONTokener of the source text.
* @return A JSONObject combining the names and values. * @return A JSONObject combining the names and values.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException {
throws JSONException { final JSONArray ja = rowToJSONArray(x);
JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null; return ja != null ? ja.toJSONObject(names) : null;
} }
@ -138,31 +146,32 @@ public class CDL {
* Produce a comma delimited text row from a JSONArray. Values containing * Produce a comma delimited text row from a JSONArray. Values containing
* the comma character will be quoted. Troublesome characters may be * the comma character will be quoted. Troublesome characters may be
* removed. * removed.
* @param ja A JSONArray of strings. *
* @param ja
* A JSONArray of strings.
* @return A string ending in NEWLINE. * @return A string ending in NEWLINE.
*/ */
public static String rowToString(JSONArray ja) { public static String rowToString(final JSONArray ja) {
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (int i = 0; i < ja.length(); i += 1) { for (int i = 0; i < ja.length(); i += 1) {
if (i > 0) { if (i > 0) {
sb.append(','); sb.append(',');
} }
Object object = ja.opt(i); final Object object = ja.opt(i);
if (object != null) { if (object != null) {
String string = object.toString(); final String string = object.toString();
if (string.length() > 0 && (string.indexOf(',') >= 0 || if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
sb.append('"'); sb.append('"');
int length = string.length(); final int length = string.length();
for (int j = 0; j < length; j += 1) { for (int j = 0; j < length; j += 1) {
char c = string.charAt(j); final char c = string.charAt(j);
if (c >= ' ' && c != '"') { if ((c >= ' ') && (c != '"')) {
sb.append(c); sb.append(c);
} }
} }
sb.append('"'); sb.append('"');
} else { }
else {
sb.append(string); sb.append(string);
} }
} }
@ -174,54 +183,62 @@ public class CDL {
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string, * Produce a JSONArray of JSONObjects from a comma delimited text string,
* using the first row as a source of names. * 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. * @return A JSONArray of JSONObjects.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(String string) throws JSONException { public static JSONArray toJSONArray(final String string) throws JSONException {
return toJSONArray(new JSONTokener(string)); return toJSONArray(new JSONTokener(string));
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string, * Produce a JSONArray of JSONObjects from a comma delimited text string,
* using the first row as a source of names. * 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. * @return A JSONArray of JSONObjects.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(JSONTokener x) throws JSONException { public static JSONArray toJSONArray(final JSONTokener x) throws JSONException {
return toJSONArray(rowToJSONArray(x), x); return toJSONArray(rowToJSONArray(x), x);
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string * Produce a JSONArray of JSONObjects from a comma delimited text string
* using a supplied JSONArray as the source of element names. * 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. * @return A JSONArray of JSONObjects.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(JSONArray names, String string) public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException {
throws JSONException {
return toJSONArray(names, new JSONTokener(string)); return toJSONArray(names, new JSONTokener(string));
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string * Produce a JSONArray of JSONObjects from a comma delimited text string
* using a supplied JSONArray as the source of element names. * 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. * @return A JSONArray of JSONObjects.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(JSONArray names, JSONTokener x) public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException {
throws JSONException { if ((names == null) || (names.length() == 0)) {
if (names == null || names.length() == 0) {
return null; return null;
} }
JSONArray ja = new JSONArray(); final JSONArray ja = new JSONArray();
for (;;) { for (;;) {
JSONObject jo = rowToJSONObject(names, x); final JSONObject jo = rowToJSONObject(names, x);
if (jo == null) { if (jo == null) {
break; break;
} }
@ -233,19 +250,20 @@ public class CDL {
return ja; return ja;
} }
/** /**
* Produce a comma delimited text from a JSONArray of JSONObjects. The * Produce a comma delimited text from a JSONArray of JSONObjects. The
* first row will be a list of names obtained by inspecting the first * first row will be a list of names obtained by inspecting the first
* JSONObject. * JSONObject.
* @param ja A JSONArray of JSONObjects. *
* @param ja
* A JSONArray of JSONObjects.
* @return A comma delimited text. * @return A comma delimited text.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONArray ja) throws JSONException { public static String toString(final JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0); final JSONObject jo = ja.optJSONObject(0);
if (jo != null) { if (jo != null) {
JSONArray names = jo.names(); final JSONArray names = jo.names();
if (names != null) { if (names != null) {
return rowToString(names) + toString(names, ja); return rowToString(names) + toString(names, ja);
} }
@ -257,19 +275,21 @@ public class CDL {
* Produce a comma delimited text from a JSONArray of JSONObjects using * 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 * a provided list of names. The list of names is not included in the
* output. * 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. * @return A comma delimited text.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONArray names, JSONArray ja) public static String toString(final JSONArray names, final JSONArray ja) throws JSONException {
throws JSONException { if ((names == null) || (names.length() == 0)) {
if (names == null || names.length() == 0) {
return null; return null;
} }
StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
for (int i = 0; i < ja.length(); i += 1) { for (int i = 0; i < ja.length(); i += 1) {
JSONObject jo = ja.optJSONObject(i); final JSONObject jo = ja.optJSONObject(i);
if (jo != null) { if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names))); sb.append(rowToString(jo.toJSONArray(names)));
} }

View File

@ -1,31 +1,33 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* Convert a web browser cookie specification to a JSONObject and back. * Convert a web browser cookie specification to a JSONObject and back.
* JSON and Cookies are both notations for name/value pairs. * JSON and Cookies are both notations for name/value pairs.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
@ -40,28 +42,30 @@ public class Cookie {
* only a convention, not a standard. Often, cookies are expected to have * only a convention, not a standard. Often, cookies are expected to have
* encoded values. We encode '=' and ';' because we must. We encode '%' and * encoded values. We encode '=' and ';' because we must. We encode '%' and
* '+' because they are meta characters in URL encoding. * '+' because they are meta characters in URL encoding.
* @param string The source string. *
* @param string
* The source string.
* @return The escaped result. * @return The escaped result.
*/ */
public static String escape(String string) { public static String escape(final String string) {
char c; char c;
String s = string.trim(); final String s = string.trim();
int length = s.length(); final int length = s.length();
StringBuilder sb = new StringBuilder(length); final StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i += 1) { for (int i = 0; i < length; i += 1) {
c = s.charAt(i); c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { if ((c < ' ') || (c == '+') || (c == '%') || (c == '=') || (c == ';')) {
sb.append('%'); sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16)); sb.append(Character.forDigit((char) (c & 0x0f), 16));
} else { }
else {
sb.append(c); sb.append(c);
} }
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Convert a cookie specification string into a JSONObject. The string * Convert a cookie specification string into a JSONObject. The string
* will contain a name value pair separated by '='. The name and the value * 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 * stored under the key "value". This method does not do checking or
* validation of the parameters. It only converts the cookie string into * validation of the parameters. It only converts the cookie string into
* a JSONObject. * a JSONObject.
* @param string The cookie specification string. *
* @param string
* The cookie specification string.
* @return A JSONObject containing "name", "value", and possibly other * @return A JSONObject containing "name", "value", and possibly other
* members. * members.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
String name; String name;
JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
Object value; Object value;
JSONTokener x = new JSONTokener(string); final JSONTokener x = new JSONTokener(string);
jo.put("name", x.nextTo('=')); jo.put("name", x.nextTo('='));
x.next('='); x.next('=');
jo.put("value", x.nextTo(';')); jo.put("value", x.nextTo(';'));
@ -91,10 +97,12 @@ public class Cookie {
if (x.next() != '=') { if (x.next() != '=') {
if (name.equals("secure")) { if (name.equals("secure")) {
value = Boolean.TRUE; value = Boolean.TRUE;
} else { }
else {
throw x.syntaxError("Missing '=' in cookie parameter."); throw x.syntaxError("Missing '=' in cookie parameter.");
} }
} else { }
else {
value = unescape(x.nextTo(';')); value = unescape(x.nextTo(';'));
x.next(); x.next();
} }
@ -103,19 +111,20 @@ public class Cookie {
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a cookie specification string. The JSONObject * Convert a JSONObject into a cookie specification string. The JSONObject
* must contain "name" and "value" members. * must contain "name" and "value" members.
* If the JSONObject contains "expires", "domain", "path", or "secure" * If the JSONObject contains "expires", "domain", "path", or "secure"
* members, they will be appended to the cookie specification string. * members, they will be appended to the cookie specification string.
* All other members are ignored. * All other members are ignored.
* @param jo A JSONObject *
* @param jo
* A JSONObject
* @return A cookie specification string * @return A cookie specification string
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(final JSONObject jo) throws JSONException {
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(escape(jo.getString("name"))); sb.append(escape(jo.getString("name")));
sb.append("="); sb.append("=");
@ -141,23 +150,26 @@ public class Cookie {
/** /**
* Convert <code>%</code><i>hh</i> sequences to single characters, and * Convert <code>%</code><i>hh</i> sequences to single characters, and
* convert plus to space. * convert plus to space.
* @param string A string that may contain *
* <code>+</code>&nbsp;<small>(plus)</small> and * @param string
* <code>%</code><i>hh</i> sequences. * A string that may contain <code>+</code>
* &nbsp;<small>(plus)</small> and <code>%</code><i>hh</i>
* sequences.
* @return The unescaped string. * @return The unescaped string.
*/ */
public static String unescape(String string) { public static String unescape(final String string) {
int length = string.length(); final int length = string.length();
StringBuilder sb = new StringBuilder(length); final StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
char c = string.charAt(i); char c = string.charAt(i);
if (c == '+') { if (c == '+') {
c = ' '; c = ' ';
} else if (c == '%' && i + 2 < length) { }
int d = JSONTokener.dehexchar(string.charAt(i + 1)); else if ((c == '%') && ((i + 2) < length)) {
int e = JSONTokener.dehexchar(string.charAt(i + 2)); final int d = JSONTokener.dehexchar(string.charAt(i + 1));
if (d >= 0 && e >= 0) { final int e = JSONTokener.dehexchar(string.charAt(i + 2));
c = (char)(d * 16 + e); if ((d >= 0) && (e >= 0)) {
c = (char) ((d * 16) + e);
i += 2; i += 2;
} }
} }

View File

@ -1,33 +1,34 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.util.Iterator; import java.util.Iterator;
/** /**
* Convert a web browser cookie list string to a JSONObject and back. * Convert a web browser cookie list string to a JSONObject and back.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
@ -42,15 +43,17 @@ public class CookieList {
* To add a cookie to a cooklist, * To add a cookie to a cooklist,
* cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookielistJSONObject.put(cookieJSONObject.getString("name"),
* cookieJSONObject.getString("value")); * cookieJSONObject.getString("value"));
* @param string A cookie list string *
* @param string
* A cookie list string
* @return A JSONObject * @return A JSONObject
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
JSONTokener x = new JSONTokener(string); final JSONTokener x = new JSONTokener(string);
while (x.more()) { while (x.more()) {
String name = Cookie.unescape(x.nextTo('=')); final String name = Cookie.unescape(x.nextTo('='));
x.next('='); x.next('=');
jo.put(name, Cookie.unescape(x.nextTo(';'))); jo.put(name, Cookie.unescape(x.nextTo(';')));
x.next(); x.next();
@ -63,15 +66,17 @@ public class CookieList {
* of name/value pairs. The names are separated from the values by '='. * of name/value pairs. The names are separated from the values by '='.
* The pairs are separated by ';'. The characters '%', '+', '=', and ';' * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
* in the names and values are replaced by "%hh". * in the names and values are replaced by "%hh".
* @param jo A JSONObject *
* @param jo
* A JSONObject
* @return A cookie list string * @return A cookie list string
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(final JSONObject jo) throws JSONException {
boolean b = false; boolean b = false;
Iterator<String> keys = jo.keys(); final Iterator<String> keys = jo.keys();
String string; String string;
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
while (keys.hasNext()) { while (keys.hasNext()) {
string = keys.next(); string = keys.next();
if (!jo.isNull(string)) { if (!jo.isNull(string)) {

View File

@ -1,33 +1,34 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.util.Iterator; import java.util.Iterator;
/** /**
* Convert an HTTP header to a JSONObject and back. * Convert an HTTP header to a JSONObject and back.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
@ -39,63 +40,82 @@ public class HTTP {
/** /**
* Convert an HTTP header string into a JSONObject. It can be a request * Convert an HTTP header string into a JSONObject. It can be a request
* header or a response header. A request header will contain * header or a response header. A request header will contain
* <pre>{ *
* <pre>
* {
* Method: "POST" (for example), * Method: "POST" (for example),
* "Request-URI": "/" (for example), * "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example) * "HTTP-Version": "HTTP/1.1" (for example)
* }</pre> * }
* </pre>
*
* A response header will contain * A response header will contain
* <pre>{ *
* <pre>
* {
* "HTTP-Version": "HTTP/1.1" (for example), * "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example), * "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example) * "Reason-Phrase": "OK" (for example)
* }</pre> * }
* </pre>
*
* In addition, the other parameters in the header will be captured, using * In addition, the other parameters in the header will be captured, using
* the HTTP field names as JSON names, so that <pre> * the HTTP field names as JSON names, so that
*
* <pre>
* Date: Sun, 26 May 2002 18:06:04 GMT * Date: Sun, 26 May 2002 18:06:04 GMT
* Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
* Cache-Control: no-cache</pre> * Cache-Control: no-cache
* </pre>
*
* become * become
* <pre>{... *
* <pre>
* {...
* Date: "Sun, 26 May 2002 18:06:04 GMT", * Date: "Sun, 26 May 2002 18:06:04 GMT",
* Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
* "Cache-Control": "no-cache", * "Cache-Control": "no-cache",
* ...}</pre> * ...}
* </pre>
*
* It does no further checking or conversion. It does not parse dates. * It does no further checking or conversion. It does not parse dates.
* It does not do '%' transforms on URLs. * 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 * @return A JSONObject containing the elements and attributes
* of the XML string. * of the XML string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string); final HTTPTokener x = new HTTPTokener(string);
String token; String token;
token = x.nextToken(); token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) { if (token.toUpperCase().startsWith("HTTP")) {
// Response // Response
jo.put("HTTP-Version", token); jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken()); jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0')); jo.put("Reason-Phrase", x.nextTo('\0'));
x.next(); x.next();
} else { }
else {
// Request // Request
jo.put("Method", token); jo.put("Method", token);
jo.put("Request-URI", x.nextToken()); jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken()); jo.put("HTTP-Version", x.nextToken());
} }
// Fields // Fields
while (x.more()) { while (x.more()) {
String name = x.nextTo(':'); final String name = x.nextTo(':');
x.next(':'); x.next(':');
jo.put(name, x.nextTo('\0')); jo.put(name, x.nextTo('\0'));
x.next(); x.next();
@ -103,38 +123,49 @@ public class HTTP {
return jo; return jo;
} }
/** /**
* Convert a JSONObject into an HTTP header. A request header must contain * Convert a JSONObject into an HTTP header. A request header must contain
* <pre>{ *
* <pre>
* {
* Method: "POST" (for example), * Method: "POST" (for example),
* "Request-URI": "/" (for example), * "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example) * "HTTP-Version": "HTTP/1.1" (for example)
* }</pre> * }
* </pre>
*
* A response header must contain * A response header must contain
* <pre>{ *
* <pre>
* {
* "HTTP-Version": "HTTP/1.1" (for example), * "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example), * "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example) * "Reason-Phrase": "OK" (for example)
* }</pre> * }
* </pre>
*
* Any other members of the JSONObject will be output as HTTP fields. * Any other members of the JSONObject will be output as HTTP fields.
* The result will end with two CRLF pairs. * The result will end with two CRLF pairs.
* @param jo A JSONObject *
* @param jo
* A JSONObject
* @return An HTTP header string. * @return An HTTP header string.
* @throws JSONException if the object does not contain enough * @throws JSONException
* if the object does not contain enough
* information. * information.
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(final JSONObject jo) throws JSONException {
Iterator<String> keys = jo.keys(); final Iterator<String> keys = jo.keys();
String string; String string;
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
sb.append(jo.getString("HTTP-Version")); sb.append(jo.getString("HTTP-Version"));
sb.append(' '); sb.append(' ');
sb.append(jo.getString("Status-Code")); sb.append(jo.getString("Status-Code"));
sb.append(' '); sb.append(' ');
sb.append(jo.getString("Reason-Phrase")); 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(jo.getString("Method"));
sb.append(' '); sb.append(' ');
sb.append('"'); sb.append('"');
@ -142,15 +173,14 @@ public class HTTP {
sb.append('"'); sb.append('"');
sb.append(' '); sb.append(' ');
sb.append(jo.getString("HTTP-Version")); sb.append(jo.getString("HTTP-Version"));
} else { }
else {
throw new JSONException("Not enough material for an HTTP header."); throw new JSONException("Not enough material for an HTTP header.");
} }
sb.append(CRLF); sb.append(CRLF);
while (keys.hasNext()) { while (keys.hasNext()) {
string = keys.next(); string = keys.next();
if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) {
!"Reason-Phrase".equals(string) && !"Method".equals(string) &&
!"Request-URI".equals(string) && !jo.isNull(string)) {
sb.append(string); sb.append(string);
sb.append(": "); sb.append(": ");
sb.append(jo.getString(string)); sb.append(jo.getString(string));

View File

@ -1,31 +1,33 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* The HTTPTokener extends the JSONTokener to provide additional methods * The HTTPTokener extends the JSONTokener to provide additional methods
* for the parsing of HTTP headers. * for the parsing of HTTP headers.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
@ -33,26 +35,29 @@ public class HTTPTokener extends JSONTokener {
/** /**
* Construct an HTTPTokener from a string. * 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); super(string);
} }
/** /**
* Get the next token or string. This is used in parsing HTTP headers. * Get the next token or string. This is used in parsing HTTP headers.
*
* @throws JSONException * @throws JSONException
* @return A String. * @return A String.
*/ */
public String nextToken() throws JSONException { public String nextToken() throws JSONException {
char c; char c;
char q; char q;
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
do { do {
c = next(); c = next();
} while (Character.isWhitespace(c)); }
if (c == '"' || c == '\'') { while (Character.isWhitespace(c));
if ((c == '"') || (c == '\'')) {
q = c; q = c;
for (;;) { for (;;) {
c = next(); c = next();
@ -66,7 +71,7 @@ public class HTTPTokener extends JSONTokener {
} }
} }
for (;;) { for (;;) {
if (c == 0 || Character.isWhitespace(c)) { if ((c == 0) || Character.isWhitespace(c)) {
return sb.toString(); return sb.toString();
} }
sb.append(c); sb.append(c);

View File

@ -69,8 +69,8 @@ import java.util.Map;
* <li>Strings do not need to be quoted at all if they do not begin with a quote * <li>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 * or single quote, and if they do not contain leading or trailing spaces, and
* if they do not contain any of these characters: * if they do not contain any of these characters:
* <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and if
* if they are not the reserved words <code>true</code>, <code>false</code>, or * they are not the reserved words <code>true</code>, <code>false</code>, or
* <code>null</code>.</li> * <code>null</code>.</li>
* </ul> * </ul>
* *
@ -99,7 +99,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If there is a syntax error. * If there is a syntax error.
*/ */
public JSONArray(JSONTokener x) throws JSONException { public JSONArray(final JSONTokener x) throws JSONException {
this(); this();
if (x.nextClean() != '[') { if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['"); throw x.syntaxError("A JSONArray text must start with '['");
@ -110,7 +110,8 @@ public class JSONArray {
if (x.nextClean() == ',') { if (x.nextClean() == ',') {
x.back(); x.back();
this.myArrayList.add(JSONObject.NULL); this.myArrayList.add(JSONObject.NULL);
} else { }
else {
x.back(); x.back();
this.myArrayList.add(x.nextValue()); this.myArrayList.add(x.nextValue());
} }
@ -140,7 +141,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If there is a syntax error. * If there is a syntax error.
*/ */
public JSONArray(String source) throws JSONException { public JSONArray(final String source) throws JSONException {
this(new JSONTokener(source)); this(new JSONTokener(source));
} }
@ -150,10 +151,10 @@ public class JSONArray {
* @param collection * @param collection
* A Collection. * A Collection.
*/ */
public JSONArray(Collection<Object> collection) { public JSONArray(final Collection<Object> collection) {
this.myArrayList = new ArrayList<Object>(); this.myArrayList = new ArrayList<Object>();
if (collection != null) { if (collection != null) {
Iterator<Object> iter = collection.iterator(); final Iterator<Object> iter = collection.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next())); this.myArrayList.add(JSONObject.wrap(iter.next()));
} }
@ -166,16 +167,16 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If not an array. * If not an array.
*/ */
public JSONArray(Object array) throws JSONException { public JSONArray(final Object array) throws JSONException {
this(); this();
if (array.getClass().isArray()) { if (array.getClass().isArray()) {
int length = Array.getLength(array); final int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) { for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i))); this.put(JSONObject.wrap(Array.get(array, i)));
} }
} else { }
throw new JSONException( else {
"JSONArray initial value should be a string or collection or array."); throw new JSONException("JSONArray initial value should be a string or collection or array.");
} }
} }
@ -188,8 +189,8 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If there is no value for the index. * If there is no value for the index.
*/ */
public Object get(int index) throws JSONException { public Object get(final int index) throws JSONException {
Object object = this.opt(index); final Object object = this.opt(index);
if (object == null) { if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found."); 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 * If there is no value for the index or if the value is not
* convertible to boolean. * convertible to boolean.
*/ */
public boolean getBoolean(int index) throws JSONException { public boolean getBoolean(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
if (object.equals(Boolean.FALSE) if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) {
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false; return false;
} else if (object.equals(Boolean.TRUE) }
|| (object instanceof String && ((String) object) else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) {
.equalsIgnoreCase("true"))) {
return true; return true;
} }
throw new JSONException("JSONArray[" + index + "] is not a boolean."); 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 * If the key is not found or if the value cannot be converted
* to a number. * to a number.
*/ */
public double getDouble(int index) throws JSONException { public double getDouble(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
try { try {
return object instanceof Number ? ((Number) object).doubleValue() return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
: Double.parseDouble((String) object); }
} catch (Exception e) { catch (final Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number."); throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
} }
@ -250,12 +248,12 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the key is not found or if the value is not a number. * If the key is not found or if the value is not a number.
*/ */
public int getInt(int index) throws JSONException { public int getInt(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
try { try {
return object instanceof Number ? ((Number) object).intValue() return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
: Integer.parseInt((String) object); }
} catch (Exception e) { catch (final Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number."); 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 * If there is no value for the index. or if the value is not a
* JSONArray * JSONArray
*/ */
public JSONArray getJSONArray(int index) throws JSONException { public JSONArray getJSONArray(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
return (JSONArray) object; 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 * If there is no value for the index or if the value is not a
* JSONObject * JSONObject
*/ */
public JSONObject getJSONObject(int index) throws JSONException { public JSONObject getJSONObject(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
return (JSONObject) object; return (JSONObject) object;
} }
@ -306,12 +304,12 @@ public class JSONArray {
* If the key is not found or if the value cannot be converted * If the key is not found or if the value cannot be converted
* to a number. * to a number.
*/ */
public long getLong(int index) throws JSONException { public long getLong(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
try { try {
return object instanceof Number ? ((Number) object).longValue() return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
: Long.parseLong((String) object); }
} catch (Exception e) { catch (final Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number."); throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
} }
@ -325,8 +323,8 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If there is no string value for the index. * If there is no string value for the index.
*/ */
public String getString(int index) throws JSONException { public String getString(final int index) throws JSONException {
Object object = this.get(index); final Object object = this.get(index);
if (object instanceof String) { if (object instanceof String) {
return (String) object; return (String) object;
} }
@ -340,7 +338,7 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * 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. * @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)); return JSONObject.NULL.equals(this.opt(index));
} }
@ -355,9 +353,9 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the array contains an invalid number. * If the array contains an invalid number.
*/ */
public String join(String separator) throws JSONException { public String join(final String separator) throws JSONException {
int len = this.length(); final int len = this.length();
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) { for (int i = 0; i < len; i += 1) {
if (i > 0) { if (i > 0) {
@ -384,9 +382,8 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return An object value, or null if there is no object at that index. * @return An object value, or null if there is no object at that index.
*/ */
public Object opt(int index) { public Object opt(final int index) {
return (index < 0 || index >= this.length()) ? null : this.myArrayList return ((index < 0) || (index >= this.length())) ? null : this.myArrayList.get(index);
.get(index);
} }
/** /**
@ -398,7 +395,7 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return The truth. * @return The truth.
*/ */
public boolean optBoolean(int index) { public boolean optBoolean(final int index) {
return this.optBoolean(index, false); return this.optBoolean(index, false);
} }
@ -413,10 +410,11 @@ public class JSONArray {
* A boolean default. * A boolean default.
* @return The truth. * @return The truth.
*/ */
public boolean optBoolean(int index, boolean defaultValue) { public boolean optBoolean(final int index, final boolean defaultValue) {
try { try {
return this.getBoolean(index); return this.getBoolean(index);
} catch (Exception e) { }
catch (final Exception e) {
return defaultValue; return defaultValue;
} }
} }
@ -430,7 +428,7 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return The value. * @return The value.
*/ */
public double optDouble(int index) { public double optDouble(final int index) {
return this.optDouble(index, Double.NaN); return this.optDouble(index, Double.NaN);
} }
@ -445,10 +443,11 @@ public class JSONArray {
* The default value. * The default value.
* @return The value. * @return The value.
*/ */
public double optDouble(int index, double defaultValue) { public double optDouble(final int index, final double defaultValue) {
try { try {
return this.getDouble(index); return this.getDouble(index);
} catch (Exception e) { }
catch (final Exception e) {
return defaultValue; return defaultValue;
} }
} }
@ -462,7 +461,7 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return The value. * @return The value.
*/ */
public int optInt(int index) { public int optInt(final int index) {
return this.optInt(index, 0); return this.optInt(index, 0);
} }
@ -477,10 +476,11 @@ public class JSONArray {
* The default value. * The default value.
* @return The value. * @return The value.
*/ */
public int optInt(int index, int defaultValue) { public int optInt(final int index, final int defaultValue) {
try { try {
return this.getInt(index); return this.getInt(index);
} catch (Exception e) { }
catch (final Exception e) {
return defaultValue; return defaultValue;
} }
} }
@ -493,8 +493,8 @@ public class JSONArray {
* @return A JSONArray value, or null if the index has no value, or if the * @return A JSONArray value, or null if the index has no value, or if the
* value is not a JSONArray. * value is not a JSONArray.
*/ */
public JSONArray optJSONArray(int index) { public JSONArray optJSONArray(final int index) {
Object o = this.opt(index); final Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray) o : null; return o instanceof JSONArray ? (JSONArray) o : null;
} }
@ -507,8 +507,8 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return A JSONObject value. * @return A JSONObject value.
*/ */
public JSONObject optJSONObject(int index) { public JSONObject optJSONObject(final int index) {
Object o = this.opt(index); final Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject) o : null; return o instanceof JSONObject ? (JSONObject) o : null;
} }
@ -521,7 +521,7 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return The value. * @return The value.
*/ */
public long optLong(int index) { public long optLong(final int index) {
return this.optLong(index, 0); return this.optLong(index, 0);
} }
@ -536,10 +536,11 @@ public class JSONArray {
* The default value. * The default value.
* @return The value. * @return The value.
*/ */
public long optLong(int index, long defaultValue) { public long optLong(final int index, final long defaultValue) {
try { try {
return this.getLong(index); return this.getLong(index);
} catch (Exception e) { }
catch (final Exception e) {
return defaultValue; return defaultValue;
} }
} }
@ -553,7 +554,7 @@ public class JSONArray {
* The index must be between 0 and length() - 1. * The index must be between 0 and length() - 1.
* @return A String value. * @return A String value.
*/ */
public String optString(int index) { public String optString(final int index) {
return this.optString(index, ""); return this.optString(index, "");
} }
@ -567,10 +568,9 @@ public class JSONArray {
* The default value. * The default value.
* @return A String value. * @return A String value.
*/ */
public String optString(int index, String defaultValue) { public String optString(final int index, final String defaultValue) {
Object object = this.opt(index); final Object object = this.opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object return JSONObject.NULL.equals(object) ? defaultValue : object.toString();
.toString();
} }
/** /**
@ -580,7 +580,7 @@ public class JSONArray {
* A boolean value. * A boolean value.
* @return this. * @return this.
*/ */
public JSONArray put(boolean value) { public JSONArray put(final boolean value) {
this.put(value ? Boolean.TRUE : Boolean.FALSE); this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this; return this;
} }
@ -593,7 +593,7 @@ public class JSONArray {
* A Collection value. * A Collection value.
* @return this. * @return this.
*/ */
public JSONArray put(Collection<Object> value) { public JSONArray put(final Collection<Object> value) {
this.put(new JSONArray(value)); this.put(new JSONArray(value));
return this; return this;
} }
@ -607,8 +607,8 @@ public class JSONArray {
* if the value is not finite. * if the value is not finite.
* @return this. * @return this.
*/ */
public JSONArray put(double value) throws JSONException { public JSONArray put(final double value) throws JSONException {
Double d = new Double(value); final Double d = new Double(value);
JSONObject.testValidity(d); JSONObject.testValidity(d);
this.put(d); this.put(d);
return this; return this;
@ -621,7 +621,7 @@ public class JSONArray {
* An int value. * An int value.
* @return this. * @return this.
*/ */
public JSONArray put(int value) { public JSONArray put(final int value) {
this.put(new Integer(value)); this.put(new Integer(value));
return this; return this;
} }
@ -633,7 +633,7 @@ public class JSONArray {
* A long value. * A long value.
* @return this. * @return this.
*/ */
public JSONArray put(long value) { public JSONArray put(final long value) {
this.put(new Long(value)); this.put(new Long(value));
return this; return this;
} }
@ -646,7 +646,7 @@ public class JSONArray {
* A Map value. * A Map value.
* @return this. * @return this.
*/ */
public JSONArray put(Map<String, Object> value) { public JSONArray put(final Map<String, Object> value) {
this.put(new JSONObject(value)); this.put(new JSONObject(value));
return this; return this;
} }
@ -660,7 +660,7 @@ public class JSONArray {
* JSONObject.NULL object. * JSONObject.NULL object.
* @return this. * @return this.
*/ */
public JSONArray put(Object value) { public JSONArray put(final Object value) {
this.myArrayList.add(value); this.myArrayList.add(value);
return this; return this;
} }
@ -678,7 +678,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the index is negative. * 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); this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this; return this;
} }
@ -695,7 +695,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the index is negative or if the value is not finite. * If the index is negative or if the value is not finite.
*/ */
public JSONArray put(int index, Collection<Object> value) throws JSONException { public JSONArray put(final int index, final Collection<Object> value) throws JSONException {
this.put(index, new JSONArray(value)); this.put(index, new JSONArray(value));
return this; return this;
} }
@ -713,7 +713,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the index is negative or if the value is not finite. * 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)); this.put(index, new Double(value));
return this; return this;
} }
@ -731,7 +731,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the index is negative. * 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)); this.put(index, new Integer(value));
return this; return this;
} }
@ -749,7 +749,7 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If the index is negative. * 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)); this.put(index, new Long(value));
return this; return this;
} }
@ -767,7 +767,7 @@ public class JSONArray {
* If the index is negative or if the the value is an invalid * If the index is negative or if the the value is an invalid
* number. * number.
*/ */
public JSONArray put(int index, Map<String, Object> value) throws JSONException { public JSONArray put(final int index, final Map<String, Object> value) throws JSONException {
this.put(index, new JSONObject(value)); this.put(index, new JSONObject(value));
return this; return this;
} }
@ -788,14 +788,15 @@ public class JSONArray {
* If the index is negative or if the the value is an invalid * If the index is negative or if the the value is an invalid
* number. * number.
*/ */
public JSONArray put(int index, Object value) throws JSONException { public JSONArray put(final int index, final Object value) throws JSONException {
JSONObject.testValidity(value); JSONObject.testValidity(value);
if (index < 0) { if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found."); throw new JSONException("JSONArray[" + index + "] not found.");
} }
if (index < this.length()) { if (index < this.length()) {
this.myArrayList.set(index, value); this.myArrayList.set(index, value);
} else { }
else {
while (index != this.length()) { while (index != this.length()) {
this.put(JSONObject.NULL); this.put(JSONObject.NULL);
} }
@ -812,39 +813,40 @@ public class JSONArray {
* @return The value that was associated with the index, or null if there * @return The value that was associated with the index, or null if there
* was no value. * was no value.
*/ */
public Object remove(int index) { public Object remove(final int index) {
return index >= 0 && index < this.length() return (index >= 0) && (index < this.length()) ? this.myArrayList.remove(index) : null;
? this.myArrayList.remove(index)
: null;
} }
/** /**
* Determine if two JSONArrays are similar. * Determine if two JSONArrays are similar.
* They must contain similar sequences. * They must contain similar sequences.
* *
* @param other The other JSONArray * @param other
* The other JSONArray
* @return true if they are equal * @return true if they are equal
*/ */
public boolean similar(Object other) { public boolean similar(final Object other) {
if (!(other instanceof JSONArray)) { if (!(other instanceof JSONArray)) {
return false; return false;
} }
int len = this.length(); final int len = this.length();
if (len != ((JSONArray)other).length()) { if (len != ((JSONArray) other).length()) {
return false; return false;
} }
for (int i = 0; i < len; i += 1) { for (int i = 0; i < len; i += 1) {
Object valueThis = this.get(i); final Object valueThis = this.get(i);
Object valueOther = ((JSONArray)other).get(i); final Object valueOther = ((JSONArray) other).get(i);
if (valueThis instanceof JSONObject) { if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) { if (!((JSONObject) valueThis).similar(valueOther)) {
return false; return false;
} }
} else if (valueThis instanceof JSONArray) { }
if (!((JSONArray)valueThis).similar(valueOther)) { else if (valueThis instanceof JSONArray) {
if (!((JSONArray) valueThis).similar(valueOther)) {
return false; return false;
} }
} else if (!valueThis.equals(valueOther)) { }
else if (!valueThis.equals(valueOther)) {
return false; return false;
} }
} }
@ -863,11 +865,11 @@ public class JSONArray {
* @throws JSONException * @throws JSONException
* If any of the names are null. * If any of the names are null.
*/ */
public JSONObject toJSONObject(JSONArray names) throws JSONException { public JSONObject toJSONObject(final JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || this.length() == 0) { if ((names == null) || (names.length() == 0) || (this.length() == 0)) {
return null; return null;
} }
JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) { for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i)); jo.put(names.getString(i), this.opt(i));
} }
@ -885,10 +887,12 @@ public class JSONArray {
* @return a printable, displayable, transmittable representation of the * @return a printable, displayable, transmittable representation of the
* array. * array.
*/ */
@Override
public String toString() { public String toString() {
try { try {
return this.toString(0); return this.toString(0);
} catch (Exception e) { }
catch (final Exception e) {
return null; return null;
} }
} }
@ -905,8 +909,8 @@ public class JSONArray {
* &nbsp;<small>(right bracket)</small>. * &nbsp;<small>(right bracket)</small>.
* @throws JSONException * @throws JSONException
*/ */
public String toString(int indentFactor) throws JSONException { public String toString(final int indentFactor) throws JSONException {
StringWriter sw = new StringWriter(); final StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) { synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString(); return this.write(sw, indentFactor, 0).toString();
} }
@ -921,7 +925,7 @@ public class JSONArray {
* @return The writer. * @return The writer.
* @throws JSONException * @throws JSONException
*/ */
public Writer write(Writer writer) throws JSONException { public Writer write(final Writer writer) throws JSONException {
return this.write(writer, 0, 0); return this.write(writer, 0, 0);
} }
@ -938,17 +942,16 @@ public class JSONArray {
* @return The writer. * @return The writer.
* @throws JSONException * @throws JSONException
*/ */
Writer write(Writer writer, int indentFactor, int indent) Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
throws JSONException {
try { try {
boolean commanate = false; boolean commanate = false;
int length = this.length(); final int length = this.length();
writer.write('['); writer.write('[');
if (length == 1) { if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0), JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent);
indentFactor, indent); }
} else if (length != 0) { else if (length != 0) {
final int newindent = indent + indentFactor; final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) { for (int i = 0; i < length; i += 1) {
@ -959,8 +962,7 @@ public class JSONArray {
writer.write('\n'); writer.write('\n');
} }
JSONObject.indent(writer, newindent); JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i), JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent);
indentFactor, newindent);
commanate = true; commanate = true;
} }
if (indentFactor > 0) { if (indentFactor > 0) {
@ -970,7 +972,8 @@ public class JSONArray {
} }
writer.write(']'); writer.write(']');
return writer; return writer;
} catch (IOException e) { }
catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
} }

View File

@ -1,4 +1,5 @@
package com.intellectualcrafters.json; package com.intellectualcrafters.json;
/** /**
* The JSONException is thrown by the JSON.org classes when things are amiss. * The JSONException is thrown by the JSON.org classes when things are amiss.
* *
@ -15,15 +16,17 @@ public class JSONException extends RuntimeException {
* @param message * @param message
* Detail about the reason for the exception. * Detail about the reason for the exception.
*/ */
public JSONException(String message) { public JSONException(final String message) {
super(message); super(message);
} }
/** /**
* Constructs a new JSONException with the specified cause. * 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()); super(cause.getMessage());
this.cause = cause; this.cause = cause;
} }

View File

@ -1,32 +1,31 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.util.Iterator; import java.util.Iterator;
/** /**
* This provides static methods to convert an XML text into a JSONArray or * 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 * JSONObject, and to covert a JSONArray or JSONObject into an XML text using
@ -39,18 +38,18 @@ public class JSONML {
/** /**
* Parse XML values and store them in a JSONArray. * 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 x
* @param ja The JSONArray that is containing the current tag or null * 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. * if we are at the outermost level.
* @return A JSONArray if the value is the outermost tag, otherwise null. * @return A JSONArray if the value is the outermost tag, otherwise null.
* @throws JSONException * @throws JSONException
*/ */
private static Object parse( private static Object parse(final XMLTokener x, final boolean arrayForm, final JSONArray ja) throws JSONException {
XMLTokener x,
boolean arrayForm,
JSONArray ja
) throws JSONException {
String attribute; String attribute;
char c; char c;
String closeTag = null; String closeTag = null;
@ -60,11 +59,11 @@ public class JSONML {
Object token; Object token;
String tagName = null; String tagName = null;
// Test for and skip past these forms: // Test for and skip past these forms:
// <!-- ... --> // <!-- ... -->
// <![ ... ]]> // <![ ... ]]>
// <! ... > // <! ... >
// <? ... ?> // <? ... ?>
while (true) { while (true) {
if (!x.more()) { if (!x.more()) {
@ -76,67 +75,76 @@ public class JSONML {
if (token instanceof Character) { if (token instanceof Character) {
if (token == XML.SLASH) { if (token == XML.SLASH) {
// Close tag </ // Close tag </
token = x.nextToken(); token = x.nextToken();
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw new JSONException( throw new JSONException("Expected a closing name instead of '" + token + "'.");
"Expected a closing name instead of '" +
token + "'.");
} }
if (x.nextToken() != XML.GT) { if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped close tag"); throw x.syntaxError("Misshaped close tag");
} }
return token; return token;
} else if (token == XML.BANG) { }
else if (token == XML.BANG) {
// <! // <!
c = x.next(); c = x.next();
if (c == '-') { if (c == '-') {
if (x.next() == '-') { if (x.next() == '-') {
x.skipPast("-->"); x.skipPast("-->");
} else { }
else {
x.back(); x.back();
} }
} else if (c == '[') { }
else if (c == '[') {
token = x.nextToken(); token = x.nextToken();
if (token.equals("CDATA") && x.next() == '[') { if (token.equals("CDATA") && (x.next() == '[')) {
if (ja != null) { if (ja != null) {
ja.put(x.nextCDATA()); ja.put(x.nextCDATA());
} }
} else { }
else {
throw x.syntaxError("Expected 'CDATA['"); throw x.syntaxError("Expected 'CDATA['");
} }
} else { }
else {
i = 1; i = 1;
do { do {
token = x.nextMeta(); token = x.nextMeta();
if (token == null) { if (token == null) {
throw x.syntaxError("Missing '>' after '<!'."); throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == XML.LT) { }
else if (token == XML.LT) {
i += 1; i += 1;
} else if (token == XML.GT) { }
else if (token == XML.GT) {
i -= 1; i -= 1;
} }
} while (i > 0);
} }
} else if (token == XML.QUEST) { while (i > 0);
}
}
else if (token == XML.QUEST) {
// <? // <?
x.skipPast("?>"); x.skipPast("?>");
} else { }
else {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
// Open tag < // Open tag <
} else { }
else {
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw x.syntaxError("Bad tagName '" + token + "'."); throw x.syntaxError("Bad tagName '" + token + "'.");
} }
tagName = (String)token; tagName = (String) token;
newja = new JSONArray(); newja = new JSONArray();
newjo = new JSONObject(); newjo = new JSONObject();
if (arrayForm) { if (arrayForm) {
@ -144,7 +152,8 @@ public class JSONML {
if (ja != null) { if (ja != null) {
ja.put(newja); ja.put(newja);
} }
} else { }
else {
newjo.put("tagName", tagName); newjo.put("tagName", tagName);
if (ja != null) { if (ja != null) {
ja.put(newjo); ja.put(newjo);
@ -162,9 +171,9 @@ public class JSONML {
break; break;
} }
// attribute = value // attribute = value
attribute = (String)token; attribute = (String) token;
if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
throw x.syntaxError("Reserved attribute."); throw x.syntaxError("Reserved attribute.");
} }
@ -174,17 +183,18 @@ public class JSONML {
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw x.syntaxError("Missing value"); throw x.syntaxError("Missing value");
} }
newjo.accumulate(attribute, XML.stringToValue((String)token)); newjo.accumulate(attribute, XML.stringToValue((String) token));
token = null; token = null;
} else { }
else {
newjo.accumulate(attribute, ""); newjo.accumulate(attribute, "");
} }
} }
if (arrayForm && newjo.length() > 0) { if (arrayForm && (newjo.length() > 0)) {
newja.put(newjo); newja.put(newjo);
} }
// Empty tag <.../> // Empty tag <.../>
if (token == XML.SLASH) { if (token == XML.SLASH) {
if (x.nextToken() != XML.GT) { if (x.nextToken() != XML.GT) {
@ -193,48 +203,48 @@ public class JSONML {
if (ja == null) { if (ja == null) {
if (arrayForm) { if (arrayForm) {
return newja; return newja;
} else { }
else {
return newjo; return newjo;
} }
} }
// Content, between <...> and </...> // Content, between <...> and </...>
} else { }
else {
if (token != XML.GT) { if (token != XML.GT) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
closeTag = (String)parse(x, arrayForm, newja); closeTag = (String) parse(x, arrayForm, newja);
if (closeTag != null) { if (closeTag != null) {
if (!closeTag.equals(tagName)) { if (!closeTag.equals(tagName)) {
throw x.syntaxError("Mismatched '" + tagName + throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'");
"' and '" + closeTag + "'");
} }
tagName = null; tagName = null;
if (!arrayForm && newja.length() > 0) { if (!arrayForm && (newja.length() > 0)) {
newjo.put("childNodes", newja); newjo.put("childNodes", newja);
} }
if (ja == null) { if (ja == null) {
if (arrayForm) { if (arrayForm) {
return newja; return newja;
} else { }
else {
return newjo; return newjo;
} }
} }
} }
} }
} }
} else { }
else {
if (ja != null) { if (ja != null) {
ja.put(token instanceof String ja.put(token instanceof String ? XML.stringToValue((String) token) : token);
? XML.stringToValue((String)token)
: token);
} }
} }
} }
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as * 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 * name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child tags. * JSONArrays will represent the child tags.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* @param string The source string. *
* @param string
* The source string.
* @return A JSONArray containing the structured data from the XML string. * @return A JSONArray containing the structured data from the XML string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(String string) throws JSONException { public static JSONArray toJSONArray(final String string) throws JSONException {
return toJSONArray(new XMLTokener(string)); return toJSONArray(new XMLTokener(string));
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as * 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 * name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child content and tags. * JSONArrays will represent the child content and tags.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* @param x An XMLTokener. *
* @param x
* An XMLTokener.
* @return A JSONArray containing the structured data from the XML string. * @return A JSONArray containing the structured data from the XML string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(XMLTokener x) throws JSONException { public static JSONArray toJSONArray(final XMLTokener x) throws JSONException {
return (JSONArray)parse(x, true, null); return (JSONArray) parse(x, true, null);
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as * 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 * the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which * contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects. * will be an array of strings and JsonML JSONObjects.
*
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> 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. * @return A JSONObject containing the structured data from the XML string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(XMLTokener x) throws JSONException { public static JSONObject toJSONObject(final XMLTokener x) throws JSONException {
return (JSONObject)parse(x, false, null); return (JSONObject) parse(x, false, null);
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as * 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 * the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which * contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects. * will be an array of strings and JsonML JSONObjects.
*
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> 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. * @return A JSONObject containing the structured data from the XML string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
return toJSONObject(new XMLTokener(string)); return toJSONObject(new XMLTokener(string));
} }
/** /**
* Reverse the JSONML transformation, making an XML text from a JSONArray. * Reverse the JSONML transformation, making an XML text from a JSONArray.
* @param ja A JSONArray. *
* @param ja
* A JSONArray.
* @return An XML string. * @return An XML string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONArray ja) throws JSONException { public static String toString(final JSONArray ja) throws JSONException {
int i; int i;
JSONObject jo; JSONObject jo;
String key; String key;
Iterator<String> keys; Iterator<String> keys;
int length; int length;
Object object; Object object;
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
String tagName; String tagName;
String value; String value;
// Emit <tagName // Emit <tagName
tagName = ja.getString(0); tagName = ja.getString(0);
XML.noSpace(tagName); XML.noSpace(tagName);
@ -333,9 +349,9 @@ public class JSONML {
object = ja.opt(1); object = ja.opt(1);
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
i = 2; i = 2;
jo = (JSONObject)object; jo = (JSONObject) object;
// Emit the attributes // Emit the attributes
keys = jo.keys(); keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
@ -351,17 +367,19 @@ public class JSONML {
sb.append('"'); sb.append('"');
} }
} }
} else { }
else {
i = 1; i = 1;
} }
// Emit content in body // Emit content in body
length = ja.length(); length = ja.length();
if (i >= length) { if (i >= length) {
sb.append('/'); sb.append('/');
sb.append('>'); sb.append('>');
} else { }
else {
sb.append('>'); sb.append('>');
do { do {
object = ja.get(i); object = ja.get(i);
@ -369,13 +387,16 @@ public class JSONML {
if (object != null) { if (object != null) {
if (object instanceof String) { if (object instanceof String) {
sb.append(XML.escape(object.toString())); sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) { }
sb.append(toString((JSONObject)object)); else if (object instanceof JSONObject) {
} else if (object instanceof JSONArray) { sb.append(toString((JSONObject) object));
sb.append(toString((JSONArray)object)); }
else if (object instanceof JSONArray) {
sb.append(toString((JSONArray) object));
} }
} }
} while (i < length); }
while (i < length);
sb.append('<'); sb.append('<');
sb.append('/'); sb.append('/');
sb.append(tagName); sb.append(tagName);
@ -389,12 +410,14 @@ public class JSONML {
* The JSONObject must contain a "tagName" property. If it has children, * The JSONObject must contain a "tagName" property. If it has children,
* then it must have a "childNodes" property containing an array of objects. * then it must have a "childNodes" property containing an array of objects.
* The other properties are attributes with string values. * The other properties are attributes with string values.
* @param jo A JSONObject. *
* @param jo
* A JSONObject.
* @return An XML string. * @return An XML string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(final JSONObject jo) throws JSONException {
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
int i; int i;
JSONArray ja; JSONArray ja;
String key; String key;
@ -404,7 +427,7 @@ public class JSONML {
String tagName; String tagName;
String value; String value;
//Emit <tagName // Emit <tagName
tagName = jo.optString("tagName"); tagName = jo.optString("tagName");
if (tagName == null) { if (tagName == null) {
@ -415,7 +438,7 @@ public class JSONML {
sb.append('<'); sb.append('<');
sb.append(tagName); sb.append(tagName);
//Emit the attributes // Emit the attributes
keys = jo.keys(); keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
@ -434,13 +457,14 @@ public class JSONML {
} }
} }
//Emit content in body // Emit content in body
ja = jo.optJSONArray("childNodes"); ja = jo.optJSONArray("childNodes");
if (ja == null) { if (ja == null) {
sb.append('/'); sb.append('/');
sb.append('>'); sb.append('>');
} else { }
else {
sb.append('>'); sb.append('>');
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
@ -448,11 +472,14 @@ public class JSONML {
if (object != null) { if (object != null) {
if (object instanceof String) { if (object instanceof String) {
sb.append(XML.escape(object.toString())); sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) { }
sb.append(toString((JSONObject)object)); else if (object instanceof JSONObject) {
} else if (object instanceof JSONArray) { sb.append(toString((JSONObject) object));
sb.append(toString((JSONArray)object)); }
} else { else if (object instanceof JSONArray) {
sb.append(toString((JSONArray) object));
}
else {
sb.append(object.toString()); sb.append(object.toString());
} }
} }

View File

@ -1,4 +1,5 @@
package com.intellectualcrafters.json; package com.intellectualcrafters.json;
/** /**
* The <code>JSONString</code> interface allows a <code>toJSONString()</code> * The <code>JSONString</code> interface allows a <code>toJSONString()</code>
* method so that a class can change the behavior of * method so that a class can change the behavior of
@ -9,7 +10,8 @@ package com.intellectualcrafters.json;
*/ */
public interface JSONString { public interface JSONString {
/** /**
* The <code>toJSONString</code> method allows a class to produce its own JSON * The <code>toJSONString</code> method allows a class to produce its own
* JSON
* serialization. * serialization.
* *
* @return A strictly syntactically correct JSON text. * @return A strictly syntactically correct JSON text.

View File

@ -1,28 +1,28 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.io.StringWriter; import java.io.StringWriter;
@ -33,26 +33,29 @@ import java.io.StringWriter;
* JSONStringer can produce one JSON text. * JSONStringer can produce one JSON text.
* <p> * <p>
* A JSONStringer instance provides a <code>value</code> method for appending * A JSONStringer instance provides a <code>value</code> method for appending
* values to the * values to the text, and a <code>key</code> method for adding keys before
* text, and a <code>key</code> * values in objects. There are <code>array</code> and <code>endArray</code>
* method for adding keys before values in objects. There are <code>array</code> * methods that make and bound array values, and <code>object</code> and
* and <code>endArray</code> methods that make and bound array values, and * <code>endObject</code> methods which make and bound object values. All of
* <code>object</code> and <code>endObject</code> methods which make and bound * these methods return the JSONWriter instance, permitting cascade style. For
* object values. All of these methods return the JSONWriter instance, * example,
* permitting cascade style. For example, <pre> *
* myString = new JSONStringer() * <pre>
* .object() * myString = new JSONStringer().object().key(&quot;JSON&quot;).value(&quot;Hello, World!&quot;).endObject().toString();
* .key("JSON") * </pre>
* .value("Hello, World!") *
* .endObject() * which produces the string
* .toString();</pre> which produces the string <pre> *
* {"JSON":"Hello, World!"}</pre> * <pre>
* {"JSON":"Hello, World!"}
* </pre>
* <p> * <p>
* The first method called must be <code>array</code> or <code>object</code>. * The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONStringer adds them for * 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. * you. Objects and arrays can be nested up to 20 levels deep.
* <p> * <p>
* This can sometimes be easier than using a JSONObject to build a string. * This can sometimes be easier than using a JSONObject to build a string.
*
* @author JSON.org * @author JSON.org
* @version 2008-09-18 * @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 * problem in the construction of the JSON text (such as the calls to
* <code>array</code> were not properly balanced with calls to * <code>array</code> were not properly balanced with calls to
* <code>endArray</code>). * <code>endArray</code>).
*
* @return The JSON text. * @return The JSON text.
*/ */
@Override
public String toString() { public String toString() {
return this.mode == 'd' ? this.writer.toString() : null; return this.mode == 'd' ? this.writer.toString() : null;
} }

View File

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

View File

@ -1,30 +1,31 @@
package com.intellectualcrafters.json; package com.intellectualcrafters.json;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* JSONWriter provides a quick and convenient way of producing JSON text. * JSONWriter provides a quick and convenient way of producing JSON text.
@ -33,25 +34,29 @@ SOFTWARE.
* JSONWriter can produce one JSON text. * JSONWriter can produce one JSON text.
* <p> * <p>
* A JSONWriter instance provides a <code>value</code> method for appending * A JSONWriter instance provides a <code>value</code> method for appending
* values to the * values to the text, and a <code>key</code> method for adding keys before
* text, and a <code>key</code> * values in objects. There are <code>array</code> and <code>endArray</code>
* method for adding keys before values in objects. There are <code>array</code> * methods that make and bound array values, and <code>object</code> and
* and <code>endArray</code> methods that make and bound array values, and * <code>endObject</code> methods which make and bound object values. All of
* <code>object</code> and <code>endObject</code> methods which make and bound * these methods return the JSONWriter instance, permitting a cascade style. For
* object values. All of these methods return the JSONWriter instance, * example,
* permitting a cascade style. For example, <pre> *
* new JSONWriter(myWriter) * <pre>
* .object() * new JSONWriter(myWriter).object().key(&quot;JSON&quot;).value(&quot;Hello, World!&quot;).endObject();
* .key("JSON") * </pre>
* .value("Hello, World!") *
* .endObject();</pre> which writes <pre> * which writes
* {"JSON":"Hello, World!"}</pre> *
* <pre>
* {"JSON":"Hello, World!"}
* </pre>
* <p> * <p>
* The first method called must be <code>array</code> or <code>object</code>. * The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONWriter adds them for * 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. * you. Objects and arrays can be nested up to 20 levels deep.
* <p> * <p>
* This can sometimes be easier than using a JSONObject to build a string. * This can sometimes be easier than using a JSONObject to build a string.
*
* @author JSON.org * @author JSON.org
* @version 2011-11-24 * @version 2011-11-24
*/ */
@ -92,7 +97,7 @@ public class JSONWriter {
/** /**
* Make a fresh JSONWriter. It can be used to build one JSON text. * 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.comma = false;
this.mode = 'i'; this.mode = 'i';
this.stack = new JSONObject[maxdepth]; this.stack = new JSONObject[maxdepth];
@ -102,21 +107,25 @@ public class JSONWriter {
/** /**
* Append a value. * Append a value.
* @param string A string value. *
* @param string
* A string value.
* @return this * @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) { if (string == null) {
throw new JSONException("Null pointer"); throw new JSONException("Null pointer");
} }
if (this.mode == 'o' || this.mode == 'a') { if ((this.mode == 'o') || (this.mode == 'a')) {
try { try {
if (this.comma && this.mode == 'a') { if (this.comma && (this.mode == 'a')) {
this.writer.write(','); this.writer.write(',');
} }
this.writer.write(string); this.writer.write(string);
} catch (IOException e) { }
catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
if (this.mode == 'o') { if (this.mode == 'o') {
@ -132,13 +141,16 @@ public class JSONWriter {
* Begin appending a new array. All values until the balancing * Begin appending a new array. All values until the balancing
* <code>endArray</code> will be appended to this array. The * <code>endArray</code> will be appended to this array. The
* <code>endArray</code> method must be called to mark the array's end. * <code>endArray</code> method must be called to mark the array's end.
*
* @return this * @return this
* @throws JSONException If the nesting is too deep, or if the object is * @throws JSONException
* started in the wrong place (for example as a key or after the end of the * 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). * outermost array or object).
*/ */
public JSONWriter array() throws JSONException { 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.push(null);
this.append("["); this.append("[");
this.comma = false; this.comma = false;
@ -149,21 +161,24 @@ public class JSONWriter {
/** /**
* End something. * End something.
* @param mode Mode *
* @param c Closing character * @param mode
* Mode
* @param c
* Closing character
* @return this * @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) { if (this.mode != mode) {
throw new JSONException(mode == 'a' throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject.");
? "Misplaced endArray."
: "Misplaced endObject.");
} }
this.pop(mode); this.pop(mode);
try { try {
this.writer.write(c); this.writer.write(c);
} catch (IOException e) { }
catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
this.comma = true; this.comma = true;
@ -173,8 +188,10 @@ public class JSONWriter {
/** /**
* End an array. This method most be called to balance calls to * End an array. This method most be called to balance calls to
* <code>array</code>. * <code>array</code>.
*
* @return this * @return this
* @throws JSONException If incorrectly nested. * @throws JSONException
* If incorrectly nested.
*/ */
public JSONWriter endArray() throws JSONException { public JSONWriter endArray() throws JSONException {
return this.end('a', ']'); return this.end('a', ']');
@ -183,8 +200,10 @@ public class JSONWriter {
/** /**
* End an object. This method most be called to balance calls to * End an object. This method most be called to balance calls to
* <code>object</code>. * <code>object</code>.
*
* @return this * @return this
* @throws JSONException If incorrectly nested. * @throws JSONException
* If incorrectly nested.
*/ */
public JSONWriter endObject() throws JSONException { public JSONWriter endObject() throws JSONException {
return this.end('k', '}'); 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 * Append a key. The key will be associated with the next value. In an
* object, every value must be preceded by a key. * object, every value must be preceded by a key.
* @param string A key string. *
* @param string
* A key string.
* @return this * @return this
* @throws JSONException If the key is out of place. For example, keys * @throws JSONException
* If the key is out of place. For example, keys
* do not belong in arrays or if the key is null. * 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) { if (string == null) {
throw new JSONException("Null key."); throw new JSONException("Null key.");
} }
@ -213,28 +235,31 @@ public class JSONWriter {
this.comma = false; this.comma = false;
this.mode = 'o'; this.mode = 'o';
return this; return this;
} catch (IOException e) { }
catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
} }
throw new JSONException("Misplaced key."); throw new JSONException("Misplaced key.");
} }
/** /**
* Begin appending a new object. All keys and values until the balancing * Begin appending a new object. All keys and values until the balancing
* <code>endObject</code> will be appended to this object. The * <code>endObject</code> will be appended to this object. The
* <code>endObject</code> method must be called to mark the object's end. * <code>endObject</code> method must be called to mark the object's end.
*
* @return this * @return this
* @throws JSONException If the nesting is too deep, or if the object is * @throws JSONException
* started in the wrong place (for example as a key or after the end of the * 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). * outermost array or object).
*/ */
public JSONWriter object() throws JSONException { public JSONWriter object() throws JSONException {
if (this.mode == 'i') { if (this.mode == 'i') {
this.mode = 'o'; this.mode = 'o';
} }
if (this.mode == 'o' || this.mode == 'a') { if ((this.mode == 'o') || (this.mode == 'a')) {
this.append("{"); this.append("{");
this.push(new JSONObject()); this.push(new JSONObject());
this.comma = false; this.comma = false;
@ -244,34 +269,35 @@ public class JSONWriter {
} }
/** /**
* Pop an array or object scope. * 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) { if (this.top <= 0) {
throw new JSONException("Nesting error."); 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) { if (m != c) {
throw new JSONException("Nesting error."); throw new JSONException("Nesting error.");
} }
this.top -= 1; this.top -= 1;
this.mode = this.top == 0 this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
} }
/** /**
* Push an array or object scope. * 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) { if (this.top >= maxdepth) {
throw new JSONException("Nesting too deep."); throw new JSONException("Nesting too deep.");
} }
@ -280,47 +306,56 @@ public class JSONWriter {
this.top += 1; this.top += 1;
} }
/** /**
* Append either the value <code>true</code> or the value * Append either the value <code>true</code> or the value <code>false</code>
* <code>false</code>. * .
* @param b A boolean. *
* @param b
* A boolean.
* @return this * @return this
* @throws JSONException * @throws JSONException
*/ */
public JSONWriter value(boolean b) throws JSONException { public JSONWriter value(final boolean b) throws JSONException {
return this.append(b ? "true" : "false"); return this.append(b ? "true" : "false");
} }
/** /**
* Append a double value. * Append a double value.
* @param d A double. *
* @param d
* A double.
* @return this * @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)); return this.value(new Double(d));
} }
/** /**
* Append a long value. * Append a long value.
* @param l A long. *
* @param l
* A long.
* @return this * @return this
* @throws JSONException * @throws JSONException
*/ */
public JSONWriter value(long l) throws JSONException { public JSONWriter value(final long l) throws JSONException {
return this.append(Long.toString(l)); return this.append(Long.toString(l));
} }
/** /**
* Append an object value. * 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 * @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)); return this.append(JSONObject.valueToString(object));
} }
} }

View File

@ -93,10 +93,11 @@ public class Kim {
* @param thru * @param thru
* The index of the last byte plus one. * 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 // As the bytes are copied into the new kim, a hashcode is computed
// modified Fletcher code. // using a
// modified Fletcher code.
int sum = 1; int sum = 1;
int value; int value;
@ -105,7 +106,7 @@ public class Kim {
if (this.length > 0) { if (this.length > 0) {
this.bytes = new byte[this.length]; this.bytes = new byte[this.length];
for (int at = 0; at < this.length; at += 1) { for (int at = 0; at < this.length; at += 1) {
value = (int) bytes[at + from] & 0xFF; value = bytes[at + from] & 0xFF;
sum += value; sum += value;
this.hashcode += sum; this.hashcode += sum;
this.bytes[at] = (byte) value; this.bytes[at] = (byte) value;
@ -122,7 +123,7 @@ public class Kim {
* @param length * @param length
* The number of bytes. * The number of bytes.
*/ */
public Kim(byte[] bytes, int length) { public Kim(final byte[] bytes, final int length) {
this(bytes, 0, length); this(bytes, 0, length);
} }
@ -137,7 +138,7 @@ public class Kim {
* @param thru * @param thru
* The point at which to stop taking bytes. * 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); this(kim.bytes, from, thru);
} }
@ -149,26 +150,28 @@ public class Kim {
* @throws JSONException * @throws JSONException
* if surrogate pair mismatch. * if surrogate pair mismatch.
*/ */
public Kim(String string) throws JSONException { public Kim(final String string) throws JSONException {
int stringLength = string.length(); final int stringLength = string.length();
this.hashcode = 0; this.hashcode = 0;
this.length = 0; this.length = 0;
// First pass: Determine the length of the kim, allowing for the UTF-16 // 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. // to UTF-32 conversion, and then the UTF-32 to Kim conversion.
if (stringLength > 0) { if (stringLength > 0) {
for (int i = 0; i < stringLength; i += 1) { for (int i = 0; i < stringLength; i += 1) {
int c = string.charAt(i); final int c = string.charAt(i);
if (c <= 0x7F) { if (c <= 0x7F) {
this.length += 1; this.length += 1;
} else if (c <= 0x3FFF) { }
else if (c <= 0x3FFF) {
this.length += 2; this.length += 2;
} else { }
if (c >= 0xD800 && c <= 0xDFFF) { else {
if ((c >= 0xD800) && (c <= 0xDFFF)) {
i += 1; i += 1;
int d = string.charAt(i); final int d = string.charAt(i);
if (c > 0xDBFF || d < 0xDC00 || d > 0xDFFF) { if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) {
throw new JSONException("Bad UTF16"); 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 // Second pass: Allocate a byte array and fill that array with the
// while computing the hashcode. // conversion
// while computing the hashcode.
this.bytes = new byte[length]; this.bytes = new byte[this.length];
int at = 0; int at = 0;
int b; int b;
int sum = 1; int sum = 1;
for (int i = 0; i < stringLength; i += 1) { for (int i = 0; i < stringLength; i += 1) {
int character = string.charAt(i); int character = string.charAt(i);
if (character <= 0x7F) { if (character <= 0x7F) {
bytes[at] = (byte) character; this.bytes[at] = (byte) character;
sum += character; sum += character;
this.hashcode += sum; this.hashcode += sum;
at += 1; at += 1;
} else if (character <= 0x3FFF) { }
else if (character <= 0x3FFF) {
b = 0x80 | (character >>> 7); b = 0x80 | (character >>> 7);
bytes[at] = (byte) b; this.bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; this.hashcode += sum;
at += 1; at += 1;
b = character & 0x7F; b = character & 0x7F;
bytes[at] = (byte) b; this.bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; this.hashcode += sum;
at += 1; at += 1;
} else { }
if (character >= 0xD800 && character <= 0xDBFF) { else {
if ((character >= 0xD800) && (character <= 0xDBFF)) {
i += 1; i += 1;
character = (((character & 0x3FF) << 10) | (string character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536;
.charAt(i) & 0x3FF)) + 65536;
} }
b = 0x80 | (character >>> 14); b = 0x80 | (character >>> 14);
bytes[at] = (byte) b; this.bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; this.hashcode += sum;
at += 1; at += 1;
b = 0x80 | ((character >>> 7) & 0xFF); b = 0x80 | ((character >>> 7) & 0xFF);
bytes[at] = (byte) b; this.bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; this.hashcode += sum;
at += 1; at += 1;
b = character & 0x7F; b = character & 0x7F;
bytes[at] = (byte) b; this.bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; this.hashcode += sum;
at += 1; at += 1;
@ -239,23 +244,23 @@ public class Kim {
* @throws JSONException * @throws JSONException
* if at does not point to a valid character. * if at does not point to a valid character.
*/ */
public int characterAt(int at) throws JSONException { public int characterAt(final int at) throws JSONException {
int c = get(at); final int c = get(at);
if ((c & 0x80) == 0) { if ((c & 0x80) == 0) {
return c; return c;
} }
int character; int character;
int c1 = get(at + 1); final int c1 = get(at + 1);
if ((c1 & 0x80) == 0) { if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1; character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) { if (character > 0x7F) {
return character; return character;
} }
} else { }
int c2 = get(at + 2); else {
final int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) {
&& (character < 0xD800 || character > 0xDFFF)) {
return character; return character;
} }
} }
@ -272,8 +277,8 @@ public class Kim {
* @throws JSONException * @throws JSONException
* if the character is not representable in a kim. * if the character is not representable in a kim.
*/ */
public static int characterSize(int character) throws JSONException { public static int characterSize(final int character) throws JSONException {
if (character < 0 || character > 0x10FFFF) { if ((character < 0) || (character > 0x10FFFF)) {
throw new JSONException("Bad character " + character); throw new JSONException("Bad character " + character);
} }
return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; 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. * The position within the byte array to take the byes.
* @return The position immediately after the copy. * @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); System.arraycopy(this.bytes, 0, bytes, at, this.length);
return 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 * @returns true if this and obj are both kim objects containing identical
* byte sequences. * byte sequences.
*/ */
public boolean equals(Object obj) { @Override
public boolean equals(final Object obj) {
if (!(obj instanceof Kim)) { if (!(obj instanceof Kim)) {
return false; return false;
} }
Kim that = (Kim) obj; final Kim that = (Kim) obj;
if (this == that) { if (this == that) {
return true; return true;
} }
@ -318,22 +324,24 @@ public class Kim {
/** /**
* Get a byte from a kim. * Get a byte from a kim.
*
* @param at * @param at
* The position of the byte. The first byte is at 0. * The position of the byte. The first byte is at 0.
* @return The byte. * @return The byte.
* @throws JSONException * @throws JSONException
* if there is no byte at that position. * if there is no byte at that position.
*/ */
public int get(int at) throws JSONException { public int get(final int at) throws JSONException {
if (at < 0 || at > this.length) { if ((at < 0) || (at > this.length)) {
throw new JSONException("Bad character at " + at); 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. * Returns a hash code value for the kim.
*/ */
@Override
public int hashCode() { public int hashCode() {
return this.hashcode; return this.hashcode;
} }
@ -347,17 +355,19 @@ public class Kim {
* @throws JSONException * @throws JSONException
* if the kim is not valid. * if the kim is not valid.
*/ */
@Override
public String toString() throws JSONException { public String toString() throws JSONException {
if (this.string == null) { if (this.string == null) {
int c; int c;
int length = 0; 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)) { for (int at = 0; at < this.length; at += characterSize(c)) {
c = this.characterAt(at); c = this.characterAt(at);
if (c < 0x10000) { if (c < 0x10000) {
chars[length] = (char) c; chars[length] = (char) c;
length += 1; length += 1;
} else { }
else {
chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10)); chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10));
length += 1; length += 1;
chars[length] = (char) (0xDC00 | (c & 0x03FF)); chars[length] = (char) (0xDC00 | (c & 0x03FF));

View File

@ -1,28 +1,28 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
@ -30,22 +30,26 @@ import java.util.Properties;
/** /**
* Converts a Property file data into JSONObject and back. * Converts a Property file data into JSONObject and back.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
public class Property { public class Property {
/** /**
* Converts a property file object into a JSONObject. The property file object is a table of name value pairs. * Converts a property file object into a JSONObject. The property file
* @param properties java.util.Properties * object is a table of name value pairs.
*
* @param properties
* java.util.Properties
* @return JSONObject * @return JSONObject
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException {
JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
if (properties != null && !properties.isEmpty()) { if ((properties != null) && !properties.isEmpty()) {
Enumeration enumProperties = properties.propertyNames(); final Enumeration enumProperties = properties.propertyNames();
while(enumProperties.hasMoreElements()) { while (enumProperties.hasMoreElements()) {
String name = (String)enumProperties.nextElement(); final String name = (String) enumProperties.nextElement();
jo.put(name, properties.getProperty(name)); jo.put(name, properties.getProperty(name));
} }
} }
@ -54,16 +58,18 @@ public class Property {
/** /**
* Converts the JSONObject into a property file object. * Converts the JSONObject into a property file object.
* @param jo JSONObject *
* @param jo
* JSONObject
* @return java.util.Properties * @return java.util.Properties
* @throws JSONException * @throws JSONException
*/ */
public static Properties toProperties(JSONObject jo) throws JSONException { public static Properties toProperties(final JSONObject jo) throws JSONException {
Properties properties = new Properties(); final Properties properties = new Properties();
if (jo != null) { if (jo != null) {
Iterator<String> keys = jo.keys(); final Iterator<String> keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
String name = keys.next(); final String name = keys.next();
properties.put(name, jo.getString(name)); properties.put(name, jo.getString(name));
} }
} }

View File

@ -1,34 +1,35 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.util.Iterator; import java.util.Iterator;
/** /**
* This provides static methods to convert an XML text into a JSONObject, * This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text. * and to covert a JSONObject into an XML text.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
@ -63,19 +64,22 @@ public class XML {
/** /**
* Replace special characters with XML escapes: * Replace special characters with XML escapes:
*
* <pre> * <pre>
* &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &amp; <small>(ampersand)</small> is replaced by &amp;amp;
* &lt; <small>(less than)</small> is replaced by &amp;lt; * &lt; <small>(less than)</small> is replaced by &amp;lt;
* &gt; <small>(greater than)</small> is replaced by &amp;gt; * &gt; <small>(greater than)</small> is replaced by &amp;gt;
* &quot; <small>(double quote)</small> is replaced by &amp;quot; * &quot; <small>(double quote)</small> is replaced by &amp;quot;
* </pre> * </pre>
* @param string The string to be escaped. *
* @param string
* The string to be escaped.
* @return The escaped string. * @return The escaped string.
*/ */
public static String escape(String string) { public static String escape(final String string) {
StringBuilder sb = new StringBuilder(string.length()); final StringBuilder sb = new StringBuilder(string.length());
for (int i = 0, length = string.length(); i < length; i++) { for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i); final char c = string.charAt(i);
switch (c) { switch (c) {
case '&': case '&':
sb.append("&amp;"); sb.append("&amp;");
@ -102,32 +106,37 @@ public class XML {
/** /**
* Throw an exception if the string contains whitespace. * Throw an exception if the string contains whitespace.
* Whitespace is not allowed in tagNames and attributes. * Whitespace is not allowed in tagNames and attributes.
* @param string A string. *
* @param string
* A string.
* @throws JSONException * @throws JSONException
*/ */
public static void noSpace(String string) throws JSONException { public static void noSpace(final String string) throws JSONException {
int i, length = string.length(); int i;
final int length = string.length();
if (length == 0) { if (length == 0) {
throw new JSONException("Empty string."); throw new JSONException("Empty string.");
} }
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) { if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string + throw new JSONException("'" + string + "' contains a space character.");
"' contains a space character.");
} }
} }
} }
/** /**
* Scan the content following the named tag, attaching it to the context. * 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 x
* @param name The tag name. * 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. * @return true if the close tag is processed.
* @throws JSONException * @throws JSONException
*/ */
private static boolean parse(XMLTokener x, JSONObject context, private static boolean parse(final XMLTokener x, final JSONObject context, final String name) throws JSONException {
String name) throws JSONException {
char c; char c;
int i; int i;
JSONObject jsonobject = null; JSONObject jsonobject = null;
@ -135,19 +144,19 @@ public class XML {
String tagName; String tagName;
Object token; Object token;
// Test for and skip past these forms: // Test for and skip past these forms:
// <!-- ... --> // <!-- ... -->
// <! ... > // <! ... >
// <![ ... ]]> // <![ ... ]]>
// <? ... ?> // <? ... ?>
// Report errors for these forms: // Report errors for these forms:
// <> // <>
// <= // <=
// << // <<
token = x.nextToken(); token = x.nextToken();
// <! // <!
if (token == BANG) { if (token == BANG) {
c = x.next(); c = x.next();
@ -157,7 +166,8 @@ public class XML {
return false; return false;
} }
x.back(); x.back();
} else if (c == '[') { }
else if (c == '[') {
token = x.nextToken(); token = x.nextToken();
if ("CDATA".equals(token)) { if ("CDATA".equals(token)) {
if (x.next() == '[') { if (x.next() == '[') {
@ -175,22 +185,27 @@ public class XML {
token = x.nextMeta(); token = x.nextMeta();
if (token == null) { if (token == null) {
throw x.syntaxError("Missing '>' after '<!'."); throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == LT) { }
else if (token == LT) {
i += 1; i += 1;
} else if (token == GT) { }
else if (token == GT) {
i -= 1; i -= 1;
} }
} while (i > 0); }
while (i > 0);
return false; return false;
} else if (token == QUEST) { }
else if (token == QUEST) {
// <? // <?
x.skipPast("?>"); x.skipPast("?>");
return false; return false;
} else if (token == SLASH) { }
else if (token == SLASH) {
// Close tag </ // Close tag </
token = x.nextToken(); token = x.nextToken();
if (name == null) { if (name == null) {
@ -204,13 +219,15 @@ public class XML {
} }
return true; return true;
} else if (token instanceof Character) { }
else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
// Open tag < // Open tag <
} else { }
tagName = (String)token; else {
tagName = (String) token;
token = null; token = null;
jsonobject = new JSONObject(); jsonobject = new JSONObject();
for (;;) { for (;;) {
@ -218,39 +235,42 @@ public class XML {
token = x.nextToken(); token = x.nextToken();
} }
// attribute = value // attribute = value
if (token instanceof String) { if (token instanceof String) {
string = (String)token; string = (String) token;
token = x.nextToken(); token = x.nextToken();
if (token == EQ) { if (token == EQ) {
token = x.nextToken(); token = x.nextToken();
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw x.syntaxError("Missing value"); throw x.syntaxError("Missing value");
} }
jsonobject.accumulate(string, jsonobject.accumulate(string, XML.stringToValue((String) token));
XML.stringToValue((String)token));
token = null; token = null;
} else { }
else {
jsonobject.accumulate(string, ""); jsonobject.accumulate(string, "");
} }
// Empty tag <.../> // Empty tag <.../>
} else if (token == SLASH) { }
else if (token == SLASH) {
if (x.nextToken() != GT) { if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
if (jsonobject.length() > 0) { if (jsonobject.length() > 0) {
context.accumulate(tagName, jsonobject); context.accumulate(tagName, jsonobject);
} else { }
else {
context.accumulate(tagName, ""); context.accumulate(tagName, "");
} }
return false; return false;
// Content, between <...> and </...> // Content, between <...> and </...>
} else if (token == GT) { }
else if (token == GT) {
for (;;) { for (;;) {
token = x.nextContent(); token = x.nextContent();
if (token == null) { if (token == null) {
@ -258,48 +278,51 @@ public class XML {
throw x.syntaxError("Unclosed tag " + tagName); throw x.syntaxError("Unclosed tag " + tagName);
} }
return false; return false;
} else if (token instanceof String) { }
string = (String)token; else if (token instanceof String) {
string = (String) token;
if (string.length() > 0) { if (string.length() > 0) {
jsonobject.accumulate("content", jsonobject.accumulate("content", XML.stringToValue(string));
XML.stringToValue(string));
} }
// Nested element // Nested element
} else if (token == LT) { }
else if (token == LT) {
if (parse(x, jsonobject, tagName)) { if (parse(x, jsonobject, tagName)) {
if (jsonobject.length() == 0) { if (jsonobject.length() == 0) {
context.accumulate(tagName, ""); context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 && }
jsonobject.opt("content") != null) { else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) {
context.accumulate(tagName, context.accumulate(tagName, jsonobject.opt("content"));
jsonobject.opt("content")); }
} else { else {
context.accumulate(tagName, jsonobject); context.accumulate(tagName, jsonobject);
} }
return false; return false;
} }
} }
} }
} else { }
else {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
} }
} }
} }
/** /**
* Try to convert a string into a number, boolean, or null. If the string * 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 * can't be converted, return the string. This is much less ambitious than
* JSONObject.stringToValue, especially because it does not attempt to * JSONObject.stringToValue, especially because it does not attempt to
* convert plus forms, octal forms, hex forms, or E forms lacking decimal * convert plus forms, octal forms, hex forms, or E forms lacking decimal
* points. * points.
* @param string A String. *
* @param string
* A String.
* @return A simple JSON value. * @return A simple JSON value.
*/ */
public static Object stringToValue(String string) { public static Object stringToValue(final String string) {
if ("true".equalsIgnoreCase(string)) { if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE; return Boolean.TRUE;
} }
@ -310,30 +333,32 @@ public class XML {
return JSONObject.NULL; return JSONObject.NULL;
} }
// If it might be a number, try converting it, first as a Long, and then as a // If it might be a number, try converting it, first as a Long, and then
// Double. If that doesn't work, return the string. // as a
// Double. If that doesn't work, return the string.
try { try {
char initial = string.charAt(0); final char initial = string.charAt(0);
if (initial == '-' || (initial >= '0' && initial <= '9')) { if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) {
Long value = new Long(string); final Long value = new Long(string);
if (value.toString().equals(string)) { if (value.toString().equals(string)) {
return value; return value;
} }
} }
} catch (Exception ignore) { }
catch (final Exception ignore) {
try { try {
Double value = new Double(string); final Double value = new Double(string);
if (value.toString().equals(string)) { if (value.toString().equals(string)) {
return value; return value;
} }
} catch (Exception ignoreAlso) { }
catch (final Exception ignoreAlso) {
} }
} }
return string; return string;
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation * JSONObject. Some information may be lost in this transformation
@ -344,41 +369,45 @@ public class XML {
* Sequences of similar elements are represented as JSONArrays. Content * Sequences of similar elements are represented as JSONArrays. Content
* text may be placed in a "content" member. Comments, prologs, DTDs, and * text may be placed in a "content" member. Comments, prologs, DTDs, and
* <code>&lt;[ [ ]]></code> are ignored. * <code>&lt;[ [ ]]></code> are ignored.
* @param string The source string. *
* @param string
* The source string.
* @return A JSONObject containing the structured data from the XML string. * @return A JSONObject containing the structured data from the XML string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
XMLTokener x = new XMLTokener(string); final XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) { while (x.more() && x.skipPast("<")) {
parse(x, jo, null); parse(x, jo, null);
} }
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a well-formed, element-normal XML string. * Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject. *
* @param object
* A JSONObject.
* @return A string. * @return A string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(Object object) throws JSONException { public static String toString(final Object object) throws JSONException {
return toString(object, null); return toString(object, null);
} }
/** /**
* Convert a JSONObject into a well-formed, element-normal XML string. * 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.
* @param tagName
* The optional name of the enclosing tag.
* @return A string. * @return A string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(Object object, String tagName) public static String toString(Object object, final String tagName) throws JSONException {
throws JSONException { final StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
int i; int i;
JSONArray ja; JSONArray ja;
JSONObject jo; JSONObject jo;
@ -389,7 +418,7 @@ public class XML {
Object value; Object value;
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
// Emit <tagName> // Emit <tagName>
if (tagName != null) { if (tagName != null) {
sb.append('<'); sb.append('<');
@ -397,9 +426,9 @@ public class XML {
sb.append('>'); sb.append('>');
} }
// Loop thru the keys. // Loop thru the keys.
jo = (JSONObject)object; jo = (JSONObject) object;
keys = jo.keys(); keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
key = keys.next(); key = keys.next();
@ -407,13 +436,13 @@ public class XML {
if (value == null) { if (value == null) {
value = ""; 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 ("content".equals(key)) {
if (value instanceof JSONArray) { if (value instanceof JSONArray) {
ja = (JSONArray)value; ja = (JSONArray) value;
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
if (i > 0) { if (i > 0) {
@ -421,14 +450,16 @@ public class XML {
} }
sb.append(escape(ja.get(i).toString())); sb.append(escape(ja.get(i).toString()));
} }
} else { }
else {
sb.append(escape(value.toString())); 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(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
value = ja.get(i); value = ja.get(i);
@ -440,24 +471,27 @@ public class XML {
sb.append("</"); sb.append("</");
sb.append(key); sb.append(key);
sb.append('>'); sb.append('>');
} else { }
else {
sb.append(toString(value, key)); sb.append(toString(value, key));
} }
} }
} else if ("".equals(value)) { }
else if ("".equals(value)) {
sb.append('<'); sb.append('<');
sb.append(key); sb.append(key);
sb.append("/>"); sb.append("/>");
// Emit a new tag <k> // Emit a new tag <k>
} else { }
else {
sb.append(toString(value, key)); sb.append(toString(value, key));
} }
} }
if (tagName != null) { if (tagName != null) {
// Emit the </tagname> close tag // Emit the </tagname> close tag
sb.append("</"); sb.append("</");
sb.append(tagName); sb.append(tagName);
@ -465,25 +499,26 @@ public class XML {
} }
return sb.toString(); return sb.toString();
// XML does not have good support for arrays. If an array appears in a place // XML does not have good support for arrays. If an array appears in
// where XML is lacking, synthesize an <array> element. // a place
// where XML is lacking, synthesize an <array> element.
} else { }
else {
if (object.getClass().isArray()) { if (object.getClass().isArray()) {
object = new JSONArray(object); object = new JSONArray(object);
} }
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
ja = (JSONArray)object; ja = (JSONArray) object;
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
} }
return sb.toString(); return sb.toString();
} else { }
else {
string = (object == null) ? "null" : escape(object.toString()); string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" : return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">";
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
} }
} }
} }

View File

@ -1,38 +1,40 @@
package com.intellectualcrafters.json; 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* The XMLTokener extends the JSONTokener to provide additional methods * The XMLTokener extends the JSONTokener to provide additional methods
* for the parsing of XML texts. * for the parsing of XML texts.
*
* @author JSON.org * @author JSON.org
* @version 2014-05-03 * @version 2014-05-03
*/ */
public class XMLTokener extends JSONTokener { public class XMLTokener extends JSONTokener {
/**
/** The table of entity values. It initially contains Character values for * The table of entity values. It initially contains Character values for
* amp, apos, gt, lt, quot. * amp, apos, gt, lt, quot.
*/ */
public static final java.util.HashMap<String, Character> entity; public static final java.util.HashMap<String, Character> entity;
@ -48,21 +50,25 @@ public class XMLTokener extends JSONTokener {
/** /**
* Construct an XMLTokener from a string. * 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); super(s);
} }
/** /**
* Get the text in the CDATA block. * Get the text in the CDATA block.
*
* @return The string up to the <code>]]&gt;</code>. * @return The string up to the <code>]]&gt;</code>.
* @throws JSONException If the <code>]]&gt;</code> is not found. * @throws JSONException
* If the <code>]]&gt;</code> is not found.
*/ */
public String nextCDATA() throws JSONException { public String nextCDATA() throws JSONException {
char c; char c;
int i; int i;
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (;;) { for (;;) {
c = next(); c = next();
if (end()) { if (end()) {
@ -70,15 +76,13 @@ public class XMLTokener extends JSONTokener {
} }
sb.append(c); sb.append(c);
i = sb.length() - 3; i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' && if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) {
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i); sb.setLength(i);
return sb.toString(); return sb.toString();
} }
} }
} }
/** /**
* Get the next XML outer token, trimming whitespace. There are two kinds * Get the next XML outer token, trimming whitespace. There are two kinds
* of tokens: the '<' character which begins a markup tag, and the content * of tokens: the '<' character which begins a markup tag, and the content
@ -93,7 +97,8 @@ public class XMLTokener extends JSONTokener {
StringBuilder sb; StringBuilder sb;
do { do {
c = next(); c = next();
} while (Character.isWhitespace(c)); }
while (Character.isWhitespace(c));
if (c == 0) { if (c == 0) {
return null; return null;
} }
@ -102,52 +107,59 @@ public class XMLTokener extends JSONTokener {
} }
sb = new StringBuilder(); sb = new StringBuilder();
for (;;) { for (;;) {
if (c == '<' || c == 0) { if ((c == '<') || (c == 0)) {
back(); back();
return sb.toString().trim(); return sb.toString().trim();
} }
if (c == '&') { if (c == '&') {
sb.append(nextEntity(c)); sb.append(nextEntity(c));
} else { }
else {
sb.append(c); sb.append(c);
} }
c = next(); c = next();
} }
} }
/** /**
* Return the next entity. These entities are translated to Characters: * Return the next entity. These entities are translated to Characters:
* <code>&amp; &apos; &gt; &lt; &quot;</code>. * <code>&amp; &apos; &gt; &lt; &quot;</code>.
* @param ampersand An ampersand character. *
* @param ampersand
* An ampersand character.
* @return A Character or an entity String if the entity is not recognized. * @return A Character or an entity String if the entity is not recognized.
* @throws JSONException If missing ';' in XML entity. * @throws JSONException
* If missing ';' in XML entity.
*/ */
public Object nextEntity(char ampersand) throws JSONException { public Object nextEntity(final char ampersand) throws JSONException {
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (;;) { for (;;) {
char c = next(); final char c = next();
if (Character.isLetterOrDigit(c) || c == '#') { if (Character.isLetterOrDigit(c) || (c == '#')) {
sb.append(Character.toLowerCase(c)); sb.append(Character.toLowerCase(c));
} else if (c == ';') { }
else if (c == ';') {
break; break;
} else { }
else {
throw syntaxError("Missing ';' in XML entity: &" + sb); throw syntaxError("Missing ';' in XML entity: &" + sb);
} }
} }
String string = sb.toString(); final String string = sb.toString();
Object object = entity.get(string); final Object object = entity.get(string);
return object != null ? object : ampersand + string + ";"; return object != null ? object : ampersand + string + ";";
} }
/** /**
* Returns the next XML meta token. This is used for skipping over <!...> * Returns the next XML meta token. This is used for skipping over <!...>
* and <?...?> structures. * and <?...?> structures.
*
* @return Syntax characters (<code>< > / = ! ?</code>) are returned as * @return Syntax characters (<code>< > / = ! ?</code>) are returned as
* Character, and strings and names are returned as Boolean. We don't care * Character, and strings and names are returned as Boolean. We
* don't care
* what the values actually are. * what the values actually are.
* @throws JSONException If a string is not properly closed or if the XML * @throws JSONException
* If a string is not properly closed or if the XML
* is badly structured. * is badly structured.
*/ */
public Object nextMeta() throws JSONException { public Object nextMeta() throws JSONException {
@ -155,7 +167,8 @@ public class XMLTokener extends JSONTokener {
char q; char q;
do { do {
c = next(); c = next();
} while (Character.isWhitespace(c)); }
while (Character.isWhitespace(c));
switch (c) { switch (c) {
case 0: case 0:
throw syntaxError("Misshaped meta tag"); throw syntaxError("Misshaped meta tag");
@ -206,14 +219,15 @@ public class XMLTokener extends JSONTokener {
} }
} }
/** /**
* Get the next XML Token. These tokens are found inside of angle * Get the next XML Token. These tokens are found inside of angle
* brackets. It may be one of these characters: <code>/ > = ! ?</code> or it * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it
* may be a string wrapped in single quotes or double quotes, or it may be a * may be a string wrapped in single quotes or double quotes, or it may be a
* name. * name.
*
* @return a String or a Character. * @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 { public Object nextToken() throws JSONException {
char c; char c;
@ -221,7 +235,8 @@ public class XMLTokener extends JSONTokener {
StringBuilder sb; StringBuilder sb;
do { do {
c = next(); c = next();
} while (Character.isWhitespace(c)); }
while (Character.isWhitespace(c));
switch (c) { switch (c) {
case 0: case 0:
throw syntaxError("Misshaped element"); throw syntaxError("Misshaped element");
@ -238,7 +253,7 @@ public class XMLTokener extends JSONTokener {
case '?': case '?':
return XML.QUEST; return XML.QUEST;
// Quoted string // Quoted string
case '"': case '"':
case '\'': case '\'':
@ -254,13 +269,14 @@ public class XMLTokener extends JSONTokener {
} }
if (c == '&') { if (c == '&') {
sb.append(nextEntity(c)); sb.append(nextEntity(c));
} else { }
else {
sb.append(c); sb.append(c);
} }
} }
default: default:
// Name // Name
sb = new StringBuilder(); sb = new StringBuilder();
for (;;) { for (;;) {
@ -290,21 +306,23 @@ public class XMLTokener extends JSONTokener {
} }
} }
/** /**
* Skip characters until past the requested string. * 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. * If it is not found, we are left at the end of the source with a result of
* @param to A string to skip past. * false.
*
* @param to
* A string to skip past.
* @throws JSONException * @throws JSONException
*/ */
public boolean skipPast(String to) throws JSONException { public boolean skipPast(final String to) throws JSONException {
boolean b; boolean b;
char c; char c;
int i; int i;
int j; int j;
int offset = 0; int offset = 0;
int length = to.length(); final int length = to.length();
char[] circle = new char[length]; final char[] circle = new char[length];
/* /*
* First fill the circle buffer with as many characters as are in the * First fill the circle buffer with as many characters as are in the

View File

@ -16,7 +16,7 @@ public class AbstractFlag {
* The key must be alphabetical characters and <= 16 characters * The key must be alphabetical characters and <= 16 characters
* in length * in length
*/ */
public AbstractFlag(String key) { public AbstractFlag(final String key) {
if (!StringUtils.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) { if (!StringUtils.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) {
throw new IllegalArgumentException("Flag must be alphabetic characters"); throw new IllegalArgumentException("Flag must be alphabetic characters");
} }
@ -26,7 +26,7 @@ public class AbstractFlag {
this.key = key.toLowerCase(); this.key = key.toLowerCase();
} }
public String parseValue(String value) { public String parseValue(final String value) {
return value; return value;
} }
@ -34,7 +34,6 @@ public class AbstractFlag {
return "Flag value must be alphanumeric"; return "Flag value must be alphanumeric";
} }
/** /**
* AbstractFlag key * AbstractFlag key
* *
@ -50,11 +49,17 @@ public class AbstractFlag {
} }
@Override @Override
public boolean equals(Object other){ public boolean equals(final Object other) {
if (other == null) return false; if (other == null) {
if (other == this) return true; return false;
if (!(other instanceof AbstractFlag)) return false; }
AbstractFlag otherObj = (AbstractFlag)other; if (other == this) {
return true;
}
if (!(other instanceof AbstractFlag)) {
return false;
}
final AbstractFlag otherObj = (AbstractFlag) other;
return (otherObj.key.equals(this.key)); return (otherObj.key.equals(this.key));
} }

View File

@ -1,5 +1,6 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
public class BlockWrapper { public class BlockWrapper {
public int x; public int x;
public int y; public int y;
@ -7,7 +8,7 @@ public class BlockWrapper {
public int id; public int id;
public byte data; 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.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;

View File

@ -40,7 +40,7 @@ public enum C {
NOT_CONSOLE("&cFor safety reasons, this command can only be executed by console."), NOT_CONSOLE("&cFor safety reasons, this command can only be executed by console."),
IS_CONSOLE("&cThis command can only be executed by a player."), 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"), 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."), PASTED("&cThe plot selection was successfully pasted. It has been cleared from your clipboard."),
@ -327,10 +327,7 @@ public enum C {
HELP_CATEGORY("&6Current Category&c: &l%category%"), HELP_CATEGORY("&6Current Category&c: &l%category%"),
HELP_INFO("&6You need to specify a help category"), HELP_INFO("&6You need to specify a help category"),
HELP_INFO_ITEM("&6/plots help %category% &c- &6%category_desc%"), HELP_INFO_ITEM("&6/plots help %category% &c- &6%category_desc%"),
HELP_PAGE( HELP_PAGE("&c>> &6%usage% &c[&6%alias%&c]\n" + "&c>> &6%desc%\n"),
"&c>> &6%usage% &c[&6%alias%&c]\n" +
"&c>> &6%desc%\n"
),
HELP_ITEM_SEPARATOR("&c%lines"), HELP_ITEM_SEPARATOR("&c%lines"),
HELP_HEADER("&c(Page &6%cur&c/&6%max&c) &6Help for Plots"), HELP_HEADER("&c(Page &6%cur&c/&6%max&c) &6Help for Plots"),
/* /*
@ -366,7 +363,7 @@ public enum C {
* @param d * @param d
* default * default
*/ */
C(String d) { C(final String d) {
this.d = d; this.d = d;
if (PlotMain.translations == null) { if (PlotMain.translations == null) {
this.s = d; this.s = d;
@ -382,6 +379,7 @@ public enum C {
public static class Potato { public static class Potato {
} }
/** /**
* Get the default string * Get the default string
* *
@ -398,9 +396,9 @@ public enum C {
* @return translated if exists else default * @return translated if exists else default
*/ */
public String s() { public String s() {
if(PlotMain.translations != null){ if (PlotMain.translations != null) {
String t = PlotMain.translations.getString(this.toString()); final String t = PlotMain.translations.getString(this.toString());
if (t!=null) { if (t != null) {
this.s = t; this.s = t;
} }
} }

View File

@ -3,103 +3,102 @@ package com.intellectualcrafters.plot;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
public class Configuration { public class Configuration {
public static final SettingValue STRING = new SettingValue("STRING") { public static final SettingValue STRING = new SettingValue("STRING") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
return true; return true;
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
return string; return string;
} }
}; };
public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") { public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
return true; return true;
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
return string.split(","); return string.split(",");
} }
}; };
public static final SettingValue INTEGER = new SettingValue("INTEGER") { public static final SettingValue INTEGER = new SettingValue("INTEGER") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
try { try {
Integer.parseInt(string); Integer.parseInt(string);
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
return Integer.parseInt(string); return Integer.parseInt(string);
} }
}; };
public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
try { try {
Boolean.parseBoolean(string); Boolean.parseBoolean(string);
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
return Boolean.parseBoolean(string); return Boolean.parseBoolean(string);
} }
}; };
public static final SettingValue DOUBLE = new SettingValue("DOUBLE") { public static final SettingValue DOUBLE = new SettingValue("DOUBLE") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
try { try {
Double.parseDouble(string); Double.parseDouble(string);
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
return Double.parseDouble(string); return Double.parseDouble(string);
} }
}; };
public static final SettingValue BIOME = new SettingValue("BIOME") { public static final SettingValue BIOME = new SettingValue("BIOME") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
try { try {
Biome.valueOf(string.toUpperCase()); Biome.valueOf(string.toUpperCase());
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
for (Biome biome : Biome.values()) { for (final Biome biome : Biome.values()) {
if (biome.name().equals(string.toUpperCase())) { if (biome.name().equals(string.toUpperCase())) {
return biome; return biome;
} }
@ -108,17 +107,17 @@ public class Configuration {
} }
@Override @Override
public Object parseObject(Object object) { public Object parseObject(final Object object) {
return ((Biome) object).toString(); return ((Biome) object).toString();
} }
}; };
public static final SettingValue BLOCK = new SettingValue("BLOCK") { public static final SettingValue BLOCK = new SettingValue("BLOCK") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
try { try {
if (string.contains(":")) { if (string.contains(":")) {
String[] split = string.split(":"); final String[] split = string.split(":");
Short.parseShort(split[0]); Short.parseShort(split[0]);
Short.parseShort(split[1]); Short.parseShort(split[1]);
} }
@ -127,15 +126,15 @@ public class Configuration {
} }
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
if (string.contains(":")) { if (string.contains(":")) {
String[] split = string.split(":"); final String[] split = string.split(":");
return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1]));
} }
else { else {
@ -144,35 +143,38 @@ public class Configuration {
} }
@Override @Override
public Object parseObject(Object object) { public Object parseObject(final Object object) {
return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data; return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data;
} }
}; };
public static int gcd(int a, int b) { public static int gcd(final int a, final int b) {
if (b==0) return a; if (b == 0) {
return gcd(b,a%b); return a;
} }
private static int gcd(int[] a) return gcd(b, a % b);
{ }
private static int gcd(final int[] a) {
int result = a[0]; int result = a[0];
for(int i = 1; i < a.length; i++) for (int i = 1; i < a.length; i++) {
result = gcd(result, a[i]); result = gcd(result, a[i]);
}
return result; return result;
} }
public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") { public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(final String string) {
try { try {
for (String block : string.split(",")) { for (String block : string.split(",")) {
if (block.contains("%")) { if (block.contains("%")) {
String[] split = block.split("%"); final String[] split = block.split("%");
Integer.parseInt(split[0]); Integer.parseInt(split[0]);
block = split[1]; block = split[1];
} }
if (block.contains(":")) { if (block.contains(":")) {
String[] split = block.split(":"); final String[] split = block.split(":");
Short.parseShort(split[0]); Short.parseShort(split[0]);
Short.parseShort(split[1]); Short.parseShort(split[1]);
} }
@ -182,48 +184,47 @@ public class Configuration {
} }
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(final String string) {
String[] blocks = string.split(","); final String[] blocks = string.split(",");
ArrayList<PlotBlock> parsedvalues = new ArrayList<PlotBlock>(); final ArrayList<PlotBlock> parsedvalues = new ArrayList<PlotBlock>();
final PlotBlock[] values = new PlotBlock[blocks.length];
PlotBlock[] values = new PlotBlock[blocks.length]; final int[] counts = new int[blocks.length];
int[] counts = new int[blocks.length];
int min = 100; int min = 100;
for (int i = 0; i < blocks.length; i++) { for (int i = 0; i < blocks.length; i++) {
if (blocks[i].contains("%")) { if (blocks[i].contains("%")) {
String[] split = blocks[i].split("%"); final String[] split = blocks[i].split("%");
blocks[i] = split[1]; blocks[i] = split[1];
int value = Integer.parseInt(split[0]); final int value = Integer.parseInt(split[0]);
counts[i] = value; counts[i] = value;
if (value<min) { if (value < min) {
min = value; min = value;
} }
} }
else { else {
counts[i] = 1; counts[i] = 1;
if (1<min) { if (1 < min) {
min = 1; min = 1;
} }
} }
if (blocks[i].contains(":")) { if (blocks[i].contains(":")) {
String[] split = blocks[i].split(":"); final String[] split = blocks[i].split(":");
values[i] = new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); values[i] = new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1]));
} }
else { else {
values[i] = new PlotBlock(Short.parseShort(blocks[i]), (byte) 0); values[i] = new PlotBlock(Short.parseShort(blocks[i]), (byte) 0);
} }
} }
int gcd = gcd(counts); final int gcd = gcd(counts);
for (int i = 0; i < counts.length; i++) { for (int i = 0; i < counts.length; i++) {
int num = counts[i]; final int num = counts[i];
for (int j = 0; j<num/gcd; j++) { for (int j = 0; j < (num / gcd); j++) {
parsedvalues.add(values[i]); parsedvalues.add(values[i]);
} }
} }
@ -232,9 +233,9 @@ public class Configuration {
} }
@Override @Override
public Object parseObject(Object object) { public Object parseObject(final Object object) {
List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<String>();
for (PlotBlock block : (PlotBlock[]) object) { for (final PlotBlock block : (PlotBlock[]) object) {
list.add((block.id + ":" + (block.data))); list.add((block.id + ":" + (block.data)));
} }
return list; return list;
@ -246,9 +247,9 @@ public class Configuration {
* configuration easier * configuration easier
*/ */
public static abstract class SettingValue { public static abstract class SettingValue {
private String type; private final String type;
public SettingValue(String type) { public SettingValue(final String type) {
this.type = type; this.type = type;
} }
@ -256,12 +257,12 @@ public class Configuration {
return this.type; return this.type;
} }
public Object parseObject(Object object) { public Object parseObject(final Object object) {
return object; return object;
} }
public abstract Object parseString(String string); public abstract Object parseString(final String string);
public abstract boolean validateValue(String string); public abstract boolean validateValue(final String string);
} }
} }

View File

@ -1,19 +1,19 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import com.intellectualcrafters.plot.Configuration.SettingValue;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays; import java.util.Arrays;
public class ConfigurationNode { import org.apache.commons.lang.StringUtils;
private String constant;
private Object default_value;
private String description;
private Object value;
private SettingValue type;
public ConfigurationNode(String constant, Object default_value, String description, SettingValue type, import com.intellectualcrafters.plot.Configuration.SettingValue;
boolean required) {
public class ConfigurationNode {
private final String constant;
private final Object default_value;
private final String description;
private Object value;
private final SettingValue type;
public ConfigurationNode(final String constant, final Object default_value, final String description, final SettingValue type, final boolean required) {
this.constant = constant; this.constant = constant;
this.default_value = default_value; this.default_value = default_value;
this.description = description; this.description = description;
@ -25,20 +25,20 @@ public class ConfigurationNode {
return this.type; return this.type;
} }
public boolean isValid(String string) { public boolean isValid(final String string) {
try { try {
Object result = this.type.parseString(string); final Object result = this.type.parseString(string);
if (result == null) { if (result == null) {
return false; return false;
} }
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
public boolean setValue(String string) { public boolean setValue(final String string) {
if (!this.type.validateValue(string)) { if (!this.type.validateValue(string)) {
return false; return false;
} }

View File

@ -21,10 +21,10 @@ public class ConsoleColors {
UNDERLINE("\033[0m"), UNDERLINE("\033[0m"),
ITALIC("\033[3m"); ITALIC("\033[3m");
private String win; private final String win;
private String lin; private final String lin;
ConsoleColor(String lin) { ConsoleColor(final String lin) {
this.lin = lin; this.lin = lin;
this.win = this.win; this.win = this.win;
} }
@ -52,16 +52,16 @@ public class ConsoleColors {
*/ */
public static String fromString(String input) { public static String fromString(String input) {
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))
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)); .replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET));
return input + "\u001B[0m"; return input + "\u001B[0m";
} }
public static String fromChatColor(ChatColor color) { public static String fromChatColor(final ChatColor color) {
return chatColor(color).getLin(); return chatColor(color).getLin();
} }
public static ConsoleColor chatColor(ChatColor color) { public static ConsoleColor chatColor(final ChatColor color) {
switch (color) { switch (color) {
case RESET: case RESET:
return ConsoleColor.RESET; return ConsoleColor.RESET;

View File

@ -3,8 +3,8 @@ package com.intellectualcrafters.plot;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
public class Flag { public class Flag {
private AbstractFlag key; private final AbstractFlag key;
private String value; private final String value;
/** /**
* Flag object used to store basic information for a Plot. Flags are a * Flag object used to store basic information for a Plot. Flags are a
@ -19,13 +19,12 @@ public class Flag {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if you provide inadequate inputs * if you provide inadequate inputs
*/ */
public Flag(AbstractFlag key, String value) { public Flag(final AbstractFlag key, final String value) {
char[] allowedCharacters = new char[] { final char[] allowedCharacters = new char[] { '[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§' };
'[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§'
};
String tempValue = value; String tempValue = value;
for(char c : allowedCharacters) for (final char c : allowedCharacters) {
tempValue = tempValue.replace(c, 'c'); tempValue = tempValue.replace(c, 'c');
}
if (!StringUtils.isAlphanumericSpace(tempValue)) { if (!StringUtils.isAlphanumericSpace(tempValue)) {
throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)"); throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)");
} }
@ -34,7 +33,7 @@ public class Flag {
} }
this.key = key; this.key = key;
this.value = key.parseValue(value); this.value = key.parseValue(value);
if (this.value==null) { if (this.value == null) {
throw new IllegalArgumentException(key.getValueDesc()); throw new IllegalArgumentException(key.getValueDesc());
} }
} }
@ -75,7 +74,7 @@ public class Flag {
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -85,7 +84,7 @@ public class Flag {
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
Flag other = (Flag) obj; final Flag other = (Flag) obj;
return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value)); return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value));
} }

View File

@ -1,11 +1,11 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.entity.Player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.bukkit.entity.Player;
public class FlagManager { public class FlagManager {
// TODO add some flags // TODO add some flags
@ -23,30 +23,32 @@ public class FlagManager {
* @param flag * @param flag
* @return * @return
*/ */
public static boolean addFlag(AbstractFlag flag) { public static boolean addFlag(final AbstractFlag flag) {
if (getFlag(flag.getKey()) != null) { if (getFlag(flag.getKey()) != null) {
return false; return false;
} }
return flags.add(flag); return flags.add(flag);
} }
public static Flag[] removeFlag(Flag[] flags, String r) { public static Flag[] removeFlag(final Flag[] flags, final String r) {
Flag[] f = new Flag[flags.length - 1]; final Flag[] f = new Flag[flags.length - 1];
int index = 0; int index = 0;
for(Flag flag : flags) { for (final Flag flag : flags) {
if(!flag.getKey().equals(r)) if (!flag.getKey().equals(r)) {
f[index++] = flag; f[index++] = flag;
} }
}
return f; return f;
} }
public static Flag[] removeFlag(Set<Flag> flags, String r) { public static Flag[] removeFlag(final Set<Flag> flags, final String r) {
Flag[] flagArray = new Flag[flags.size() - 1]; final Flag[] flagArray = new Flag[flags.size() - 1];
int index = 0; int index = 0;
for(Flag flag : flags) { for (final Flag flag : flags) {
if(!flag.getKey().equals(r)) if (!flag.getKey().equals(r)) {
flagArray[index++] = flag; flagArray[index++] = flag;
} }
}
return flagArray; return flagArray;
} }
@ -61,15 +63,18 @@ public class FlagManager {
/** /**
* Get a list of registerd AbstragFlag objects based on player permissions * Get a list of registerd AbstragFlag objects based on player permissions
* @param player with permissions *
* @param player
* with permissions
* @return List (AbstractFlag) * @return List (AbstractFlag)
*/ */
public static List<AbstractFlag> getFlags(Player player) { public static List<AbstractFlag> getFlags(final Player player) {
List<AbstractFlag> returnFlags = new ArrayList<>(); final List<AbstractFlag> returnFlags = new ArrayList<>();
for(AbstractFlag flag : flags) { for (final AbstractFlag flag : flags) {
if(player.hasPermission("plots.set." + flag.getKey().toLowerCase())) if (player.hasPermission("plots.set." + flag.getKey().toLowerCase())) {
returnFlags.add(flag); returnFlags.add(flag);
} }
}
return returnFlags; return returnFlags;
} }
@ -79,8 +84,8 @@ public class FlagManager {
* @param string * @param string
* @return AbstractFlag * @return AbstractFlag
*/ */
public static AbstractFlag getFlag(String string) { public static AbstractFlag getFlag(final String string) {
for (AbstractFlag flag : flags) { for (final AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) { if (flag.getKey().equalsIgnoreCase(string)) {
return flag; return flag;
} }
@ -96,9 +101,9 @@ public class FlagManager {
* If to create the flag if it does not exist * If to create the flag if it does not exist
* @return AbstractFlag * @return AbstractFlag
*/ */
public static AbstractFlag getFlag(String string, boolean create) { public static AbstractFlag getFlag(final String string, final boolean create) {
if ((getFlag(string) == null) && create) { if ((getFlag(string) == null) && create) {
AbstractFlag flag = new AbstractFlag(string); final AbstractFlag flag = new AbstractFlag(string);
addFlag(flag); addFlag(flag);
return flag; return flag;
} }
@ -111,14 +116,14 @@ public class FlagManager {
* @param flag * @param flag
* @return boolean Result of operation * @return boolean Result of operation
*/ */
public static boolean removeFlag(AbstractFlag flag) { public static boolean removeFlag(final AbstractFlag flag) {
return flags.remove(flag); return flags.remove(flag);
} }
public static Flag[] parseFlags(List<String> flagstrings) { public static Flag[] parseFlags(final List<String> flagstrings) {
Flag[] flags = new Flag[flagstrings.size()]; final Flag[] flags = new Flag[flagstrings.size()];
for (int i = 0; i < flagstrings.size(); i++) { for (int i = 0; i < flagstrings.size(); i++) {
String[] split = flagstrings.get(i).split(";"); final String[] split = flagstrings.get(i).split(";");
if (split.length == 1) { if (split.length == 1) {
flags[i] = new Flag(getFlag(split[0], true), ""); flags[i] = new Flag(getFlag(split[0], true), "");
} }
@ -135,10 +140,10 @@ public class FlagManager {
* @param plot * @param plot
* @return List (AbstractFlag) * @return List (AbstractFlag)
*/ */
public static List<AbstractFlag> getPlotFlags(Plot plot) { public static List<AbstractFlag> getPlotFlags(final Plot plot) {
Set<Flag> plotFlags = plot.settings.getFlags(); final Set<Flag> plotFlags = plot.settings.getFlags();
List<AbstractFlag> flags = new ArrayList<>(); final List<AbstractFlag> flags = new ArrayList<>();
for (Flag flag : plotFlags) { for (final Flag flag : plotFlags) {
flags.add(flag.getAbstractFlag()); flags.add(flag.getAbstractFlag());
} }
return flags; return flags;

View File

@ -28,7 +28,7 @@ public class LSetCube {
* @param l1 * @param l1
* @param l2 * @param l2
*/ */
public LSetCube(Location l1, Location l2) { public LSetCube(final Location l1, final Location l2) {
this.l1 = l1; this.l1 = l1;
this.l1 = l2; this.l1 = l2;
} }
@ -39,7 +39,7 @@ public class LSetCube {
* @param l1 * @param l1
* @param size * @param size
*/ */
public LSetCube(Location l1, int size) { public LSetCube(final Location l1, final int size) {
this.l1 = l1; this.l1 = l1;
this.l2 = l1.clone().add(size, size, size); this.l2 = l1.clone().add(size, size, size);
} }
@ -50,9 +50,9 @@ public class LSetCube {
* @return abs. min * @return abs. min
*/ */
public Location minLoc() { public Location minLoc() {
int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX()); final int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY()); final int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ()); final int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z); return new Location(this.l1.getWorld(), x, y, z);
} }
@ -62,9 +62,9 @@ public class LSetCube {
* @return abs. max * @return abs. max
*/ */
public Location maxLoc() { public Location maxLoc() {
int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX()); final int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY()); final int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ()); final int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z); return new Location(this.l1.getWorld(), x, y, z);
} }
@ -84,11 +84,11 @@ public class LSetCube {
/** /**
* *
*/ */
private Location min; private final Location min;
/** /**
* *
*/ */
private Location max; private final Location max;
/** /**
* *
*/ */
@ -97,7 +97,7 @@ public class LSetCube {
/** /**
* @param cube * @param cube
*/ */
public LCycler(LSetCube cube) { public LCycler(final LSetCube cube) {
this.min = cube.minLoc(); this.min = cube.minLoc();
this.max = cube.maxLoc(); this.max = cube.maxLoc();
this.current = this.min; this.current = this.min;
@ -107,9 +107,7 @@ public class LSetCube {
* @return * @return
*/ */
public boolean hasNext() { public boolean hasNext() {
return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ());
&& ((this.current.getBlockY() + 1) <= this.max.getBlockY())
&& ((this.current.getBlockZ() + 1) <= this.max.getBlockZ());
} }
/** /**

View File

@ -45,12 +45,12 @@ public class Lag implements Runnable {
* Ticks * Ticks
* @return ticks per second * @return ticks per second
*/ */
public static double getTPS(int ticks) { public static double getTPS(final int ticks) {
if (TC < ticks) { if (TC < ticks) {
return 20.0D; return 20.0D;
} }
int t = (TC - 1 - ticks) % T.length; final int t = (TC - 1 - ticks) % T.length;
long e = System.currentTimeMillis() - T[t]; final long e = System.currentTimeMillis() - T[t];
return ticks / (e / 1000.0D); return ticks / (e / 1000.0D);
} }
@ -62,8 +62,8 @@ public class Lag implements Runnable {
* @return number of ticks since $tI * @return number of ticks since $tI
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static long getElapsed(int tI) { public static long getElapsed(final int tI) {
long t = T[tI % T.length]; final long t = T[tI % T.length];
return System.currentTimeMillis() - t; return System.currentTimeMillis() - t;
} }

View File

@ -26,18 +26,18 @@ public class Logger {
private static ArrayList<String> entries; private static ArrayList<String> entries;
private static File log; private static File log;
public static void setup(File file) { public static void setup(final File file) {
log = file; log = file;
entries = new ArrayList<>(); entries = new ArrayList<>();
try { try {
BufferedReader reader = new BufferedReader(new FileReader(file)); final BufferedReader reader = new BufferedReader(new FileReader(file));
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
entries.add(line); entries.add(line);
} }
reader.close(); reader.close();
} }
catch (IOException e) { catch (final IOException e) {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup"); PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup");
} }
} }
@ -46,9 +46,9 @@ public class Logger {
GENERAL("General"), GENERAL("General"),
WARNING("Warning"), WARNING("Warning"),
DANGER("Danger"); DANGER("Danger");
private String name; private final String name;
LogLevel(String name) { LogLevel(final String name) {
this.name = name; this.name = name;
} }
@ -59,18 +59,18 @@ public class Logger {
} }
public static void write() throws IOException { public static void write() throws IOException {
FileWriter writer = new FileWriter(log); final FileWriter writer = new FileWriter(log);
for (String string : entries) { for (final String string : entries) {
writer.write(string + System.lineSeparator()); writer.write(string + System.lineSeparator());
} }
writer.close(); writer.close();
} }
public static void add(LogLevel level, String string) { public static void add(final LogLevel level, final String string) {
append("[" + level.toString() + "] " + string); append("[" + level.toString() + "] " + string);
} }
private static void append(String string) { private static void append(final String string) {
entries.add("[" + new Date().toString() + "]" + string); entries.add("[" + new Date().toString() + "]" + string);
} }
} }

View File

@ -29,6 +29,28 @@ package com.intellectualcrafters.plot;
* representing official policies, either expressed or implied, of anybody else. * 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.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -37,16 +59,6 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask; 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 { public class Metrics {
/** /**
* The current revision number * The current revision number
@ -192,7 +204,7 @@ public class Metrics {
Metrics.this.task = null; Metrics.this.task = null;
// Tell all plotters to stop gathering // Tell all plotters to stop gathering
// information. // information.
for (Graph graph : Metrics.this.graphs) { for (final Graph graph : Metrics.this.graphs) {
graph.onOptOut(); graph.onOptOut();
} }
} }
@ -211,7 +223,7 @@ public class Metrics {
// Each post thereafter will be a ping // Each post thereafter will be a ping
this.firstPost = false; this.firstPost = false;
} }
catch (IOException e) { catch (final IOException e) {
if (Metrics.this.debug) { if (Metrics.this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
} }
@ -233,13 +245,13 @@ public class Metrics {
// Reload the metrics file // Reload the metrics file
this.configuration.load(getConfigFile()); this.configuration.load(getConfigFile());
} }
catch (IOException ex) { catch (final IOException ex) {
if (this.debug) { if (this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
} }
return true; return true;
} }
catch (InvalidConfigurationException ex) { catch (final InvalidConfigurationException ex) {
if (this.debug) { if (this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
} }
@ -309,7 +321,7 @@ public class Metrics {
// plugin.getDataFolder() => base/plugins/PluginA/ // plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/ // pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory. // The base is not necessarily relative to the startup directory.
File pluginsFolder = this.plugin.getDataFolder().getParentFile(); final File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml // return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
@ -319,28 +331,32 @@ public class Metrics {
*/ */
private void postPlugin(final boolean isPing) throws IOException { private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section // Server software specific section
PluginDescriptionFile description = this.plugin.getDescription(); final PluginDescriptionFile description = this.plugin.getDescription();
String pluginName = description.getName(); final String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if final boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE
// if
// online // online
// mode // mode
// is // is
// enabled // enabled
String pluginVersion = description.getVersion(); final String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion(); final String serverVersion = Bukkit.getVersion();
int playersOnline = 0; int playersOnline = 0;
try { try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
playersOnline = ((Collection<?>)Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).size(); playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).size();
else }
playersOnline = ((Player[])Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).length; else {
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).length;
}
}
catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
} }
catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex){}
// END server software specific section -- all code below does not use // END server software specific section -- all code below does not use
// any code outside of this class / Java // any code outside of this class / Java
// Construct the post data // Construct the post data
StringBuilder json = new StringBuilder(1024); final StringBuilder json = new StringBuilder(1024);
json.append('{'); json.append('{');
// The plugin's description file containg all of the plugin data such as // The plugin's description file containg all of the plugin data such as
// name, version, author, etc // name, version, author, etc
@ -349,11 +365,11 @@ public class Metrics {
appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline)); appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6 // New data as of R6
String osname = System.getProperty("os.name"); final String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch"); String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version"); final String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version"); final String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors(); final int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64 // normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) { if (osarch.equals("amd64")) {
osarch = "x86_64"; osarch = "x86_64";
@ -379,10 +395,10 @@ public class Metrics {
boolean firstGraph = true; boolean firstGraph = true;
final Iterator<Graph> iter = this.graphs.iterator(); final Iterator<Graph> iter = this.graphs.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Graph graph = iter.next(); final Graph graph = iter.next();
StringBuilder graphJson = new StringBuilder(); final StringBuilder graphJson = new StringBuilder();
graphJson.append('{'); graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) { for (final Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
} }
graphJson.append('}'); graphJson.append('}');
@ -400,7 +416,7 @@ public class Metrics {
// close json // close json
json.append('}'); json.append('}');
// Create the url // Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website // Connect to the website
URLConnection connection; URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it // Mineshafter creates a socks proxy, so we can safely bypass it
@ -411,8 +427,8 @@ public class Metrics {
else { else {
connection = url.openConnection(); connection = url.openConnection();
} }
byte[] uncompressed = json.toString().getBytes(); final byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString()); final byte[] compressed = gzip(json.toString());
// Headers // Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Content-Type", "application/json");
@ -422,11 +438,10 @@ public class Metrics {
connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true); connection.setDoOutput(true);
if (this.debug) { if (this.debug) {
System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
+ " compressed=" + compressed.length);
} }
// Write the data // Write the data
OutputStream os = connection.getOutputStream(); final OutputStream os = connection.getOutputStream();
os.write(compressed); os.write(compressed);
os.flush(); os.flush();
// Now read the response // Now read the response
@ -439,8 +454,7 @@ public class Metrics {
if (response == null) { if (response == null) {
response = "null"; response = "null";
} }
else else if (response.startsWith("7")) {
if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1); response = response.substring(response.startsWith("7,") ? 2 : 1);
} }
throw new IOException(response); throw new IOException(response);
@ -452,7 +466,7 @@ public class Metrics {
final Iterator<Graph> iter = this.graphs.iterator(); final Iterator<Graph> iter = this.graphs.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
final Graph graph = iter.next(); final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) { for (final Plotter plotter : graph.getPlotters()) {
plotter.reset(); plotter.reset();
} }
} }
@ -467,14 +481,14 @@ public class Metrics {
* @param input * @param input
* @return * @return
*/ */
public static byte[] gzip(String input) { public static byte[] gzip(final String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null; GZIPOutputStream gzos = null;
try { try {
gzos = new GZIPOutputStream(baos); gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8")); gzos.write(input.getBytes("UTF-8"));
} }
catch (IOException e) { catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
finally { finally {
@ -482,7 +496,7 @@ public class Metrics {
try { try {
gzos.close(); gzos.close();
} }
catch (IOException ignore) { catch (final IOException ignore) {
} }
} }
} }
@ -500,7 +514,7 @@ public class Metrics {
Class.forName("mineshafter.MineServer"); Class.forName("mineshafter.MineServer");
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
} }
@ -513,7 +527,7 @@ public class Metrics {
* @param value * @param value
* @throws UnsupportedEncodingException * @throws UnsupportedEncodingException
*/ */
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false; boolean isValueNumeric = false;
try { try {
if (value.equals("0") || !value.endsWith("0")) { if (value.equals("0") || !value.endsWith("0")) {
@ -521,7 +535,7 @@ public class Metrics {
isValueNumeric = true; isValueNumeric = true;
} }
} }
catch (NumberFormatException e) { catch (final NumberFormatException e) {
isValueNumeric = false; isValueNumeric = false;
} }
if (json.charAt(json.length() - 1) != '{') { if (json.charAt(json.length() - 1) != '{') {
@ -543,11 +557,11 @@ public class Metrics {
* @param text * @param text
* @return * @return
*/ */
private static String escapeJSON(String text) { private static String escapeJSON(final String text) {
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append('"'); builder.append('"');
for (int index = 0; index < text.length(); index++) { for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index); final char chr = text.charAt(index);
switch (chr) { switch (chr) {
case '"': case '"':
case '\\': case '\\':
@ -568,7 +582,7 @@ public class Metrics {
break; break;
default: default:
if (chr < ' ') { if (chr < ' ') {
String t = "000" + Integer.toHexString(chr); final String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4)); builder.append("\\u" + t.substring(t.length() - 4));
} }
else { else {

View File

@ -20,7 +20,7 @@ import com.sk89q.worldedit.regions.CuboidRegion;
public class PWE { public class PWE {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void setMask(Player p, Location l) { public static void setMask(final Player p, final Location l) {
try { try {
LocalSession s; LocalSession s;
if (PlotMain.worldEdit == null) { if (PlotMain.worldEdit == null) {
@ -30,14 +30,12 @@ public class PWE {
s = PlotMain.worldEdit.getSession(p); s = PlotMain.worldEdit.getSession(p);
} }
PlotId id = PlayerFunctions.getPlot(l); final PlotId id = PlayerFunctions.getPlot(l);
if (id != null) { if (id != null) {
Plot plot = PlotMain.getPlots(l.getWorld()).get(id); final Plot plot = PlotMain.getPlots(l.getWorld()).get(id);
if (plot != null) { if (plot != null) {
boolean r; boolean r;
r = r = ((plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId())) || plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId());
(plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId())
|| plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId());
if (!r) { if (!r) {
if (p.hasPermission("plots.worldedit.bypass")) { if (p.hasPermission("plots.worldedit.bypass")) {
removeMask(p, s); removeMask(p, s);
@ -46,41 +44,41 @@ public class PWE {
} }
else { else {
World w = p.getWorld(); final World w = p.getWorld();
Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id); final Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id);
Location tloc = PlotHelper.getPlotTopLoc(w, plot.id); final Location tloc = PlotHelper.getPlotTopLoc(w, plot.id);
Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1); final Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1);
Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ()); final Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ());
LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld(); final LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld();
CuboidRegion region = new CuboidRegion(lw, bvec, tvec); final CuboidRegion region = new CuboidRegion(lw, bvec, tvec);
RegionMask mask = new RegionMask(region); final RegionMask mask = new RegionMask(region);
s.setMask(mask); s.setMask(mask);
return; return;
} }
} }
} }
if (noMask(s)) { if (noMask(s)) {
BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); final BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); final Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69);
s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2)));
} }
} }
catch (Exception e) { catch (final Exception e) {
// throw new // throw new
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?"); // "WorldEdit == Null?");
} }
} }
public static boolean noMask(LocalSession s) { public static boolean noMask(final LocalSession s) {
return s.getMask() == null; return s.getMask() == null;
} }
public static void setNoMask(Player p) { public static void setNoMask(final Player p) {
try { try {
LocalSession s; LocalSession s;
if (PlotMain.worldEdit == null) { if (PlotMain.worldEdit == null) {
@ -89,21 +87,21 @@ public class PWE {
else { else {
s = PlotMain.worldEdit.getSession(p); s = PlotMain.worldEdit.getSession(p);
} }
BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); final BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); final Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69);
s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2)));
} }
catch (Exception e) { catch (final Exception e) {
} }
} }
public static void removeMask(Player p, LocalSession s) { public static void removeMask(final Player p, final LocalSession s) {
Mask mask = null; final Mask mask = null;
s.setMask(mask); s.setMask(mask);
} }
public static void removeMask(Player p) { public static void removeMask(final Player p) {
try { try {
LocalSession s; LocalSession s;
if (PlotMain.worldEdit == null) { if (PlotMain.worldEdit == null) {
@ -114,7 +112,7 @@ public class PWE {
} }
removeMask(p, s); removeMask(p, s);
} }
catch (Exception e) { catch (final Exception e) {
// throw new // throw new
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?"); // "WorldEdit == Null?");

View File

@ -9,12 +9,20 @@
package com.intellectualcrafters.plot; 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.block.Biome;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.*;
/** /**
* Functions involving players, plots and locations. * Functions involving players, plots and locations.
* *
@ -28,7 +36,7 @@ public class PlayerFunctions {
* player * player
* @return * @return
*/ */
public static boolean isInPlot(Player player) { public static boolean isInPlot(final Player player) {
return getCurrentPlot(player) != null; return getCurrentPlot(player) != null;
} }
@ -37,15 +45,15 @@ public class PlayerFunctions {
* plot * plot
* @return * @return
*/ */
public static boolean hasExpired(Plot plot) { public static boolean hasExpired(final Plot plot) {
OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner); final OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner);
long lp = player.getLastPlayed(); final long lp = player.getLastPlayed();
long cu = System.currentTimeMillis(); final long cu = System.currentTimeMillis();
return (lp - cu) > 30l; return (lp - cu) > 30l;
} }
public static ArrayList<PlotId> getPlotSelectionIds(World world, PlotId pos1, PlotId pos2) { public static ArrayList<PlotId> getPlotSelectionIds(final World world, final PlotId pos1, final PlotId pos2) {
ArrayList<PlotId> myplots = new ArrayList<PlotId>(); final ArrayList<PlotId> myplots = new ArrayList<PlotId>();
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.y; y <= pos2.y; y++) {
myplots.add(new PlotId(x, y)); myplots.add(new PlotId(x, y));
@ -54,10 +62,10 @@ public class PlayerFunctions {
return myplots; return myplots;
} }
public static ArrayList<PlotId> getMaxPlotSelectionIds(World world, PlotId pos1, PlotId pos2) { public static ArrayList<PlotId> getMaxPlotSelectionIds(final World world, PlotId pos1, PlotId pos2) {
Plot plot1 = PlotMain.getPlots(world).get(pos1); final Plot plot1 = PlotMain.getPlots(world).get(pos1);
Plot plot2 = PlotMain.getPlots(world).get(pos2); final Plot plot2 = PlotMain.getPlots(world).get(pos2);
if (plot1 != null) { if (plot1 != null) {
pos1 = getBottomPlot(world, plot1).id; pos1 = getBottomPlot(world, plot1).id;
@ -67,7 +75,7 @@ public class PlayerFunctions {
pos2 = getTopPlot(world, plot2).id; pos2 = getTopPlot(world, plot2).id;
} }
ArrayList<PlotId> myplots = new ArrayList<PlotId>(); final ArrayList<PlotId> myplots = new ArrayList<PlotId>();
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.y; y <= pos2.y; y++) {
myplots.add(new PlotId(x, y)); myplots.add(new PlotId(x, y));
@ -76,17 +84,17 @@ public class PlayerFunctions {
return myplots; return myplots;
} }
public static Plot getBottomPlot(World world, Plot plot) { public static Plot getBottomPlot(final World world, final Plot plot) {
if (plot.settings.getMerged(0)) { if (plot.settings.getMerged(0)) {
Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1)); final Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1));
if (p==null) { if (p == null) {
return plot; return plot;
} }
return getBottomPlot(world, p); return getBottomPlot(world, p);
} }
if (plot.settings.getMerged(3)) { if (plot.settings.getMerged(3)) {
Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y)); final Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y));
if (p==null) { if (p == null) {
return plot; return plot;
} }
return getBottomPlot(world, p); return getBottomPlot(world, p);
@ -94,7 +102,7 @@ public class PlayerFunctions {
return plot; return plot;
} }
public static Plot getTopPlot(World world, Plot plot) { public static Plot getTopPlot(final World world, final Plot plot) {
if (plot.settings.getMerged(2)) { if (plot.settings.getMerged(2)) {
return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1))); return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1)));
} }
@ -105,52 +113,54 @@ public class PlayerFunctions {
} }
/** /**
* Returns the plot at a location (mega plots are not considered, all plots are treated as small plots) * Returns the plot at a location (mega plots are not considered, all plots
* are treated as small plots)
*
* @param loc * @param loc
* @return * @return
*/ */
public static PlotId getPlotAbs(Location loc) { public static PlotId getPlotAbs(final Location loc) {
String world = loc.getWorld().getName(); final String world = loc.getWorld().getName();
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
if (manager == null) { if (manager == null) {
return null; return null;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
return manager.getPlotIdAbs(plotworld, loc); return manager.getPlotIdAbs(plotworld, loc);
} }
/** /**
* Returns the plot id at a location (mega plots are considered) * Returns the plot id at a location (mega plots are considered)
*
* @param loc * @param loc
* @return * @return
*/ */
public static PlotId getPlot(Location loc) { public static PlotId getPlot(final Location loc) {
String world = loc.getWorld().getName(); final String world = loc.getWorld().getName();
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
if (manager == null) { if (manager == null) {
return null; return null;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
return manager.getPlotId(plotworld, loc); return manager.getPlotId(plotworld, loc);
} }
/** /**
* Returns the plot a player is currently in. * Returns the plot a player is currently in.
*
* @param player * @param player
* @return * @return
*/ */
public static Plot getCurrentPlot(Player player) { public static Plot getCurrentPlot(final Player player) {
if (!PlotMain.isPlotWorld(player.getWorld())) { if (!PlotMain.isPlotWorld(player.getWorld())) {
return null; return null;
} }
PlotId id = getPlot(player.getLocation()); final PlotId id = getPlot(player.getLocation());
World world = player.getWorld(); final World world = player.getWorld();
if (id == null) { if (id == null) {
return null; return null;
} }
HashMap<PlotId, Plot> plots = PlotMain.getPlots(world); final HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
if (plots != null) { if (plots != null) {
if (plots.containsKey(id)) { if (plots.containsKey(id)) {
return plots.get(id); return plots.get(id);
@ -162,22 +172,24 @@ public class PlayerFunctions {
/** /**
* Updates a given plot with another instance * Updates a given plot with another instance
*
* @deprecated * @deprecated
*
* @param plot * @param plot
*/ */
@Deprecated @Deprecated
public static void set(Plot plot) { public static void set(final Plot plot) {
PlotMain.updatePlot(plot); PlotMain.updatePlot(plot);
} }
/** /**
* Get the plots for a player * Get the plots for a player
*
* @param plr * @param plr
* @return * @return
*/ */
public static Set<Plot> getPlayerPlots(World world, Player plr) { public static Set<Plot> getPlayerPlots(final World world, final Player plr) {
Set<Plot> p = PlotMain.getPlots(world, plr); final Set<Plot> p = PlotMain.getPlots(world, plr);
if (p == null) { if (p == null) {
return new HashSet<Plot>(); return new HashSet<Plot>();
} }
@ -186,13 +198,14 @@ public class PlayerFunctions {
/** /**
* Get the number of plots for a player * Get the number of plots for a player
*
* @param plr * @param plr
* @return * @return
*/ */
public static int getPlayerPlotCount(World world, Player plr) { public static int getPlayerPlotCount(final World world, final Player plr) {
UUID uuid = plr.getUniqueId(); final UUID uuid = plr.getUniqueId();
int count = 0; int count = 0;
for (Plot plot: PlotMain.getPlots(world).values()) { for (final Plot plot : PlotMain.getPlots(world).values()) {
if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) { if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) {
count++; count++;
} }
@ -202,11 +215,12 @@ public class PlayerFunctions {
/** /**
* Get the maximum number of plots a player is allowed * Get the maximum number of plots a player is allowed
*
* @param p * @param p
* @return * @return
*/ */
@SuppressWarnings("SuspiciousNameCombination") @SuppressWarnings("SuspiciousNameCombination")
public static int getAllowedPlots(Player p) { public static int getAllowedPlots(final Player p) {
return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS);
} }
@ -226,7 +240,7 @@ public class PlayerFunctions {
* @param msg * @param msg
* Was used to wrap the chat client length (Packets out--) * Was used to wrap the chat client length (Packets out--)
*/ */
public static void sendMessageWrapped(Player plr, String msg) { public static void sendMessageWrapped(final Player plr, final String msg) {
plr.sendMessage(msg); plr.sendMessage(msg);
} }
@ -238,12 +252,12 @@ public class PlayerFunctions {
* @param msg * @param msg
* Message to send * Message to send
*/ */
public static void sendMessage(Player plr, String msg) { public static void sendMessage(final Player plr, final String msg) {
if ((msg.length() == 0) || msg.equalsIgnoreCase("")) { if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
return; return;
} }
if (plr==null) { if (plr == null) {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg); PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg);
return; return;
} }
@ -259,9 +273,9 @@ public class PlayerFunctions {
* @param c * @param c
* Caption to send * Caption to send
*/ */
public static void sendMessage(Player plr, C c, String... args) { public static void sendMessage(final Player plr, final C c, final String... args) {
if (plr==null) { if (plr == null) {
PlotMain.sendConsoleSenderMessage(c); PlotMain.sendConsoleSenderMessage(c);
return; return;
} }
@ -271,7 +285,7 @@ public class PlayerFunctions {
} }
String msg = c.s(); String msg = c.s();
if ((args != null) && (args.length > 0)) { if ((args != null) && (args.length > 0)) {
for (String str : args) { for (final String str : args) {
msg = msg.replaceFirst("%s", str); msg = msg.replaceFirst("%s", str);
} }
} }

View File

@ -8,14 +8,15 @@
package com.intellectualcrafters.plot; 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.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import com.intellectualcrafters.plot.database.DBFunc;
import java.util.UUID;
/** /**
* The plot class * The plot class
@ -65,7 +66,7 @@ public class Plot implements Cloneable {
* Has the plot changed since the last save cycle? * Has the plot changed since the last save cycle?
*/ */
public boolean hasChanged = false; public boolean hasChanged = false;
public boolean countsTowardsMax = true ; public boolean countsTowardsMax = true;
/** /**
* Primary constructor * Primary constructor
@ -76,7 +77,7 @@ public class Plot implements Cloneable {
* @param helpers * @param helpers
* @param denied * @param denied
*/ */
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, String world) { public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList<UUID> helpers, final ArrayList<UUID> denied, final String world) {
this.id = id; this.id = id;
this.settings = new PlotSettings(this); this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome); this.settings.setBiome(plotBiome);
@ -104,9 +105,7 @@ public class Plot implements Cloneable {
* @param time * @param time
* @param merged * @param merged
*/ */
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> trusted, public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList<UUID> helpers, final ArrayList<UUID> trusted, final ArrayList<UUID> denied, final String alias, final PlotHomePosition position, final Flag[] flags, final String world, final boolean[] merged) {
ArrayList<UUID> denied, String alias,
PlotHomePosition position, Flag[] flags, String world, boolean[] merged) {
this.id = id; this.id = id;
this.settings = new PlotSettings(this); this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome); this.settings.setBiome(plotBiome);
@ -142,7 +141,7 @@ public class Plot implements Cloneable {
* *
* @param player * @param player
*/ */
public void setOwner(Player player) { public void setOwner(final Player player) {
this.owner = player.getUniqueId(); this.owner = player.getUniqueId();
} }
@ -152,12 +151,8 @@ public class Plot implements Cloneable {
* @param player * @param player
* @return true if the player is added as a helper or is the owner * @return true if the player is added as a helper or is the owner
*/ */
public boolean hasRights(Player player) { public boolean hasRights(final Player player) {
return PlotMain.hasPermission(player, "plots.admin") 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)));
|| ((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)));
} }
/** /**
@ -166,9 +161,8 @@ public class Plot implements Cloneable {
* @param player * @param player
* @return false if the player is allowed to enter * @return false if the player is allowed to enter
*/ */
public boolean deny_entry(Player player) { public boolean deny_entry(final Player player) {
return (this.denied != null) return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId())));
&& ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId())));
} }
/** /**
@ -202,7 +196,7 @@ public class Plot implements Cloneable {
try { try {
return super.clone(); return super.clone();
} }
catch (CloneNotSupportedException e) { catch (final CloneNotSupportedException e) {
return null; return null;
} }
} }
@ -212,7 +206,7 @@ public class Plot implements Cloneable {
* *
* @param uuid * @param uuid
*/ */
public void addDenied(UUID uuid) { public void addDenied(final UUID uuid) {
this.denied.add(uuid); this.denied.add(uuid);
} }
@ -221,7 +215,7 @@ public class Plot implements Cloneable {
* *
* @param uuid * @param uuid
*/ */
public void addHelper(UUID uuid) { public void addHelper(final UUID uuid) {
this.helpers.add(uuid); this.helpers.add(uuid);
} }
@ -230,7 +224,7 @@ public class Plot implements Cloneable {
* *
* @param uuid * @param uuid
*/ */
public void addTrusted(UUID uuid) { public void addTrusted(final UUID uuid) {
this.trusted.add(uuid); this.trusted.add(uuid);
} }
@ -251,7 +245,7 @@ public class Plot implements Cloneable {
* *
* @param uuid * @param uuid
*/ */
public void removeDenied(UUID uuid) { public void removeDenied(final UUID uuid) {
this.denied.remove(uuid); this.denied.remove(uuid);
} }
@ -260,7 +254,7 @@ public class Plot implements Cloneable {
* *
* @param uuid * @param uuid
*/ */
public void removeHelper(UUID uuid) { public void removeHelper(final UUID uuid) {
this.helpers.remove(uuid); this.helpers.remove(uuid);
} }
@ -269,7 +263,7 @@ public class Plot implements Cloneable {
* *
* @param uuid * @param uuid
*/ */
public void removeTrusted(UUID uuid) { public void removeTrusted(final UUID uuid) {
this.trusted.remove(uuid); this.trusted.remove(uuid);
} }
@ -279,7 +273,7 @@ public class Plot implements Cloneable {
* @param plr * @param plr
* initiator * initiator
*/ */
public void clear(Player plr) { public void clear(final Player plr) {
PlotHelper.clear(plr, this); PlotHelper.clear(plr, this);
} }

View File

@ -4,7 +4,7 @@ public class PlotBlock {
public short id; public short id;
public byte data; public byte data;
public PlotBlock(short id, byte data) { public PlotBlock(final short id, final byte data) {
this.id = id; this.id = id;
this.data = data; this.data = data;
} }

View File

@ -5,7 +5,7 @@ public class PlotComment {
public final int tier; public final int tier;
public final String senderName; 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.comment = comment;
this.tier = tier; this.tier = tier;
this.senderName = senderName; this.senderName = senderName;

View File

@ -4,11 +4,11 @@ import org.bukkit.generator.ChunkGenerator;
public abstract class PlotGenerator extends ChunkGenerator { public abstract class PlotGenerator extends ChunkGenerator {
public PlotGenerator(String world) { public PlotGenerator(final String world) {
PlotMain.loadWorld(world, this); 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();
} }

View File

@ -8,9 +8,19 @@
package com.intellectualcrafters.plot; 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 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.Biome;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
@ -18,10 +28,7 @@ import org.bukkit.block.Sign;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.io.File; import com.intellectualcrafters.plot.database.DBFunc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
/** /**
* plot functions * plot functions
@ -39,7 +46,7 @@ public class PlotHelper {
* @param direction * @param direction
* @return * @return
*/ */
public static PlotId getPlotIdRelative(PlotId id, int direction) { public static PlotId getPlotIdRelative(final PlotId id, final int direction) {
switch (direction) { switch (direction) {
case 0: case 0:
return new PlotId(id.x, id.y - 1); return new PlotId(id.x, id.y - 1);
@ -55,17 +62,18 @@ public class PlotHelper {
/** /**
* Merges all plots in the arraylist (with cost) * Merges all plots in the arraylist (with cost)
*
* @param plr * @param plr
* @param world * @param world
* @param plotIds * @param plotIds
* @return * @return
*/ */
public static boolean mergePlots(Player plr, World world, ArrayList<PlotId> plotIds) { public static boolean mergePlots(final Player plr, final World world, final ArrayList<PlotId> plotIds) {
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && plotworld.USE_ECONOMY) { if (PlotMain.useEconomy && plotworld.USE_ECONOMY) {
double cost = plotIds.size() * plotworld.MERGE_PRICE; final double cost = plotIds.size() * plotworld.MERGE_PRICE;
if (cost > 0d) { if (cost > 0d) {
Economy economy = PlotMain.economy; final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) { if (economy.getBalance(plr) < cost) {
PlayerFunctions.sendMessage(plr, C.CANNOT_AFFORD_MERGE, "" + cost); PlayerFunctions.sendMessage(plr, C.CANNOT_AFFORD_MERGE, "" + cost);
return false; return false;
@ -91,15 +99,15 @@ public class PlotHelper {
* @param plotIds * @param plotIds
* @return boolean (success) * @return boolean (success)
*/ */
public static boolean mergePlots(World world, ArrayList<PlotId> plotIds) { public static boolean mergePlots(final World world, final ArrayList<PlotId> plotIds) {
if (plotIds.size() < 2) { if (plotIds.size() < 2) {
return false; return false;
} }
PlotId pos1 = plotIds.get(0); final PlotId pos1 = plotIds.get(0);
PlotId pos2 = plotIds.get(plotIds.size() - 1); final PlotId pos2 = plotIds.get(plotIds.size() - 1);
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
manager.startPlotMerge(world, plotworld, plotIds); manager.startPlotMerge(world, plotworld, plotIds);
@ -110,11 +118,11 @@ public class PlotHelper {
boolean changed = false; boolean changed = false;
boolean lx = x < pos2.x; final boolean lx = x < pos2.x;
boolean ly = y < pos2.y; final boolean ly = y < pos2.y;
PlotId id = new PlotId(x, y); final PlotId id = new PlotId(x, y);
Plot plot = PlotMain.getPlots(world).get(id); final Plot plot = PlotMain.getPlots(world).get(id);
Plot plot2 = null; Plot plot2 = null;
if (lx) { if (lx) {
@ -144,7 +152,7 @@ public class PlotHelper {
if (changed) { if (changed) {
result = true; result = true;
DBFunc.setMerged(world.getName(), plot, plot.settings.getMerged()); DBFunc.setMerged(world.getName(), plot, plot.settings.getMerged());
if (plot2!=null) { if (plot2 != null) {
DBFunc.setMerged(world.getName(), plot2, plot2.settings.getMerged()); DBFunc.setMerged(world.getName(), plot2, plot2.settings.getMerged());
} }
} }
@ -166,9 +174,9 @@ public class PlotHelper {
* @param lesserPlot * @param lesserPlot
* @param greaterPlot * @param greaterPlot
*/ */
public static void mergePlot(World world, Plot lesserPlot, Plot greaterPlot) { public static void mergePlot(final World world, final Plot lesserPlot, final Plot greaterPlot) {
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
if (lesserPlot.id.x == greaterPlot.id.x) { if (lesserPlot.id.x == greaterPlot.id.x) {
if (!lesserPlot.settings.getMerged(2)) { if (!lesserPlot.settings.getMerged(2)) {
@ -190,7 +198,7 @@ public class PlotHelper {
* Random number gen section * Random number gen section
*/ */
public static final long nextLong() { public static final long nextLong() {
long a = state; final long a = state;
state = xorShift64(a); state = xorShift64(a);
return a; return a;
} }
@ -202,39 +210,40 @@ public class PlotHelper {
return a; return a;
} }
public static final int random(int n) { public static final int random(final int n) {
if (n == 1) { if (n == 1) {
return 0; return 0;
} }
long r = ((nextLong() >>> 32) * n) >> 32; final long r = ((nextLong() >>> 32) * n) >> 32;
return (int) r; return (int) r;
} }
/* /*
* End of random number gen section * End of random number gen section
*/ */
public static void removeSign(World world, Plot p) { public static void removeSign(final World world, final Plot p) {
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
Location loc = manager.getSignLoc(world, plotworld, p); final Location loc = manager.getSignLoc(world, plotworld, p);
Block bs = loc.getBlock(); final Block bs = loc.getBlock();
bs.setType(Material.AIR); bs.setType(Material.AIR);
} }
public static void setSign(Player player, Plot p) { public static void setSign(final Player player, final Plot p) {
setSign(player.getWorld(), player.getName(), p); setSign(player.getWorld(), player.getName(), p);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void setSign(World world, String name, Plot p) { public static void setSign(final World world, final String name, final Plot p) {
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
Location loc = manager.getSignLoc(world, plotworld, p); final Location loc = manager.getSignLoc(world, plotworld, p);
Block bs = loc.getBlock(); final Block bs = loc.getBlock();
bs.setType(Material.AIR); bs.setType(Material.AIR);
bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
String id = p.id.x + ";" + p.id.y; final String id = p.id.x + ";" + p.id.y;
Sign sign = (Sign) bs.getState(); final Sign sign = (Sign) bs.getState();
sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id)); 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(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(2, C.OWNER_SIGN_LINE_3.translated().replaceAll("%id%", id).replaceAll("%plr%", name));
@ -242,19 +251,18 @@ public class PlotHelper {
sign.update(true); sign.update(true);
} }
public static String getPlayerName(final UUID uuid) {
public static String getPlayerName(UUID uuid) {
if (uuid == null) { if (uuid == null) {
return "unknown"; return "unknown";
} }
OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); final OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid);
if (plr == null) { if (plr == null) {
return "unknown"; return "unknown";
} }
return plr.getName(); return plr.getName();
} }
public static String getStringSized(int max, String string) { public static String getStringSized(final int max, final String string) {
if (string.length() > max) { if (string.length() > max) {
return string.substring(0, max); return string.substring(0, max);
} }
@ -263,18 +271,19 @@ public class PlotHelper {
/** /**
* Set a block quickly, attempts to use NMS if possible * Set a block quickly, attempts to use NMS if possible
*
* @param block * @param block
* @param plotblock * @param plotblock
*/ */
public static boolean setBlock(Block block, PlotBlock plotblock) { public static boolean setBlock(final Block block, final PlotBlock plotblock) {
if (canSetFast) { if (canSetFast) {
if (block.getTypeId() != plotblock.id || plotblock.data != block.getData()) { if ((block.getTypeId() != plotblock.id) || (plotblock.data != block.getData())) {
try { try {
SetBlockFast.set(block.getWorld(), block.getX(), block.getY(), block.getZ(), plotblock.id, plotblock.data); SetBlockFast.set(block.getWorld(), block.getX(), block.getY(), block.getZ(), plotblock.id, plotblock.data);
return true; return true;
} }
catch (Throwable e) { catch (final Throwable e) {
canSetFast = false; canSetFast = false;
} }
} }
@ -298,19 +307,20 @@ public class PlotHelper {
/** /**
* Adjusts a plot wall * Adjusts a plot wall
*
* @param player * @param player
* @param plot * @param plot
* @param block * @param block
*/ */
public static void adjustWall(Player player, Plot plot, PlotBlock block) { public static void adjustWall(final Player player, final Plot plot, final PlotBlock block) {
World world = player.getWorld(); final World world = player.getWorld();
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
manager.setWall(world, plotworld, plot.id, block); manager.setWall(world, plotworld, plot.id, block);
} }
public static void autoMerge(World world, Plot plot, Player player) { public static void autoMerge(final World world, final Plot plot, final Player player) {
if (plot == null) { if (plot == null) {
return; return;
} }
@ -325,16 +335,16 @@ public class PlotHelper {
boolean merge = true; boolean merge = true;
int count = 0; int count = 0;
while (merge) { while (merge) {
if (count>16) { if (count > 16) {
break; break;
} }
count++; count++;
PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; final PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id;
PlotId top = PlayerFunctions.getTopPlot(world, plot).id; final PlotId top = PlayerFunctions.getTopPlot(world, plot).id;
merge = false; merge = false;
plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
if (ownsPlots(world, plots, player, 0)) { if (ownsPlots(world, plots, player, 0)) {
boolean result = mergePlots(world, plots); final boolean result = mergePlots(world, plots);
if (result) { if (result) {
merge = true; merge = true;
continue; continue;
@ -342,7 +352,7 @@ public class PlotHelper {
} }
plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
if (ownsPlots(world, plots, player, 1)) { if (ownsPlots(world, plots, player, 1)) {
boolean result = mergePlots(world, plots); final boolean result = mergePlots(world, plots);
if (result) { if (result) {
merge = true; merge = true;
continue; continue;
@ -350,7 +360,7 @@ public class PlotHelper {
} }
plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
if (ownsPlots(world, plots, player, 2)) { if (ownsPlots(world, plots, player, 2)) {
boolean result = mergePlots(world, plots); final boolean result = mergePlots(world, plots);
if (result) { if (result) {
merge = true; merge = true;
continue; continue;
@ -358,7 +368,7 @@ public class PlotHelper {
} }
plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
if (ownsPlots(world, plots, player, 3)) { if (ownsPlots(world, plots, player, 3)) {
boolean result = mergePlots(world, plots); final boolean result = mergePlots(world, plots);
if (result) { if (result) {
merge = true; merge = true;
continue; continue;
@ -371,19 +381,19 @@ public class PlotHelper {
} }
} }
private static boolean ownsPlots(World world, ArrayList<PlotId> plots, Player player, int dir) { private static boolean ownsPlots(final World world, final ArrayList<PlotId> plots, final Player player, final int dir) {
PlotId id_min = plots.get(0); final PlotId id_min = plots.get(0);
PlotId id_max = plots.get(plots.size() - 1); final PlotId id_max = plots.get(plots.size() - 1);
for (PlotId myid : plots) { for (final PlotId myid : plots) {
Plot myplot = PlotMain.getPlots(world).get(myid); final Plot myplot = PlotMain.getPlots(world).get(myid);
if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(player.getUniqueId()))) { if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(player.getUniqueId()))) {
return false; return false;
} }
PlotId top = PlayerFunctions.getTopPlot(world, myplot).id; final PlotId top = PlayerFunctions.getTopPlot(world, myplot).id;
if (((top.x > id_max.x) && (dir != 1)) || ((top.y > id_max.y) && (dir != 2))) { if (((top.x > id_max.x) && (dir != 1)) || ((top.y > id_max.y) && (dir != 2))) {
return false; return false;
} }
PlotId bot = PlayerFunctions.getBottomPlot(world, myplot).id; final PlotId bot = PlayerFunctions.getBottomPlot(world, myplot).id;
if (((bot.x < id_min.x) && (dir != 3)) || ((bot.y < id_min.y) && (dir != 0))) { if (((bot.x < id_min.x) && (dir != 3)) || ((bot.y < id_min.y) && (dir != 0))) {
return false; return false;
} }
@ -391,13 +401,13 @@ public class PlotHelper {
return true; return true;
} }
public static boolean createPlot(Player player, Plot plot) { public static boolean createPlot(final Player player, final Plot plot) {
World w = plot.getWorld(); final World w = plot.getWorld();
Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), new ArrayList<UUID>(), new ArrayList<UUID>(), w.getName()); final Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), new ArrayList<UUID>(), new ArrayList<UUID>(), w.getName());
PlotMain.updatePlot(p); PlotMain.updatePlot(p);
DBFunc.createPlot(p); DBFunc.createPlot(p);
DBFunc.createPlotSettings(DBFunc.getId(w.getName(), plot.id), plot); DBFunc.createPlotSettings(DBFunc.getId(w.getName(), plot.id), plot);
PlotWorld plotworld = PlotMain.getWorldSettings(w); final PlotWorld plotworld = PlotMain.getWorldSettings(w);
if (plotworld.AUTO_MERGE) { if (plotworld.AUTO_MERGE) {
autoMerge(w, p, player); autoMerge(w, p, player);
} }
@ -405,27 +415,27 @@ public class PlotHelper {
return true; return true;
} }
public static int getLoadedChunks(World world) { public static int getLoadedChunks(final World world) {
return world.getLoadedChunks().length; return world.getLoadedChunks().length;
} }
public static int getEntities(World world) { public static int getEntities(final World world) {
return world.getEntities().size(); return world.getEntities().size();
} }
public static int getTileEntities(World world) { public static int getTileEntities(final World world) {
PlotMain.getWorldSettings(world); PlotMain.getWorldSettings(world);
int x = 0; int x = 0;
for (Chunk chunk : world.getLoadedChunks()) { for (final Chunk chunk : world.getLoadedChunks()) {
x += chunk.getTileEntities().length; x += chunk.getTileEntities().length;
} }
return x; return x;
} }
public static double getWorldFolderSize(World world) { public static double getWorldFolderSize(final World world) {
// long size = FileUtil.sizeOfDirectory(world.getWorldFolder()); // long size = FileUtil.sizeOfDirectory(world.getWorldFolder());
File folder = world.getWorldFolder(); final File folder = world.getWorldFolder();
long size = folder.length(); final long size = folder.length();
return (((size) / 1024) / 1024); return (((size) / 1024) / 1024);
} }
@ -585,21 +595,21 @@ public class PlotHelper {
// } // }
// } // }
public static String createId(int x, int z) { public static String createId(final int x, final int z) {
return x + ";" + z; return x + ";" + z;
} }
public static ArrayList<String> runners_p = new ArrayList<String>(); public static ArrayList<String> runners_p = new ArrayList<String>();
public static HashMap<Plot, Integer> runners = new HashMap<Plot, Integer>(); public static HashMap<Plot, Integer> runners = new HashMap<Plot, Integer>();
public static void adjustWallFilling(final Player requester, final Plot plot, PlotBlock block) { public static void adjustWallFilling(final Player requester, final Plot plot, final PlotBlock block) {
if (runners.containsKey(plot)) { if (runners.containsKey(plot)) {
PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER);
return; return;
} }
World world = requester.getWorld(); final World world = requester.getWorld();
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
manager.setWallFilling(world, plotworld, plot.id, block); manager.setWallFilling(world, plotworld, plot.id, block);
PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED);
if (canSetFast) { if (canSetFast) {
@ -607,15 +617,15 @@ public class PlotHelper {
} }
} }
public static void setFloor(final Player requester, final Plot plot, PlotBlock[] blocks) { public static void setFloor(final Player requester, final Plot plot, final PlotBlock[] blocks) {
if (runners.containsKey(plot)) { if (runners.containsKey(plot)) {
PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER);
return; return;
} }
World world = requester.getWorld(); final World world = requester.getWorld();
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED);
manager.setFloor(world, plotworld, plot.id, blocks); manager.setFloor(world, plotworld, plot.id, blocks);
if (canSetFast) { if (canSetFast) {
@ -623,26 +633,26 @@ public class PlotHelper {
} }
} }
public static int square(int x) { public static int square(final int x) {
return x * x; return x * x;
} }
public static short[] getBlock(String block) { public static short[] getBlock(final String block) {
if (block.contains(":")) { if (block.contains(":")) {
String[] split = block.split(":"); final String[] split = block.split(":");
return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) };
} }
return new short[] { Short.parseShort(block), 0 }; return new short[] { Short.parseShort(block), 0 };
} }
public static void clearAllEntities(World world, Plot plot, boolean tile) { 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 pos1 = getPlotBottomLoc(world, plot.id).add(1, 0, 1);
final Location pos2 = getPlotTopLoc(world, plot.id); final Location pos2 = getPlotTopLoc(world, plot.id);
for (int i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { 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) { for (int j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) {
Chunk chunk = world.getChunkAt(i, j); final Chunk chunk = world.getChunkAt(i, j);
for (Entity entity : chunk.getEntities()) { for (final Entity entity : chunk.getEntities()) {
PlotId id = PlayerFunctions.getPlot(entity.getLocation()); final PlotId id = PlayerFunctions.getPlot(entity.getLocation());
if ((id != null) && id.equals(plot.id)) { if ((id != null) && id.equals(plot.id)) {
if (entity instanceof Player) { if (entity instanceof Player) {
PlotMain.teleportPlayer((Player) entity, entity.getLocation(), plot); PlotMain.teleportPlayer((Player) entity, entity.getLocation(), plot);
@ -653,17 +663,18 @@ public class PlotHelper {
} }
} }
if (tile) { if (tile) {
for (BlockState entity : chunk.getTileEntities()) { for (final BlockState entity : chunk.getTileEntities()) {
entity.setRawData((byte) 0); entity.setRawData((byte) 0);
} }
} }
} }
} }
} }
public static void clear(final World world, final Plot plot) {
PlotManager manager = PlotMain.getPlotManager(world);
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; final int prime = 31;
int h = 1; int h = 1;
@ -681,7 +692,6 @@ public class PlotHelper {
} }
} }
/** /**
* Clear a plot * Clear a plot
* *
@ -699,7 +709,7 @@ public class PlotHelper {
final long start = System.nanoTime(); final long start = System.nanoTime();
final World world; final World world;
if (requester!=null) { if (requester != null) {
world = requester.getWorld(); world = requester.getWorld();
} }
else { else {
@ -712,20 +722,19 @@ public class PlotHelper {
clearAllEntities(world, plot, false); clearAllEntities(world, plot, false);
clear(world, plot); clear(world, plot);
removeSign(world, plot); removeSign(world, plot);
PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0)));
+ ((System.nanoTime() - start) / 1000000.0)));
return; return;
} }
public static void setCuboid(World world, Location pos1, Location pos2, PlotBlock[] blocks) { public static void setCuboid(final World world, final Location pos1, final Location pos2, final PlotBlock[] blocks) {
if (!canSetFast) { if (!canSetFast) {
for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) {
for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) {
int i = random(blocks.length); final int i = random(blocks.length);
PlotBlock newblock = blocks[i]; final PlotBlock newblock = blocks[i];
Block block = world.getBlockAt(x, y, z); final Block block = world.getBlockAt(x, y, z);
if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) {
block.setTypeIdAndData(newblock.id, newblock.data, false); block.setTypeIdAndData(newblock.id, newblock.data, false);
} }
@ -738,9 +747,9 @@ public class PlotHelper {
for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) {
for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) {
int i = random(blocks.length); final int i = random(blocks.length);
PlotBlock newblock = blocks[i]; final PlotBlock newblock = blocks[i];
Block block = world.getBlockAt(x, y, z); final Block block = world.getBlockAt(x, y, z);
if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) {
SetBlockFast.set(world, x, y, z, newblock.id, newblock.data); SetBlockFast.set(world, x, y, z, newblock.id, newblock.data);
} }
@ -748,17 +757,17 @@ public class PlotHelper {
} }
} }
} }
catch (Exception e) { catch (final Exception e) {
} }
} }
} }
public static void setSimpleCuboid(World world, Location pos1, Location pos2, PlotBlock newblock) { public static void setSimpleCuboid(final World world, final Location pos1, final Location pos2, final PlotBlock newblock) {
if (!canSetFast) { if (!canSetFast) {
for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) {
for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) {
Block block = world.getBlockAt(x, y, z); final Block block = world.getBlockAt(x, y, z);
if (!((block.getTypeId() == newblock.id))) { if (!((block.getTypeId() == newblock.id))) {
block.setTypeId(newblock.id, false); block.setTypeId(newblock.id, false);
} }
@ -771,7 +780,7 @@ public class PlotHelper {
for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) {
for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) {
Block block = world.getBlockAt(x, y, z); final Block block = world.getBlockAt(x, y, z);
if (!((block.getTypeId() == newblock.id))) { if (!((block.getTypeId() == newblock.id))) {
SetBlockFast.set(world, x, y, z, newblock.id, (byte) 0); SetBlockFast.set(world, x, y, z, newblock.id, (byte) 0);
} }
@ -779,17 +788,17 @@ public class PlotHelper {
} }
} }
} }
catch (Exception e) { catch (final Exception e) {
} }
} }
} }
public static void setBiome(World world, Plot plot, Biome b) { public static void setBiome(final World world, final Plot plot, final Biome b) {
int bottomX = getPlotBottomLoc(world, plot.id).getBlockX() - 1; final int bottomX = getPlotBottomLoc(world, plot.id).getBlockX() - 1;
int topX = getPlotTopLoc(world, plot.id).getBlockX() + 1; final int topX = getPlotTopLoc(world, plot.id).getBlockX() + 1;
int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ() - 1; final int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ() - 1;
int topZ = getPlotTopLoc(world, plot.id).getBlockZ() + 1; final int topZ = getPlotTopLoc(world, plot.id).getBlockZ() + 1;
for (int x = bottomX; x <= topX; x++) { for (int x = bottomX; x <= topX; x++) {
for (int z = bottomZ; z <= topZ; z++) { for (int z = bottomZ; z <= topZ; z++) {
@ -801,13 +810,14 @@ public class PlotHelper {
PlotMain.updatePlot(plot); PlotMain.updatePlot(plot);
refreshPlotChunks(world, plot); refreshPlotChunks(world, plot);
} }
public static int getHeighestBlock(World world, int x, int z) {
public static int getHeighestBlock(final World world, final int x, final int z) {
boolean safe = false; boolean safe = false;
for (int i = 1; i<world.getMaxHeight(); i++) { for (int i = 1; i < world.getMaxHeight(); i++) {
int id = world.getBlockAt(x,i,z).getTypeId(); final int id = world.getBlockAt(x, i, z).getTypeId();
if (id==0) { if (id == 0) {
if (safe) { if (safe) {
return i-1; return i - 1;
} }
safe = true; safe = true;
} }
@ -815,42 +825,40 @@ public class PlotHelper {
return 64; return 64;
} }
public static Location getPlotHome(World w, PlotId plotid) { public static Location getPlotHome(final World w, final PlotId plotid) {
if (getPlot(w, plotid).settings.getPosition() == PlotHomePosition.DEFAULT) { if (getPlot(w, plotid).settings.getPosition() == PlotHomePosition.DEFAULT) {
Location bot = getPlotBottomLoc(w, plotid); final Location bot = getPlotBottomLoc(w, plotid);
int x = bot.getBlockX(); final int x = bot.getBlockX();
int z = bot.getBlockZ() - 2; final int z = bot.getBlockZ() - 2;
int y = getHeighestBlock(w, x, z); final int y = getHeighestBlock(w, x, z);
return new Location(w, x, y, z); return new Location(w, x, y, z);
} }
else { else {
Location final Location bot = getPlotBottomLoc(w, plotid), top = getPlotTopLoc(w, plotid);
bot = getPlotBottomLoc(w, plotid), final int x = top.getBlockX() - bot.getBlockX();
top = getPlotTopLoc(w, plotid); final int z = top.getBlockZ() - bot.getBlockZ();
int x = top.getBlockX() - bot.getBlockX(); final int y = getHeighestBlock(w, x, z);
int z = top.getBlockZ() - bot.getBlockZ(); return new Location(w, bot.getBlockX() + (x / 2), y, bot.getBlockZ() + (z / 2));
int y = getHeighestBlock(w, x, z);
return new Location(w, bot.getBlockX() + x/2, y, bot.getBlockZ() + z/2);
} }
} }
public static Location getPlotHome(World w, Plot plot) { public static Location getPlotHome(final World w, final Plot plot) {
return getPlotHome(w, plot.id); return getPlotHome(w, plot.id);
} }
public static void refreshPlotChunks(World world, Plot plot) { public static void refreshPlotChunks(final World world, final Plot plot) {
int bottomX = getPlotBottomLoc(world, plot.id).getBlockX(); final int bottomX = getPlotBottomLoc(world, plot.id).getBlockX();
int topX = getPlotTopLoc(world, plot.id).getBlockX(); final int topX = getPlotTopLoc(world, plot.id).getBlockX();
int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ(); final int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ();
int topZ = getPlotTopLoc(world, plot.id).getBlockZ(); final int topZ = getPlotTopLoc(world, plot.id).getBlockZ();
int minChunkX = (int) Math.floor((double) bottomX / 16); final int minChunkX = (int) Math.floor((double) bottomX / 16);
int maxChunkX = (int) Math.floor((double) topX / 16); final int maxChunkX = (int) Math.floor((double) topX / 16);
int minChunkZ = (int) Math.floor((double) bottomZ / 16); final int minChunkZ = (int) Math.floor((double) bottomZ / 16);
int maxChunkZ = (int) Math.floor((double) topZ / 16); final int maxChunkZ = (int) Math.floor((double) topZ / 16);
for (int x = minChunkX; x <= maxChunkX; x++) { for (int x = minChunkX; x <= maxChunkX; x++) {
for (int z = minChunkZ; z <= maxChunkZ; z++) { for (int z = minChunkZ; z <= maxChunkZ; z++) {
@ -860,82 +868,93 @@ public class PlotHelper {
} }
/** /**
* Gets the top plot location of a plot (all plots are treated as small plots) * Gets the top plot location of a plot (all plots are treated as small
* plots)
* - To get the top loc of a mega plot use getPlotTopLoc(...) * - To get the top loc of a mega plot use getPlotTopLoc(...)
*
* @param world * @param world
* @param id * @param id
* @return * @return
*/ */
public static Location getPlotTopLocAbs(World world, PlotId id) { public static Location getPlotTopLocAbs(final World world, final PlotId id) {
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
return manager.getPlotTopLocAbs(plotworld, id); return manager.getPlotTopLocAbs(plotworld, id);
} }
/** /**
* Gets the bottom plot location of a plot (all plots are treated as small plots) * Gets the bottom plot location of a plot (all plots are treated as small
* plots)
* - To get the top loc of a mega plot use getPlotBottomLoc(...) * - To get the top loc of a mega plot use getPlotBottomLoc(...)
*
* @param world * @param world
* @param id * @param id
* @return * @return
*/ */
public static Location getPlotBottomLocAbs(World world, PlotId id) { public static Location getPlotBottomLocAbs(final World world, final PlotId id) {
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
return manager.getPlotBottomLocAbs(plotworld, id); return manager.getPlotBottomLocAbs(plotworld, id);
} }
/** /**
* Obtains the width of a plot (x width) * Obtains the width of a plot (x width)
*
* @param world * @param world
* @param id * @param id
* @return * @return
*/ */
public static int getPlotWidth(World world, PlotId id) { public static int getPlotWidth(final World world, final PlotId id) {
return getPlotTopLoc(world, id).getBlockX() - getPlotBottomLoc(world, id).getBlockX(); return getPlotTopLoc(world, id).getBlockX() - getPlotBottomLoc(world, id).getBlockX();
} }
/** /**
* Gets the top loc of a plot (if mega, returns top loc of that mega plot) * Gets the top loc of a plot (if mega, returns top loc of that mega plot)
* - If you would like each plot treated as a small plot use getPlotTopLocAbs(...) * - If you would like each plot treated as a small plot use
* getPlotTopLocAbs(...)
*
* @param world * @param world
* @param id * @param id
* @return * @return
*/ */
public static Location getPlotTopLoc(World world, PlotId id) { public static Location getPlotTopLoc(final World world, PlotId id) {
Plot plot = PlotMain.getPlots(world).get(id); final Plot plot = PlotMain.getPlots(world).get(id);
if (plot != null) { if (plot != null) {
id = PlayerFunctions.getTopPlot(world, plot).id; id = PlayerFunctions.getTopPlot(world, plot).id;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
return manager.getPlotTopLocAbs(plotworld, id); return manager.getPlotTopLocAbs(plotworld, id);
} }
/** /**
* Gets the bottom loc of a plot (if mega, returns bottom loc of that mega plot) * Gets the bottom loc of a plot (if mega, returns bottom loc of that mega
* - If you would like each plot treated as a small plot use getPlotBottomLocAbs(...) * plot)
* - If you would like each plot treated as a small plot use
* getPlotBottomLocAbs(...)
*
* @param world * @param world
* @param id * @param id
* @return * @return
*/ */
public static Location getPlotBottomLoc(World world, PlotId id) { public static Location getPlotBottomLoc(final World world, PlotId id) {
Plot plot = PlotMain.getPlots(world).get(id); final Plot plot = PlotMain.getPlots(world).get(id);
if (plot != null) { if (plot != null) {
id = PlayerFunctions.getBottomPlot(world, plot).id; id = PlayerFunctions.getBottomPlot(world, plot).id;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
PlotManager manager = PlotMain.getPlotManager(world); final PlotManager manager = PlotMain.getPlotManager(world);
return manager.getPlotBottomLocAbs(plotworld, id); return manager.getPlotBottomLocAbs(plotworld, id);
} }
/** /**
* Fetches the plot from the main class * Fetches the plot from the main class
*
* @param world * @param world
* @param id * @param id
* @return * @return
*/ */
public static Plot getPlot(World world, PlotId id) { public static Plot getPlot(final World world, final PlotId id) {
if (id == null) { if (id == null) {
return null; return null;
} }
@ -947,11 +966,12 @@ public class PlotHelper {
/** /**
* Returns the plot at a given location * Returns the plot at a given location
*
* @param loc * @param loc
* @return * @return
*/ */
public static Plot getCurrentPlot(Location loc) { public static Plot getCurrentPlot(final Location loc) {
PlotId id = PlayerFunctions.getPlot(loc); final PlotId id = PlayerFunctions.getPlot(loc);
if (id == null) { if (id == null) {
return null; return null;
} }

View File

@ -19,12 +19,12 @@ public enum PlotHomePosition {
private String string; private String string;
private char ch; private char ch;
PlotHomePosition(String string, char ch) { PlotHomePosition(final String string, final char ch) {
this.string = string; this.string = string;
this.ch = ch; this.ch = ch;
} }
public boolean isMatching(String string) { public boolean isMatching(final String string) {
if ((string.length() < 2) && (string.charAt(0) == this.ch)) { if ((string.length() < 2) && (string.charAt(0) == this.ch)) {
return true; return true;
} }

View File

@ -18,13 +18,13 @@ public class PlotId {
* @param y * @param y
* The plot y coordinate * The plot y coordinate
*/ */
public PlotId(int x, int y) { public PlotId(final int x, final int y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -34,8 +34,8 @@ public class PlotId {
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
PlotId other = (PlotId) obj; final PlotId other = (PlotId) obj;
return (((int) this.x == (int) other.x) && ((int) this.y == (int) other.y)); return ((this.x == other.x) && (this.y == other.y));
} }
@Override @Override

View File

@ -5,7 +5,6 @@ import java.util.ArrayList;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
public abstract class PlotManager { public abstract class PlotManager {
@ -14,61 +13,61 @@ public abstract class PlotManager {
* plots) * 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 // If you have a circular plot, just return the corner if it were a square
public abstract Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid); public abstract Location getPlotBottomLocAbs(final PlotWorld plotworld, final PlotId plotid);
// the same applies here // the same applies here
public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid); 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 * Plot set functions (return false if you do not support the specific set
* method) * method)
*/ */
public abstract boolean setWallFilling(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 setWall(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 setFloor(World world, PlotWorld plotworld, PlotId plotid, PlotBlock[] block); public abstract boolean setFloor(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 setBiome(final World world, final Plot plot, final Biome biome);
/* /*
* PLOT MERGING (return false if your generator does not support plot * PLOT MERGING (return false if your generator does not support plot
* merging) * merging)
*/ */
public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot); public abstract boolean createRoadEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot); public abstract boolean createRoadSouth(final PlotWorld plotworld, final Plot plot);
public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot); public abstract boolean createRoadSouthEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot); public abstract boolean removeRoadEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot); public abstract boolean removeRoadSouth(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot); public abstract boolean removeRoadSouthEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean startPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds); public abstract boolean startPlotMerge(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean startPlotUnlink(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds); public abstract boolean startPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds); public abstract boolean finishPlotMerge(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean finishPlotUnlink(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds); public abstract boolean finishPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
} }

View File

@ -1,17 +1,11 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.Chunk; import java.util.HashMap;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.block.Block; 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. * Created by Citymonstret on 2014-10-12.
@ -20,30 +14,22 @@ public class PlotSelection {
public static HashMap<String, PlotSelection> currentSelection = new HashMap<>(); public static HashMap<String, PlotSelection> currentSelection = new HashMap<>();
private PlotBlock[] plotBlocks; private final PlotBlock[] plotBlocks;
private int width; private final int width;
private Plot plot; private final Plot plot;
private Biome biome; private final Biome biome;
public PlotSelection(int width, World world, Plot plot) { public PlotSelection(final int width, final World world, final Plot plot) {
this.width = width; this.width = width;
this.plot = plot; this.plot = plot;
plotBlocks = new PlotBlock[(width * width) * (world.getMaxHeight() - 1)]; this.plotBlocks = new PlotBlock[(width * width) * (world.getMaxHeight() - 1)];
Location final Location bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), top = PlotHelper.getPlotTopLocAbs(world, plot.getId());
bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), final int minX = bot.getBlockX(), maxX = top.getBlockX(), minZ = bot.getBlockZ(), maxZ = top.getBlockZ(), minY = 1, maxY = world.getMaxHeight();
top = PlotHelper.getPlotTopLocAbs(world, plot.getId());
int
minX = bot.getBlockX(),
maxX = top.getBlockX(),
minZ = bot.getBlockZ(),
maxZ = top.getBlockZ(),
minY = 1,
maxY = world.getMaxHeight();
Block current; Block current;
this.biome = world.getBiome(minX, minZ); this.biome = world.getBiome(minX, minZ);
@ -53,70 +39,60 @@ public class PlotSelection {
for (int z = minZ; z < maxZ; z++) { for (int z = minZ; z < maxZ; z++) {
for (int y = minY; y < maxY; y++) { for (int y = minY; y < maxY; y++) {
current = world.getBlockAt(x + 1, y, z + 1); current = world.getBlockAt(x + 1, y, z + 1);
plotBlocks[index++] = new PlotBlock( this.plotBlocks[index++] = new PlotBlock((short) current.getTypeId(), current.getData());
(short) current.getTypeId(),
current.getData()
);
} }
} }
} }
// Yay :D
//Yay :D
} }
public PlotBlock[] getBlocks() { public PlotBlock[] getBlocks() {
return plotBlocks; return this.plotBlocks;
} }
public int getWidth() { public int getWidth() {
return width; return this.width;
} }
public Plot getPlot() { public Plot getPlot() {
return plot; return this.plot;
} }
public static boolean swap(World world, PlotId id1, PlotId id2) { public static boolean swap(final World world, final PlotId id1, final PlotId id2) {
Location bot2 = PlotHelper.getPlotBottomLocAbs(world, id2).add(1, 0, 1); final Location bot2 = PlotHelper.getPlotBottomLocAbs(world, id2).add(1, 0, 1);
Location bot1 = PlotHelper.getPlotBottomLocAbs(world, id1).add(1, 0, 1); final Location bot1 = PlotHelper.getPlotBottomLocAbs(world, id1).add(1, 0, 1);
Location top1 = PlotHelper.getPlotTopLocAbs(world, id1); final Location top1 = PlotHelper.getPlotTopLocAbs(world, id1);
int final int minX = bot1.getBlockX(), maxX = top1.getBlockX(), minZ = bot1.getBlockZ(), maxZ = top1.getBlockZ(),
minX = bot1.getBlockX(),
maxX = top1.getBlockX(),
minZ = bot1.getBlockZ(),
maxZ = top1.getBlockZ(),
minX2 = bot2.getBlockX(), minX2 = bot2.getBlockX(), minZ2 = bot2.getBlockZ();
minZ2 = bot2.getBlockZ();
boolean canSetFast = PlotHelper.canSetFast; final boolean canSetFast = PlotHelper.canSetFast;
for (int x = 0; x <= maxX - minX; x++) { for (int x = 0; x <= (maxX - minX); x++) {
for (int z = 0; z <= maxZ - minZ; z++) { for (int z = 0; z <= (maxZ - minZ); z++) {
for (int y = 1; y <= world.getMaxHeight(); y++) { for (int y = 1; y <= world.getMaxHeight(); y++) {
final Block block1 = world.getBlockAt(x + minX, y, z + minZ); final Block block1 = world.getBlockAt(x + minX, y, z + minZ);
final Block block2 = world.getBlockAt(x + minX2, y, z + minZ2); final Block block2 = world.getBlockAt(x + minX2, y, z + minZ2);
final BlockWrapper b1 = wrapBlock(block1); final BlockWrapper b1 = wrapBlock(block1);
final BlockWrapper b2 = wrapBlock(block2); 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) { if (canSetFast) {
try { try {
SetBlockFast.set(world, b1.x, b1.y, b1.z, b2.id, b2.data); 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); SetBlockFast.set(world, b2.x, b2.y, b2.z, b1.id, b1.data);
} catch (NoSuchMethodException e) { }
catch (final NoSuchMethodException e) {
PlotHelper.canSetFast = false; PlotHelper.canSetFast = false;
} }
} }
else { 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); block1.setTypeIdAndData(b2.id, b2.data, false);
block2.setTypeIdAndData(b1.id, b1.data, false); block2.setTypeIdAndData(b1.id, b1.data, false);
} }
@ -136,23 +112,14 @@ public class PlotSelection {
return true; 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()); return new BlockWrapper(block.getX(), block.getY(), block.getZ(), (short) block.getTypeId(), block.getData());
} }
public void paste(World world, Plot plot) { public void paste(final World world, final Plot plot) {
final Location bot = PlotHelper.getPlotBottomLocAbs(world, plot.getId()), top = PlotHelper.getPlotTopLocAbs(world, plot.getId());
Location final int minX = bot.getBlockX(), maxX = top.getBlockX(), minZ = bot.getBlockZ(), maxZ = top.getBlockZ(), minY = 1, maxY = world.getMaxHeight();
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();
if (this.biome != world.getBiome(minX, minZ)) { if (this.biome != world.getBiome(minX, minZ)) {
PlotHelper.setBiome(world, plot, this.biome); PlotHelper.setBiome(world, plot, this.biome);
@ -163,7 +130,7 @@ public class PlotSelection {
for (int x = minX; x < maxX; x++) { for (int x = minX; x < maxX; x++) {
for (int z = minZ; z < maxZ; z++) { for (int z = minZ; z < maxZ; z++) {
for (int y = minY; y < maxY; y++) { 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); world.getBlockAt(x + 1, y, z + 1).setTypeIdAndData(current.id, current.data, true);
} }
} }

View File

@ -8,15 +8,13 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.database.DBFunc;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.bukkit.block.Biome;
/** /**
* plot settings * plot settings
* *
@ -49,7 +47,7 @@ public class PlotSettings {
* *
* @param plot * @param plot
*/ */
public PlotSettings(Plot plot) { public PlotSettings(final Plot plot) {
this.alias = ""; this.alias = "";
} }
@ -63,7 +61,7 @@ public class PlotSettings {
* @param direction * @param direction
* @return boolean * @return boolean
*/ */
public boolean getMerged(int direction) { public boolean getMerged(final int direction) {
return this.merged[direction]; return this.merged[direction];
} }
@ -78,22 +76,21 @@ public class PlotSettings {
return this.merged; return this.merged;
} }
public void setMerged(boolean[] merged) { public void setMerged(final boolean[] merged) {
this.merged = merged; this.merged = merged;
} }
public void setMerged(int direction, boolean merged) { public void setMerged(final int direction, final boolean merged) {
this.merged[direction] = merged; this.merged[direction] = merged;
} }
/** /**
* @param b * @param b
*/ */
public void setBiome(Biome b) { public void setBiome(final Biome b) {
this.biome = b; this.biome = b;
} }
/** /**
* @return * @return
* @deprecated * @deprecated
@ -103,20 +100,18 @@ public class PlotSettings {
return this.biome; return this.biome;
} }
/** /**
* @param alias * @param alias
*/ */
public void setAlias(String alias) { public void setAlias(final String alias) {
this.alias = alias; this.alias = alias;
} }
/** /**
* @param flag * @param flag
*/ */
public void addFlag(Flag flag) { public void addFlag(final Flag flag) {
Flag hasFlag = getFlag(flag.getKey()); final Flag hasFlag = getFlag(flag.getKey());
if (hasFlag != null) { if (hasFlag != null) {
this.flags.remove(hasFlag); this.flags.remove(hasFlag);
} }
@ -126,7 +121,7 @@ public class PlotSettings {
/** /**
* @param flags * @param flags
*/ */
public void setFlags(Flag[] flags) { public void setFlags(final Flag[] flags) {
this.flags = new HashSet<Flag>(Arrays.asList(flags)); this.flags = new HashSet<Flag>(Arrays.asList(flags));
} }
@ -141,8 +136,8 @@ public class PlotSettings {
* @param flag * @param flag
* @return * @return
*/ */
public Flag getFlag(String flag) { public Flag getFlag(final String flag) {
for (Flag myflag : this.flags) { for (final Flag myflag : this.flags) {
if (myflag.getKey().equals(flag)) { if (myflag.getKey().equals(flag)) {
return myflag; return myflag;
} }
@ -154,7 +149,7 @@ public class PlotSettings {
return this.position; return this.position;
} }
public void setPosition(PlotHomePosition position) { public void setPosition(final PlotHomePosition position) {
this.position = position; this.position = position;
} }
@ -169,9 +164,10 @@ public class PlotSettings {
public String getLeaveMessage() { public String getLeaveMessage() {
return ""; return "";
} }
public ArrayList<PlotComment> getComments(int tier) {
ArrayList<PlotComment> c = new ArrayList<PlotComment>(); public ArrayList<PlotComment> getComments(final int tier) {
for (PlotComment comment : this.comments) { final ArrayList<PlotComment> c = new ArrayList<PlotComment>();
for (final PlotComment comment : this.comments) {
if (comment.tier == tier) { if (comment.tier == tier) {
c.add(comment); c.add(comment);
} }
@ -179,11 +175,11 @@ public class PlotSettings {
return c; return c;
} }
public void setComments(ArrayList<PlotComment> comments) { public void setComments(final ArrayList<PlotComment> comments) {
this.comments = comments; this.comments = comments;
} }
public void addComment(PlotComment comment) { public void addComment(final PlotComment comment) {
if (this.comments == null) { if (this.comments == null) {
this.comments = new ArrayList<PlotComment>(); this.comments = new ArrayList<PlotComment>();
} }

View File

@ -5,7 +5,7 @@ package com.intellectualcrafters.plot;
*/ */
public class PlotSquaredException extends RuntimeException { public class PlotSquaredException extends RuntimeException {
public PlotSquaredException(PlotError error, String details) { public PlotSquaredException(final PlotError error, final String details) {
super("PlotError >> " + error.getHeader() + ": " + details); super("PlotError >> " + error.getHeader() + ": " + details);
PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + error.getHeader() + ": &6" + details); PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + error.getHeader() + ": &6" + details);
} }
@ -14,7 +14,7 @@ public class PlotSquaredException extends RuntimeException {
MISSING_DEPENDENCY("Missing Dependency"); MISSING_DEPENDENCY("Missing Dependency");
private String errorHeader; private String errorHeader;
PlotError(String errorHeader) { PlotError(final String errorHeader) {
this.errorHeader = errorHeader; this.errorHeader = errorHeader;
} }

View File

@ -1,15 +1,97 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.Material; import static org.bukkit.Material.ACACIA_STAIRS;
import org.bukkit.block.Biome; import static org.bukkit.Material.BEACON;
import org.bukkit.configuration.ConfigurationSection; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import static org.bukkit.Material.*; import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.configuration.ConfigurationSection;
/** /**
* *
@ -21,18 +103,8 @@ public abstract class PlotWorld {
// TODO make this configurable // TODO make this configurable
// make non static and static_default_valu + add config option // make non static and static_default_valu + add config option
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static ArrayList<Material> BLOCKS = new ArrayList<Material>(Arrays.asList(new Material[] { ACACIA_STAIRS, public static ArrayList<Material> BLOCKS = new ArrayList<Material>(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,
BEACON, BEDROCK, BIRCH_WOOD_STAIRS, BOOKSHELF, BREWING_STAND, BRICK, BRICK_STAIRS, BURNING_FURNACE, SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK, SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44), getMaterial(126) }));
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 boolean AUTO_MERGE;
public static boolean AUTO_MERGE_DEFAULT = false; public static boolean AUTO_MERGE_DEFAULT = false;
@ -88,18 +160,16 @@ public abstract class PlotWorld {
public boolean SPAWN_BREEDING; public boolean SPAWN_BREEDING;
public static boolean SPAWN_BREEDING_DEFAULT = false; public static boolean SPAWN_BREEDING_DEFAULT = false;
public PlotWorld(final String worldname) {
public PlotWorld(String worldname) {
this.worldname = worldname; this.worldname = worldname;
} }
/** /**
* When a world is created, the following method will be called for each * When a world is created, the following method will be called for each
* *
@param config * @param config
*/ */
public void loadDefaultConfiguration(ConfigurationSection config) public void loadDefaultConfiguration(final ConfigurationSection config) {
{
this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning"); this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning");
this.AUTO_MERGE = config.getBoolean("plot.auto_merge"); this.AUTO_MERGE = config.getBoolean("plot.auto_merge");
this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome")); this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome"));
@ -121,15 +191,15 @@ public abstract class PlotWorld {
loadConfiguration(config); loadConfiguration(config);
} }
public abstract void loadConfiguration(ConfigurationSection config); public abstract void loadConfiguration(final ConfigurationSection config);
/** /**
* Saving core plotworld settings * Saving core plotworld settings
*
* @param config * @param config
*/ */
public void saveConfiguration(ConfigurationSection config) public void saveConfiguration(final ConfigurationSection config) {
{ final HashMap<String, Object> options = new HashMap<String, Object>();
HashMap<String, Object> options = new HashMap<String, Object>();
options.put("natural_mob_spawning", PlotWorld.MOB_SPAWNING_DEFAULT); options.put("natural_mob_spawning", PlotWorld.MOB_SPAWNING_DEFAULT);
options.put("plot.auto_merge", PlotWorld.AUTO_MERGE_DEFAULT); options.put("plot.auto_merge", PlotWorld.AUTO_MERGE_DEFAULT);
@ -149,18 +219,16 @@ public abstract class PlotWorld {
options.put("event.spawn.egg", PlotWorld.SPAWN_EGGS_DEFAULT); options.put("event.spawn.egg", PlotWorld.SPAWN_EGGS_DEFAULT);
options.put("event.spawn.custom", PlotWorld.SPAWN_CUSTOM_DEFAULT); options.put("event.spawn.custom", PlotWorld.SPAWN_CUSTOM_DEFAULT);
options.put("event.spawn.breeding", PlotWorld.SPAWN_BREEDING_DEFAULT); options.put("event.spawn.breeding", PlotWorld.SPAWN_BREEDING_DEFAULT);
ConfigurationNode[] settings = getSettingNodes(); final ConfigurationNode[] settings = getSettingNodes();
/* /*
* Saving generator specific settings * Saving generator specific settings
*/ */
for (ConfigurationNode setting : settings) for (final ConfigurationNode setting : settings) {
{
options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue())); options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue()));
} }
for (String option : options.keySet()) for (final String option : options.keySet()) {
{
if (!config.contains(option)) { if (!config.contains(option)) {
config.set(option, options.get(option)); config.set(option, options.get(option));
} }

View File

@ -30,15 +30,15 @@ public class RUtils {
return (getFreeRam() / getTotalRam()) * 100; return (getFreeRam() / getTotalRam()) * 100;
} }
public static String formatTime(double sec) { public static String formatTime(final double sec) {
double h = sec / 3600; final double h = sec / 3600;
double m = (sec % 3600) / 60; final double m = (sec % 3600) / 60;
double s = sec % 60; final double s = sec % 60;
String string = C.TIME_FORMAT.s(); final String string = C.TIME_FORMAT.s();
String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour"); final String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour");
String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute"); final String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute");
String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second"); 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); return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h);
} }
@ -47,9 +47,9 @@ public class RUtils {
EAST(1), EAST(1),
NORTH(2), NORTH(2),
WEST(3); WEST(3);
private int i; private final int i;
Direction(int i) { Direction(final int i) {
this.i = i; this.i = i;
} }
@ -58,14 +58,14 @@ public class RUtils {
} }
} }
public void forceTexture(Player p) { public void forceTexture(final Player p) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
} }
public Direction getDirection(Location l) { public Direction getDirection(final Location l) {
double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D; final double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D;
int i = (int) d; final int i = (int) d;
int x = d < i ? i - 1 : i; final int x = d < i ? i - 1 : i;
switch (x) { switch (x) {
case 0: case 0:
return Direction.SOUTH; return Direction.SOUTH;
@ -80,7 +80,7 @@ public class RUtils {
} }
} }
public boolean compareDirections(Location l1, Location l2) { public boolean compareDirections(final Location l1, final Location l2) {
return getDirection(l1) == getDirection(l2); return getDirection(l1) == getDirection(l2);
} }

View File

@ -30,24 +30,24 @@ public class ReflectionUtils {
if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) { if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) {
forge = true; forge = true;
} }
Server server = Bukkit.getServer(); final Server server = Bukkit.getServer();
Class<?> bukkitServerClass = server.getClass(); final Class<?> bukkitServerClass = server.getClass();
String[] pas = bukkitServerClass.getName().split("\\."); String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5) { if (pas.length == 5) {
String verB = pas[3]; final String verB = pas[3];
preClassB += "." + verB; preClassB += "." + verB;
} }
try { try {
Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
Object handle = getHandle.invoke(server); final Object handle = getHandle.invoke(server);
Class handleServerClass = handle.getClass(); final Class handleServerClass = handle.getClass();
pas = handleServerClass.getName().split("\\."); pas = handleServerClass.getName().split("\\.");
if (pas.length == 5) { if (pas.length == 5) {
String verM = pas[3]; final String verM = pas[3];
preClassM += "." + verM; preClassM += "." + verM;
} }
} }
catch (Exception ignored) { catch (final Exception ignored) {
} }
} }
} }
@ -69,14 +69,13 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if no class found * if no class found
*/ */
public static RefClass getRefClass(String... classes) { public static RefClass getRefClass(final String... classes) {
for (String className : classes) { for (String className : classes) {
try { try {
className = className = className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft");
className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft");
return getRefClass(Class.forName(className)); return getRefClass(Class.forName(className));
} }
catch (ClassNotFoundException ignored) { catch (final ClassNotFoundException ignored) {
} }
} }
throw new RuntimeException("no class found"); throw new RuntimeException("no class found");
@ -89,7 +88,7 @@ public class ReflectionUtils {
* class * class
* @return RefClass based on passed class * @return RefClass based on passed class
*/ */
public static RefClass getRefClass(Class clazz) { public static RefClass getRefClass(final Class clazz) {
return new RefClass(clazz); return new RefClass(clazz);
} }
@ -108,7 +107,7 @@ public class ReflectionUtils {
return this.clazz; return this.clazz;
} }
private RefClass(Class<?> clazz) { private RefClass(final Class<?> clazz) {
this.clazz = clazz; this.clazz = clazz;
} }
@ -119,7 +118,7 @@ public class ReflectionUtils {
* the object to check * the object to check
* @return true if object is an instance of this class * @return true if object is an instance of this class
*/ */
public boolean isInstance(Object object) { public boolean isInstance(final Object object) {
return this.clazz.isInstance(object); return this.clazz.isInstance(object);
} }
@ -134,16 +133,15 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if method not found * if method not found
*/ */
public RefMethod getMethod(String name, Object... types) throws NoSuchMethodException { public RefMethod getMethod(final String name, final Object... types) throws NoSuchMethodException {
try { try {
Class[] classes = new Class[types.length]; final Class[] classes = new Class[types.length];
int i = 0; int i = 0;
for (Object e : types) { for (final Object e : types) {
if (e instanceof Class) { if (e instanceof Class) {
classes[i++] = (Class) e; classes[i++] = (Class) e;
} }
else else if (e instanceof RefClass) {
if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass(); classes[i++] = ((RefClass) e).getRealClass();
} }
else { else {
@ -153,11 +151,11 @@ public class ReflectionUtils {
try { try {
return new RefMethod(this.clazz.getMethod(name, classes)); return new RefMethod(this.clazz.getMethod(name, classes));
} }
catch (NoSuchMethodException ignored) { catch (final NoSuchMethodException ignored) {
return new RefMethod(this.clazz.getDeclaredMethod(name, classes)); return new RefMethod(this.clazz.getDeclaredMethod(name, classes));
} }
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -171,16 +169,15 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if constructor not found * if constructor not found
*/ */
public RefConstructor getConstructor(Object... types) { public RefConstructor getConstructor(final Object... types) {
try { try {
Class[] classes = new Class[types.length]; final Class[] classes = new Class[types.length];
int i = 0; int i = 0;
for (Object e : types) { for (final Object e : types) {
if (e instanceof Class) { if (e instanceof Class) {
classes[i++] = (Class) e; classes[i++] = (Class) e;
} }
else else if (e instanceof RefClass) {
if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass(); classes[i++] = ((RefClass) e).getRealClass();
} }
else { else {
@ -190,11 +187,11 @@ public class ReflectionUtils {
try { try {
return new RefConstructor(this.clazz.getConstructor(classes)); return new RefConstructor(this.clazz.getConstructor(classes));
} }
catch (NoSuchMethodException ignored) { catch (final NoSuchMethodException ignored) {
return new RefConstructor(this.clazz.getDeclaredConstructor(classes)); return new RefConstructor(this.clazz.getDeclaredConstructor(classes));
} }
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -208,27 +205,25 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if method not found * if method not found
*/ */
public RefMethod findMethod(Object... types) { public RefMethod findMethod(final Object... types) {
Class[] classes = new Class[types.length]; final Class[] classes = new Class[types.length];
int t = 0; int t = 0;
for (Object e : types) { for (final Object e : types) {
if (e instanceof Class) { if (e instanceof Class) {
classes[t++] = (Class) e; classes[t++] = (Class) e;
} }
else else if (e instanceof RefClass) {
if (e instanceof RefClass) {
classes[t++] = ((RefClass) e).getRealClass(); classes[t++] = ((RefClass) e).getRealClass();
} }
else { else {
classes[t++] = e.getClass(); classes[t++] = e.getClass();
} }
} }
List<Method> methods = new ArrayList<>(); final List<Method> methods = new ArrayList<>();
Collections.addAll(methods, this.clazz.getMethods()); Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, this.clazz.getDeclaredMethods()); Collections.addAll(methods, this.clazz.getDeclaredMethods());
findMethod: findMethod: for (final Method m : methods) {
for (Method m : methods) { final Class<?>[] methodTypes = m.getParameterTypes();
Class<?>[] methodTypes = m.getParameterTypes();
if (methodTypes.length != classes.length) { if (methodTypes.length != classes.length) {
continue; continue;
} }
@ -251,12 +246,12 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if method not found * if method not found
*/ */
public RefMethod findMethodByName(String... names) { public RefMethod findMethodByName(final String... names) {
List<Method> methods = new ArrayList<>(); final List<Method> methods = new ArrayList<>();
Collections.addAll(methods, this.clazz.getMethods()); Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, this.clazz.getDeclaredMethods()); Collections.addAll(methods, this.clazz.getDeclaredMethods());
for (Method m : methods) { for (final Method m : methods) {
for (String name : names) { for (final String name : names) {
if (m.getName().equals(name)) { if (m.getName().equals(name)) {
return new RefMethod(m); return new RefMethod(m);
} }
@ -274,7 +269,7 @@ public class ReflectionUtils {
* if method not found * if method not found
* @return RefMethod * @return RefMethod
*/ */
public RefMethod findMethodByReturnType(RefClass type) { public RefMethod findMethodByReturnType(final RefClass type) {
return findMethodByReturnType(type.clazz); return findMethodByReturnType(type.clazz);
} }
@ -291,10 +286,10 @@ public class ReflectionUtils {
if (type == null) { if (type == null) {
type = void.class; type = void.class;
} }
List<Method> methods = new ArrayList<>(); final List<Method> methods = new ArrayList<>();
Collections.addAll(methods, this.clazz.getMethods()); Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, this.clazz.getDeclaredMethods()); Collections.addAll(methods, this.clazz.getDeclaredMethods());
for (Method m : methods) { for (final Method m : methods) {
if (type.equals(m.getReturnType())) { if (type.equals(m.getReturnType())) {
return new RefMethod(m); return new RefMethod(m);
} }
@ -311,11 +306,11 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if constructor not found * if constructor not found
*/ */
public RefConstructor findConstructor(int number) { public RefConstructor findConstructor(final int number) {
List<Constructor> constructors = new ArrayList<>(); final List<Constructor> constructors = new ArrayList<>();
Collections.addAll(constructors, this.clazz.getConstructors()); Collections.addAll(constructors, this.clazz.getConstructors());
Collections.addAll(constructors, this.clazz.getDeclaredConstructors()); Collections.addAll(constructors, this.clazz.getDeclaredConstructors());
for (Constructor m : constructors) { for (final Constructor m : constructors) {
if (m.getParameterTypes().length == number) { if (m.getParameterTypes().length == number) {
return new RefConstructor(m); return new RefConstructor(m);
} }
@ -332,16 +327,16 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if field not found * if field not found
*/ */
public RefField getField(String name) { public RefField getField(final String name) {
try { try {
try { try {
return new RefField(this.clazz.getField(name)); return new RefField(this.clazz.getField(name));
} }
catch (NoSuchFieldException ignored) { catch (final NoSuchFieldException ignored) {
return new RefField(this.clazz.getDeclaredField(name)); return new RefField(this.clazz.getDeclaredField(name));
} }
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -355,7 +350,7 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if field not found * if field not found
*/ */
public RefField findField(RefClass type) { public RefField findField(final RefClass type) {
return findField(type.clazz); return findField(type.clazz);
} }
@ -372,10 +367,10 @@ public class ReflectionUtils {
if (type == null) { if (type == null) {
type = void.class; type = void.class;
} }
List<Field> fields = new ArrayList<>(); final List<Field> fields = new ArrayList<>();
Collections.addAll(fields, this.clazz.getFields()); Collections.addAll(fields, this.clazz.getFields());
Collections.addAll(fields, this.clazz.getDeclaredFields()); Collections.addAll(fields, this.clazz.getDeclaredFields());
for (Field f : fields) { for (final Field f : fields) {
if (type.equals(f.getType())) { if (type.equals(f.getType())) {
return new RefField(f); return new RefField(f);
} }
@ -411,7 +406,7 @@ public class ReflectionUtils {
return new RefClass(this.method.getReturnType()); return new RefClass(this.method.getReturnType());
} }
private RefMethod(Method method) { private RefMethod(final Method method) {
this.method = method; this.method = method;
method.setAccessible(true); method.setAccessible(true);
} }
@ -423,7 +418,7 @@ public class ReflectionUtils {
* object to which the method is applied * object to which the method is applied
* @return RefExecutor with method call(...) * @return RefExecutor with method call(...)
*/ */
public RefExecutor of(Object e) { public RefExecutor of(final Object e) {
return new RefExecutor(e); return new RefExecutor(e);
} }
@ -434,11 +429,11 @@ public class ReflectionUtils {
* sent parameters * sent parameters
* @return return value * @return return value
*/ */
public Object call(Object... params) { public Object call(final Object... params) {
try { try {
return this.method.invoke(null, params); return this.method.invoke(null, params);
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -446,7 +441,7 @@ public class ReflectionUtils {
public class RefExecutor { public class RefExecutor {
Object e; Object e;
public RefExecutor(Object e) { public RefExecutor(final Object e) {
this.e = e; this.e = e;
} }
@ -459,11 +454,11 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if something went wrong * if something went wrong
*/ */
public Object call(Object... params) { public Object call(final Object... params) {
try { try {
return RefMethod.this.method.invoke(this.e, params); return RefMethod.this.method.invoke(this.e, params);
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -490,7 +485,7 @@ public class ReflectionUtils {
return new RefClass(this.constructor.getDeclaringClass()); return new RefClass(this.constructor.getDeclaringClass());
} }
private RefConstructor(Constructor constructor) { private RefConstructor(final Constructor constructor) {
this.constructor = constructor; this.constructor = constructor;
constructor.setAccessible(true); constructor.setAccessible(true);
} }
@ -504,18 +499,18 @@ public class ReflectionUtils {
* @throws RuntimeException * @throws RuntimeException
* if something went wrong * if something went wrong
*/ */
public Object create(Object... params) { public Object create(final Object... params) {
try { try {
return this.constructor.newInstance(params); return this.constructor.newInstance(params);
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }
public static class RefField { public static class RefField {
private Field field; private final Field field;
/** /**
* @return passed field * @return passed field
@ -538,7 +533,7 @@ public class ReflectionUtils {
return new RefClass(this.field.getType()); return new RefClass(this.field.getType());
} }
private RefField(Field field) { private RefField(final Field field) {
this.field = field; this.field = field;
field.setAccessible(true); field.setAccessible(true);
} }
@ -550,14 +545,14 @@ public class ReflectionUtils {
* applied object * applied object
* @return RefExecutor with getter and setter * @return RefExecutor with getter and setter
*/ */
public RefExecutor of(Object e) { public RefExecutor of(final Object e) {
return new RefExecutor(e); return new RefExecutor(e);
} }
public class RefExecutor { public class RefExecutor {
Object e; Object e;
public RefExecutor(Object e) { public RefExecutor(final Object e) {
this.e = e; this.e = e;
} }
@ -567,11 +562,11 @@ public class ReflectionUtils {
* @param param * @param param
* value * value
*/ */
public void set(Object param) { public void set(final Object param) {
try { try {
RefField.this.field.set(this.e, param); RefField.this.field.set(this.e, param);
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -585,7 +580,7 @@ public class ReflectionUtils {
try { try {
return RefField.this.field.get(this.e); return RefField.this.field.get(this.e);
} }
catch (Exception e) { catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }

View File

@ -1,14 +1,5 @@
package com.intellectualcrafters.plot; 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.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -21,62 +12,98 @@ import java.util.Map;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; 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 * Schematic Handler
*
* @author Citymonstret * @author Citymonstret
* @author Empire92 * @author Empire92
*/ */
@SuppressWarnings({"all"}) @SuppressWarnings({ "all" })
public class SchematicHandler { public class SchematicHandler {
/** /**
* Paste a schematic * Paste a schematic
* @param location origin *
* @param schematic schematic to paste * @param location
* @param plot plot to paste in * origin
* @param schematic
* schematic to paste
* @param plot
* plot to paste in
* @return true if succeeded * @return true if succeeded
*/ */
public static boolean paste(Location location, Schematic schematic, Plot plot, int x_offset, int z_offset) { public static boolean paste(final Location location, final Schematic schematic, final Plot plot, final int x_offset, final int z_offset) {
if (schematic == null) { if (schematic == null) {
PlotMain.sendConsoleSenderMessage("Schematic == null :|"); PlotMain.sendConsoleSenderMessage("Schematic == null :|");
return false; return false;
} }
try { try {
Dimension demensions = schematic.getSchematicDimension(); final Dimension demensions = schematic.getSchematicDimension();
int WIDTH = demensions.getX();
int LENGTH = demensions.getZ();
int HEIGHT = demensions.getY();
DataCollection[] blocks = schematic.getBlockCollection();
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()); Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId());
int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX()+1, l1.getBlockZ()+1); final int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX() + 1, l1.getBlockZ() + 1);
l1 = l1.add(1, sy-1, 1); l1 = l1.add(1, sy - 1, 1);
World world = location.getWorld(); final World world = location.getWorld();
int y_offset;
if (HEIGHT == location.getWorld().getMaxHeight()) {
y_offset = 0;
}
else {
y_offset = l1.getBlockY();
}
for (int x = 0; x < WIDTH; x++) { for (int x = 0; x < WIDTH; x++) {
for (int z = 0; z < LENGTH; z++) { for (int z = 0; z < LENGTH; z++) {
for (int y = 0; y < HEIGHT; y++) { for (int y = 0; y < HEIGHT; y++) {
int index = y * WIDTH * LENGTH + z * WIDTH + x; final int index = (y * WIDTH * LENGTH) + (z * WIDTH) + x;
short id = blocks[index].getBlock(); final DataCollection block = blocks[index];
byte data = blocks[index].getData();
Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset); final short id = block.getBlock();
final byte data = block.getData();
PlotBlock plotblock = new PlotBlock(id, data); // 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);
PlotHelper.setBlock(block, plotblock); final PlotBlock plotblock = new PlotBlock(id, data);
PlotHelper.setBlock(bukkitBlock, plotblock);
// }
} }
} }
} }
} }
catch (Exception e) { catch (final Exception e) {
return false; return false;
} }
return true; return true;
@ -84,20 +111,19 @@ public class SchematicHandler {
/** /**
* Get a schematic * Get a schematic
* @param name to check *
* @param name
* to check
* @return schematic if found, else null * @return schematic if found, else null
*/ */
public static Schematic getSchematic(String name) { public static Schematic getSchematic(final String name) {
{ {
File parent = final File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
if (!parent.exists()) { if (!parent.exists()) {
parent.mkdir(); parent.mkdir();
} }
} }
File file = final File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic");
new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"
+ File.separator + name + ".schematic");
if (!file.exists()) { if (!file.exists()) {
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist"); PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
return null; return null;
@ -105,25 +131,25 @@ public class SchematicHandler {
Schematic schematic; Schematic schematic;
try { try {
InputStream iStream = new FileInputStream(file); final InputStream iStream = new FileInputStream(file);
NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream)); final NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream));
CompoundTag tag = (CompoundTag) stream.readTag(); final CompoundTag tag = (CompoundTag) stream.readTag();
stream.close(); stream.close();
Map<String, Tag> tagMap = tag.getValue(); final Map<String, Tag> tagMap = tag.getValue();
byte[] addId = new byte[0]; byte[] addId = new byte[0];
if (tagMap.containsKey("AddBlocks")) { if (tagMap.containsKey("AddBlocks")) {
addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue();
} }
short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); final short width = ShortTag.class.cast(tagMap.get("Width")).getValue();
short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); final short length = ShortTag.class.cast(tagMap.get("Length")).getValue();
short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); final short height = ShortTag.class.cast(tagMap.get("Height")).getValue();
byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); final byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue();
byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); final byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue();
short[] blocks = new short[b.length]; 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++) { for (int index = 0; index < b.length; index++) {
if ((index >> 1) >= addId.length) { // No corresponding if ((index >> 1) >= addId.length) { // No corresponding
@ -140,15 +166,50 @@ public class SchematicHandler {
} }
} }
DataCollection[] collection = new DataCollection[b.length]; final DataCollection[] collection = new DataCollection[b.length];
for (int x = 0; x < b.length; x++) { for (int x = 0; x < b.length; x++) {
collection[x] = new DataCollection(blocks[x], d[x]); collection[x] = new DataCollection(blocks[x], d[x]);
} }
// if (PlotMain.worldEdit!=null) {
// List<Tag> 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<String, Tag> values = new HashMap<String, Tag>();
//
// for (Map.Entry<String, Tag> 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); schematic = new Schematic(collection, dimension, file);
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@ -157,14 +218,15 @@ public class SchematicHandler {
/** /**
* Schematic Class * Schematic Class
*
* @author Citymonstret * @author Citymonstret
*/ */
public static class Schematic { public static class Schematic {
private DataCollection[] blockCollection; private final DataCollection[] blockCollection;
private Dimension schematicDimension; private final Dimension schematicDimension;
private File file; private final File file;
public Schematic(DataCollection[] blockCollection, Dimension schematicDimension, File file) { public Schematic(final DataCollection[] blockCollection, final Dimension schematicDimension, final File file) {
this.blockCollection = blockCollection; this.blockCollection = blockCollection;
this.schematicDimension = schematicDimension; this.schematicDimension = schematicDimension;
this.file = file; this.file = file;
@ -185,14 +247,15 @@ public class SchematicHandler {
/** /**
* Schematic Dimensions * Schematic Dimensions
*
* @author Citymonstret * @author Citymonstret
*/ */
public static class Dimension { public static class Dimension {
private int x; private final int x;
private int y; private final int y;
private int z; private final int z;
public Dimension(int x, int y, int z) { public Dimension(final int x, final int y, final int z) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
@ -213,24 +276,28 @@ public class SchematicHandler {
/** /**
* Saves a schematic to a file path * Saves a schematic to a file path
* @param tag to save *
* @param path to save in * @param tag
* to save
* @param path
* to save in
* @return true if succeeded * @return true if succeeded
*/ */
public static boolean save(CompoundTag tag, String path) { public static boolean save(final CompoundTag tag, final String path) {
if (tag==null) { if (tag == null) {
PlotMain.sendConsoleSenderMessage("&cCannot save empty tag"); PlotMain.sendConsoleSenderMessage("&cCannot save empty tag");
return false; return false;
} }
try { try {
OutputStream stream = new FileOutputStream(path); final OutputStream stream = new FileOutputStream(path);
NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream)); final NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream));
output.writeTag(tag); output.writeTag(tag);
output.close(); output.close();
stream.close(); stream.close();
} catch (IOException e) { }
catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@ -239,11 +306,14 @@ public class SchematicHandler {
/** /**
* Gets the schematic of a plot * Gets the schematic of a plot
* @param world to check *
* @param id plot * @param world
* to check
* @param id
* plot
* @return tag * @return tag
*/ */
public static CompoundTag getCompoundTag(World world, PlotId id) { public static CompoundTag getCompoundTag(final World world, final PlotId id) {
if (!PlotMain.getPlots(world).containsKey(id)) { if (!PlotMain.getPlots(world).containsKey(id)) {
return null; return null;
@ -258,8 +328,8 @@ public class SchematicHandler {
try { try {
for (i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { 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) { for (j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) {
Chunk chunk = world.getChunkAt(i, j); final Chunk chunk = world.getChunkAt(i, j);
boolean result = chunk.load(false); final boolean result = chunk.load(false);
if (!result) { if (!result) {
// Plot is not even generated // Plot is not even generated
@ -269,15 +339,15 @@ public class SchematicHandler {
} }
} }
} }
catch (Exception e) { catch (final Exception e) {
PlotMain.sendConsoleSenderMessage("&7 - Cannot save: corrupt chunk at "+(i/16)+", "+(j/16)); PlotMain.sendConsoleSenderMessage("&7 - Cannot save: corrupt chunk at " + (i / 16) + ", " + (j / 16));
return null; return null;
} }
int width = pos2.getBlockX()-pos1.getBlockX()+1; final int width = (pos2.getBlockX() - pos1.getBlockX()) + 1;
int height = 256; final int height = 256;
int length = pos2.getBlockZ()-pos1.getBlockZ()+1; final int length = (pos2.getBlockZ() - pos1.getBlockZ()) + 1;
HashMap<String, Tag> schematic = new HashMap<>(); final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width)); schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length)); schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height)); schematic.put("Height", new ShortTag("Height", (short) height));
@ -288,35 +358,33 @@ public class SchematicHandler {
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
byte[] blocks = new byte[width * height * length]; final byte[] blocks = new byte[width * height * length];
byte[] addBlocks = null; 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 x = 0; x < width; x++) {
for (int z = 0; z < length; z++) { for (int z = 0; z < length; z++) {
for (int y = 0; y < height; y++) { for (int y = 0; y < height; y++) {
int index = y * width * length + z * width + x; final int index = (y * width * length) + (z * width) + x;
Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z)); final Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z));
int id2 = block.getTypeId(); final int id2 = block.getTypeId();
if (id2 > 255) { if (id2 > 255) {
if (addBlocks == null) { if (addBlocks == null) {
addBlocks = new byte[(blocks.length >> 1) + 1]; addBlocks = new byte[(blocks.length >> 1) + 1];
} }
addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? (addBlocks[index >> 1] & 0xF0) | ((id2 >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((id2 >> 8) & 0xF) << 4));
addBlocks[index >> 1] & 0xF0 | (id2 >> 8) & 0xF
: addBlocks[index >> 1] & 0xF | ((id2 >> 8) & 0xF) << 4);
} }
blocks[index] = (byte) id2; blocks[index] = (byte) id2;
blockData[index] = block.getData(); blockData[index] = block.getData();
// We need worldedit to save tileentity data or entities // 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
} }
} }
} }
@ -334,13 +402,16 @@ public class SchematicHandler {
/** /**
* Schematic Data Collection * Schematic Data Collection
*
* @author Citymonstret * @author Citymonstret
*/ */
public static class DataCollection { public static class DataCollection {
private short block; private final short block;
private byte data; private final byte data;
public DataCollection(short block, byte data) { // public CompoundTag tag;
public DataCollection(final short block, final byte data) {
this.block = block; this.block = block;
this.data = data; this.data = data;
} }
@ -354,31 +425,31 @@ public class SchematicHandler {
} }
} }
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 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; boolean result = false;
for (int i = i1; i<=i2 ;i++) { for (int i = i1; i <= i2; i++) {
short id = blocks[i].getBlock(); final short id = blocks[i].getBlock();
byte data = blocks[i].getData(); final byte data = blocks[i].getData();
if (id==0) { if (id == 0) {
continue; continue;
} }
int area = WIDTH*LENGTH; final int area = WIDTH * LENGTH;
int r = i%(area); final int r = i % (area);
int x = r%WIDTH; final int x = r % WIDTH;
int y = i/area; final int y = i / area;
int z = r/WIDTH; final int z = r / WIDTH;
if (y>256) { if (y > 256) {
break; break;
} }
Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset); final Block block = world.getBlockAt(l1.getBlockX() + x + x_offset, l1.getBlockY() + y, l1.getBlockZ() + z + z_offset);
PlotBlock plotblock = new PlotBlock(id, data); final PlotBlock plotblock = new PlotBlock(id, data);
boolean set = PlotHelper.setBlock(block, plotblock); final boolean set = PlotHelper.setBlock(block, plotblock);
if (!result && set) { if (!result && set) {
result = true; result = true;
} }

View File

@ -30,17 +30,17 @@ public class SetBlockFast {
methodGetById = classBlock.getMethod("getById", 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(); final Object w = methodGetHandle.of(world).call();
Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4); final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
Object block = methodGetById.of(null).call(blockId); final Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data); methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
return true; return true;
} }
public static void update(org.bukkit.entity.Player player) { public static void update(final org.bukkit.entity.Player player) {
int distance = Bukkit.getViewDistance() + 1; final int distance = Bukkit.getViewDistance() + 1;
for (int cx = -distance; cx < distance; cx++) { for (int cx = -distance; cx < distance; cx++) {
for (int cz = -distance; cz < distance; cz++) { for (int cz = -distance; cz < distance; cz++) {
player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz); player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz);

View File

@ -77,7 +77,6 @@ public class Settings {
*/ */
public static boolean CUSTOM_API = true; public static boolean CUSTOM_API = true;
/** /**
* Database settings * Database settings
* *
@ -89,7 +88,6 @@ public class Settings {
*/ */
public static boolean USE_MONGO = false; /* public static boolean USE_MONGO = false; /*
* TODO: Implement Mongo * TODO: Implement Mongo
*
* @Brandon * @Brandon
*/ */
/** /**

View File

@ -5,6 +5,7 @@ import java.util.Collections;
/** /**
* String comparsion library * String comparsion library
*
* @author Citymonstret * @author Citymonstret
*/ */
public class StringComparsion { public class StringComparsion {
@ -12,12 +13,12 @@ public class StringComparsion {
private String bestMatch; private String bestMatch;
private double match; private double match;
public StringComparsion(String input, Object[] objects) { public StringComparsion(final String input, final Object[] objects) {
double c = 0; double c = 0;
for(Object o : objects) { for (final Object o : objects) {
if((c = compare(input, o.toString())) > match) { if ((c = compare(input, o.toString())) > this.match) {
match = c; this.match = c;
bestMatch = o.toString(); this.bestMatch = o.toString();
} }
} }
} }
@ -27,19 +28,16 @@ public class StringComparsion {
} }
public Object[] getBestMatchAdvanced() { public Object[] getBestMatchAdvanced() {
return new Object[] { return new Object[] { this.match, this.bestMatch };
match,
bestMatch
};
} }
public static double compare(String s1, String s2) { public static double compare(final String s1, final String s2) {
ArrayList p1 = wLetterPair(s1.toUpperCase()), final ArrayList p1 = wLetterPair(s1.toUpperCase()), p2 = wLetterPair(s2.toUpperCase());
p2 = wLetterPair(s2.toUpperCase()); int intersection = 0;
int intersection = 0, union = p1.size() + p2.size(); final int union = p1.size() + p2.size();
for (Object aP1 : p1) { for (final Object aP1 : p1) {
for(Object aP2 : p2) { for (final Object aP2 : p2) {
if(aP1.equals(aP2)) { if (aP1.equals(aP2)) {
intersection++; intersection++;
p2.remove(aP2); p2.remove(aP2);
break; break;
@ -49,21 +47,22 @@ public class StringComparsion {
return (2.0 * intersection) / union; return (2.0 * intersection) / union;
} }
public static ArrayList wLetterPair(String s) { public static ArrayList wLetterPair(final String s) {
ArrayList<String> aPairs = new ArrayList<>(); final ArrayList<String> aPairs = new ArrayList<>();
String[] wo = s.split("\\s"); final String[] wo = s.split("\\s");
for (String aWo : wo) { for (final String aWo : wo) {
String[] po = sLetterPair(aWo); final String[] po = sLetterPair(aWo);
Collections.addAll(aPairs, po); Collections.addAll(aPairs, po);
} }
return aPairs; return aPairs;
} }
public static String[] sLetterPair(String s) { public static String[] sLetterPair(final String s) {
int numPair = s.length() - 1; final int numPair = s.length() - 1;
String[] p = new String[numPair]; final String[] p = new String[numPair];
for(int i = 0; i < numPair; i++) for (int i = 0; i < numPair; i++) {
p[i] = s.substring(i, i + 2); p[i] = s.substring(i, i + 2);
}
return p; return p;
} }

View File

@ -8,19 +8,23 @@ public class StringWrapper {
/** /**
* Constructor * Constructor
* @param value to wrap *
* @param value
* to wrap
*/ */
public StringWrapper(String value) { public StringWrapper(final String value) {
this.value = value; this.value = value;
} }
/** /**
* Check if a wrapped string equals another one * Check if a wrapped string equals another one
* @param obj to compare *
* @param obj
* to compare
* @return true if obj equals the stored value * @return true if obj equals the stored value
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -30,12 +34,13 @@ public class StringWrapper {
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
StringWrapper other = (StringWrapper) obj; final StringWrapper other = (StringWrapper) obj;
return other.value.toLowerCase().equals(this.value.toLowerCase()); return other.value.toLowerCase().equals(this.value.toLowerCase());
} }
/** /**
* Get the string value * Get the string value
*
* @return string value * @return string value
*/ */
@Override @Override
@ -45,6 +50,7 @@ public class StringWrapper {
/** /**
* Get the hash value * Get the hash value
*
* @return has value * @return has value
*/ */
@Override @Override

View File

@ -47,7 +47,7 @@ public class Title {
* @param title * @param title
* Title * Title
*/ */
public Title(String title) { public Title(final String title) {
this.title = title; this.title = title;
loadClasses(); loadClasses();
} }
@ -60,7 +60,7 @@ public class Title {
* @param subtitle * @param subtitle
* Subtitle text * Subtitle text
*/ */
public Title(String title, String subtitle) { public Title(final String title, final String subtitle) {
this.title = title; this.title = title;
this.subtitle = subtitle; this.subtitle = subtitle;
loadClasses(); loadClasses();
@ -80,7 +80,7 @@ public class Title {
* @param fadeOutTime * @param fadeOutTime
* Fade out time * Fade out time
*/ */
public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { public Title(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) {
this.title = title; this.title = title;
this.subtitle = subtitle; this.subtitle = subtitle;
this.fadeInTime = fadeInTime; this.fadeInTime = fadeInTime;
@ -104,7 +104,7 @@ public class Title {
* @param color * @param color
* Chat color * Chat color
*/ */
public void setTitleColor(ChatColor color) { public void setTitleColor(final ChatColor color) {
this.titleColor = color; this.titleColor = color;
} }
@ -114,7 +114,7 @@ public class Title {
* @param color * @param color
* Chat color * Chat color
*/ */
public void setSubtitleColor(ChatColor color) { public void setSubtitleColor(final ChatColor color) {
this.subtitleColor = color; this.subtitleColor = color;
} }
@ -124,7 +124,7 @@ public class Title {
* @param time * @param time
* Time * Time
*/ */
public void setFadeInTime(int time) { public void setFadeInTime(final int time) {
this.fadeInTime = time; this.fadeInTime = time;
} }
@ -134,7 +134,7 @@ public class Title {
* @param time * @param time
* Time * Time
*/ */
public void setFadeOutTime(int time) { public void setFadeOutTime(final int time) {
this.fadeOutTime = time; this.fadeOutTime = time;
} }
@ -144,7 +144,7 @@ public class Title {
* @param time * @param time
* Time * Time
*/ */
public void setStayTime(int time) { public void setStayTime(final int time) {
this.stayTime = time; this.stayTime = time;
} }
@ -168,45 +168,34 @@ public class Title {
* @param player * @param player
* Player * Player
*/ */
public void send(Player player) { public void send(final Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings // First reset previous settings
resetTitle(player); resetTitle(player);
try { try {
// Send timings first // Send timings first
Object handle = getHandle(player); final Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants(); final Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket"); final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = 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));
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 // Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} }
// Send title // Send title
Object serialized = Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
+ 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); sendPacket.invoke(connection, packet);
if (!this.subtitle.equals("")) { if (!this.subtitle.equals("")) {
// Send subtitle if present // Send subtitle if present
serialized = serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
+ 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); sendPacket.invoke(connection, packet);
} }
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -216,7 +205,7 @@ public class Title {
* Broadcast the title to all players * Broadcast the title to all players
*/ */
public void broadcast() { public void broadcast() {
for (Player p : Bukkit.getOnlinePlayers()) { for (final Player p : Bukkit.getOnlinePlayers()) {
send(p); send(p);
} }
} }
@ -227,18 +216,18 @@ public class Title {
* @param player * @param player
* Player * Player
*/ */
public void clearTitle(Player player) { public void clearTitle(final Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) { if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try { try {
// Send timings first // Send timings first
Object handle = getHandle(player); final Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants(); final Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket"); final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -250,18 +239,18 @@ public class Title {
* @param player * @param player
* Player * Player
*/ */
public void resetTitle(Player player) { public void resetTitle(final Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) { if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try { try {
// Send timings first // Send timings first
Object handle = getHandle(player); final Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants(); final Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket"); final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -274,17 +263,17 @@ public class Title {
* Player * Player
* @return Protocol version * @return Protocol version
*/ */
private int getProtocolVersion(Player player) { private int getProtocolVersion(final Player player) {
int version = 0; int version = 0;
try { try {
Object handle = getHandle(player); final Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection); final Object networkManager = getValue("networkManager", connection);
version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
return version; return version;
} }
catch (Exception ex) { catch (final Exception ex) {
// ex.printStackTrace(); <-- spammy console // ex.printStackTrace(); <-- spammy console
} }
return version; return version;
@ -306,39 +295,39 @@ public class Title {
* Namespace url * Namespace url
* @return Class * @return Class
*/ */
private Class<?> getClass(String namespace) { private Class<?> getClass(final String namespace) {
try { try {
return Class.forName(namespace); return Class.forName(namespace);
} }
catch (Exception e) { catch (final Exception e) {
return null; return null;
} }
} }
private Field getField(String name, Class<?> clazz) throws Exception { private Field getField(final String name, final Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name); return clazz.getDeclaredField(name);
} }
private Object getValue(String name, Object obj) throws Exception { private Object getValue(final String name, final Object obj) throws Exception {
Field f = getField(name, obj.getClass()); final Field f = getField(name, obj.getClass());
f.setAccessible(true); f.setAccessible(true);
return f.get(obj); return f.get(obj);
} }
private Class<?> getPrimitiveType(Class<?> clazz) { private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
} }
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) { private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
int a = classes != null ? classes.length : 0; final int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a]; final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) { for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]); types[i] = getPrimitiveType(classes[i]);
} }
return types; return types;
} }
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) { private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) { if (a.length != o.length) {
return false; return false;
} }
@ -350,20 +339,20 @@ public class Title {
return true; return true;
} }
private Object getHandle(Object obj) { private Object getHandle(final Object obj) {
try { try {
return getMethod("getHandle", obj.getClass()).invoke(obj); return getMethod("getHandle", obj.getClass()).invoke(obj);
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) { private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes); final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) { for (final Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes()); final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) { if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m; return m;
} }
@ -372,36 +361,36 @@ public class Title {
} }
private String getVersion() { private String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName(); final String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + "."; return name.substring(name.lastIndexOf('.') + 1) + ".";
} }
private Class<?> getNMSClass(String className) { private Class<?> getNMSClass(final String className) {
String fullName = "net.minecraft.server." + getVersion() + className; final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null; Class<?> clazz = null;
try { try {
clazz = Class.forName(fullName); clazz = Class.forName(fullName);
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return clazz; return clazz;
} }
private Field getField(Class<?> clazz, String name) { private Field getField(final Class<?> clazz, final String name) {
try { try {
Field field = clazz.getDeclaredField(name); final Field field = clazz.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
return field; return field;
} }
catch (Exception e) { catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private Method getMethod(Class<?> clazz, String name, Class<?>... args) { private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (Method m : clazz.getMethods()) { for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) { if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true); m.setAccessible(true);
return m; return m;
@ -410,7 +399,7 @@ public class Title {
return null; return null;
} }
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) { private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true; boolean equal = true;
if (l1.length != l2.length) { if (l1.length != l2.length) {
return false; return false;

View File

@ -1,21 +1,23 @@
package com.intellectualcrafters.plot; 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.base.Charsets;
import com.google.common.collect.BiMap; import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import com.intellectualcrafters.plot.uuid.NameFetcher; import com.intellectualcrafters.plot.uuid.NameFetcher;
import com.intellectualcrafters.plot.uuid.UUIDFetcher; import com.intellectualcrafters.plot.uuid.UUIDFetcher;
import com.intellectualcrafters.plot.uuid.UUIDSaver; 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: * It uses three primary methods of achieving this:
* - Read From Cache * - Read From Cache
* - Read from OfflinePlayer objects * - Read from OfflinePlayer objects
@ -23,11 +25,14 @@ import java.util.UUID;
* All UUIDs/Usernames will be stored in a map (cache) until the server is * All UUIDs/Usernames will be stored in a map (cache) until the server is
* restarted. * restarted.
* *
* You can use getUuidMap() to save the uuids/names to a file (SQLite db for example). * You can use getUuidMap() to save the uuids/names to a file (SQLite db for
* Primary methods: getUUID(String name) & getName(UUID uuid) <-- You should ONLY use these. * example).
* Primary methods: getUUID(String name) & getName(UUID uuid) <-- You should
* ONLY use these.
* Call startFetch(JavaPlugin plugin) in your onEnable(). * Call startFetch(JavaPlugin plugin) in your onEnable().
* *
* Originally created by: * Originally created by:
*
* @author Citymonstret * @author Citymonstret
* @author Empire92 * @author Empire92
* for PlotSquared. * for PlotSquared.
@ -36,6 +41,7 @@ public class UUIDHandler {
/** /**
* Online mode * Online mode
*
* @see org.bukkit.Server#getOnlineMode() * @see org.bukkit.Server#getOnlineMode()
*/ */
private static boolean online = Bukkit.getServer().getOnlineMode(); private static boolean online = Bukkit.getServer().getOnlineMode();
@ -47,6 +53,7 @@ public class UUIDHandler {
/** /**
* Get the map containing all names/uuids * Get the map containing all names/uuids
*
* @return map with names + uuids * @return map with names + uuids
*/ */
public static BiMap<StringWrapper, UUID> getUuidMap() { public static BiMap<StringWrapper, UUID> getUuidMap() {
@ -55,74 +62,84 @@ public class UUIDHandler {
/** /**
* Check if a uuid is cached * Check if a uuid is cached
* @param uuid to check *
* @param uuid
* to check
* @return true of the uuid is cached * @return true of the uuid is cached
*/ */
public static boolean uuidExists(UUID uuid) { public static boolean uuidExists(final UUID uuid) {
return uuidMap.containsValue(uuid); return uuidMap.containsValue(uuid);
} }
/** /**
* Check if a name is cached * Check if a name is cached
* @param name to check *
* @param name
* to check
* @return true of the name is cached * @return true of the name is cached
*/ */
public static boolean nameExists(StringWrapper name) { public static boolean nameExists(final StringWrapper name) {
return uuidMap.containsKey(name); return uuidMap.containsKey(name);
} }
/** /**
* Add a set to the cache * 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) { public static void add(final StringWrapper name, final UUID uuid) {
if (!uuidMap.containsKey(name) && !uuidMap.inverse().containsKey(uuid)) { if (!uuidMap.containsKey(name) && !uuidMap.inverse().containsKey(uuid)) {
uuidMap.put(name, uuid); uuidMap.put(name, uuid);
} }
} }
/** /**
* @param name to use as key * @param name
* to use as key
* @return uuid * @return uuid
*/ */
public static UUID getUUID(String name) { public static UUID getUUID(final String name) {
StringWrapper nameWrap = new StringWrapper(name); final StringWrapper nameWrap = new StringWrapper(name);
if (uuidMap.containsKey(nameWrap)) { if (uuidMap.containsKey(nameWrap)) {
return uuidMap.get(nameWrap); return uuidMap.get(nameWrap);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(name); final Player player = Bukkit.getPlayer(name);
if (player!=null) { if (player != null) {
UUID uuid = player.getUniqueId(); final UUID uuid = player.getUniqueId();
uuidMap.put(nameWrap, uuid); uuidMap.put(nameWrap, uuid);
return uuid; return uuid;
} }
UUID uuid; UUID uuid;
if (online) { if (online) {
if(Settings.CUSTOM_API) { if (Settings.CUSTOM_API) {
if ((uuid = getUuidOnlinePlayer(nameWrap)) != null) { if ((uuid = getUuidOnlinePlayer(nameWrap)) != null) {
return uuid; return uuid;
} }
try { try {
return PlotMain.getUUIDSaver().mojangUUID(name); return PlotMain.getUUIDSaver().mojangUUID(name);
} }
catch(Exception e) { catch (final Exception e) {
try { try {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); final UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name));
uuid = fetcher.call().get(name); uuid = fetcher.call().get(name);
add(nameWrap, uuid); add(nameWrap, uuid);
} }
catch (Exception ex) { catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
} else { }
else {
try { try {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); final UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name));
uuid = fetcher.call().get(name); uuid = fetcher.call().get(name);
add(nameWrap, uuid); add(nameWrap, uuid);
} catch (Exception ex) { }
catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@ -134,18 +151,20 @@ public class UUIDHandler {
} }
/** /**
* @param uuid to use as key * @param uuid
* to use as key
* @return name (cache) * @return name (cache)
*/ */
private static StringWrapper loopSearch(UUID uuid) { private static StringWrapper loopSearch(final UUID uuid) {
return uuidMap.inverse().get(uuid); return uuidMap.inverse().get(uuid);
} }
/** /**
* @param uuid to use as key * @param uuid
* to use as key
* @return Name * @return Name
*/ */
public static String getName(UUID uuid) { public static String getName(final UUID uuid) {
if (uuidExists(uuid)) { if (uuidExists(uuid)) {
return loopSearch(uuid).value; return loopSearch(uuid).value;
} }
@ -157,38 +176,44 @@ public class UUIDHandler {
return name; return name;
} }
if (online) { if (online) {
if(!Settings.CUSTOM_API) { if (!Settings.CUSTOM_API) {
try { try {
NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); final NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid));
name = fetcher.call().get(uuid); name = fetcher.call().get(uuid);
add(new StringWrapper(name), uuid); add(new StringWrapper(name), uuid);
return name; return name;
} catch (Exception ex) { }
catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} else { }
else {
try { try {
return PlotMain.getUUIDSaver().mojangName(uuid); return PlotMain.getUUIDSaver().mojangName(uuid);
} catch(Exception e) { }
catch (final Exception e) {
try { try {
NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); final NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid));
name = fetcher.call().get(uuid); name = fetcher.call().get(uuid);
add(new StringWrapper(name), uuid); add(new StringWrapper(name), uuid);
return name; return name;
} catch (Exception ex) { }
catch (final Exception ex) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
try { try {
return PlotMain.getUUIDSaver().mojangName(uuid); return PlotMain.getUUIDSaver().mojangName(uuid);
} catch(Exception e) { }
catch (final Exception e) {
try { try {
NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); final NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid));
name = fetcher.call().get(uuid); name = fetcher.call().get(uuid);
add(new StringWrapper(name), uuid); add(new StringWrapper(name), uuid);
return name; return name;
} catch (Exception ex) { }
catch (final Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@ -200,77 +225,70 @@ public class UUIDHandler {
} }
/** /**
* @param name to use as key * @param name
* to use as key
* @return UUID (name hash) * @return UUID (name hash)
*/ */
private static UUID getUuidOfflineMode(StringWrapper name) { private static UUID getUuidOfflineMode(final StringWrapper name) {
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
add(name, uuid); add(name, uuid);
return uuid; return uuid;
} }
/** /**
* @param uuid to use as key * @param uuid
* to use as key
* @return String - name * @return String - name
*/ */
private static String getNameOnlinePlayer(UUID uuid) { private static String getNameOnlinePlayer(final UUID uuid) {
Player player = Bukkit.getPlayer(uuid); final Player player = Bukkit.getPlayer(uuid);
if (player == null || !player.isOnline()) { if ((player == null) || !player.isOnline()) {
return null; return null;
} }
String name = player.getName(); final String name = player.getName();
add(new StringWrapper(name), uuid); add(new StringWrapper(name), uuid);
return name; return name;
} }
/** /**
* @param uuid to use as key * @param uuid
* to use as key
* @return String - name * @return String - name
*/ */
private static String getNameOfflinePlayer(UUID uuid) { private static String getNameOfflinePlayer(final UUID uuid) {
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); final OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if (player == null || !player.hasPlayedBefore()) { if ((player == null) || !player.hasPlayedBefore()) {
return null; return null;
} }
String name = player.getName(); final String name = player.getName();
add(new StringWrapper(name), uuid); add(new StringWrapper(name), uuid);
return name; return name;
} }
/** /**
* @param name to use as key * @param name
* to use as key
* @return UUID * @return UUID
*/ */
private static UUID getUuidOnlinePlayer(StringWrapper name) { private static UUID getUuidOnlinePlayer(final StringWrapper name) {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(name.value); final Player player = Bukkit.getPlayer(name.value);
if (player == null) { if (player == null) {
return null; return null;
} }
UUID uuid = player.getUniqueId(); final UUID uuid = player.getUniqueId();
add(name, uuid); add(name, uuid);
return 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;
}
/** /**
* Handle saving of uuids * Handle saving of uuids
*
* @see com.intellectualcrafters.plot.uuid.UUIDSaver#globalSave(com.google.common.collect.BiMap) * @see com.intellectualcrafters.plot.uuid.UUIDSaver#globalSave(com.google.common.collect.BiMap)
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void handleSaving() { 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 // Should it save per UUIDSet or all of them? TODO: Let Jesse decide xD
saver.globalSave(getUuidMap()); saver.globalSave(getUuidMap());
} }

View File

@ -8,9 +8,9 @@
package com.intellectualcrafters.plot.api; package com.intellectualcrafters.plot.api;
import com.intellectualcrafters.plot.*; import java.util.ArrayList;
import com.intellectualcrafters.plot.commands.MainCommand; import java.util.Set;
import com.intellectualcrafters.plot.commands.SubCommand;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
@ -18,8 +18,19 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList; import com.intellectualcrafters.plot.AbstractFlag;
import java.util.Set; 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. * The plotMain api class.
@ -52,7 +63,7 @@ public class PlotAPI {
// PlotMain.updatePlot(plot); // PlotMain.updatePlot(plot);
// To access plotMain stuff. // To access plotMain stuff.
private PlotMain plotMain; private final PlotMain plotMain;
// Reference // Reference
/** /**
@ -62,6 +73,7 @@ public class PlotAPI {
/** /**
* Get all plots * Get all plots
*
* @return all plots * @return all plots
*/ */
public Set<Plot> getAllPlots() { public Set<Plot> getAllPlots() {
@ -70,21 +82,28 @@ public class PlotAPI {
/** /**
* Return all plots for a player * Return all plots for a player
*
* @param player * @param player
* @return all plots that a player owns * @return all plots that a player owns
*/ */
public Set<Plot> getPlayerPlots(Player player) { public Set<Plot> getPlayerPlots(final Player player) {
return PlotMain.getPlots(player); return PlotMain.getPlots(player);
} }
/** /**
* Add a plotoworld * Add a plotoworld
* @see com.intellectualcrafters.plot.PlotMain#addPlotWorld(String, com.intellectualcrafters.plot.PlotWorld, com.intellectualcrafters.plot.PlotManager) *
* @param world World Name * @see com.intellectualcrafters.plot.PlotMain#addPlotWorld(String,
* @param plotWorld Plot World Object * com.intellectualcrafters.plot.PlotWorld,
* @param manager World Manager * 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); PlotMain.addPlotWorld(world, plotWorld, manager);
} }
@ -115,21 +134,23 @@ public class PlotAPI {
/** /**
* Constructor. Insert any Plugin. * Constructor. Insert any Plugin.
* (Optimally the plugin that is accessing the method) * (Optimally the plugin that is accessing the method)
* @param plugin Plugin used to access this method *
* @param plugin
* Plugin used to access this method
*/ */
public PlotAPI(JavaPlugin plugin) { public PlotAPI(final JavaPlugin plugin) {
this.plotMain = JavaPlugin.getPlugin(PlotMain.class); this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
} }
/** /**
* Get the main class for this plugin <br> * Get the main class for this plugin <br>
* - Contains a lot of fields and methods - not very well organized * - Contains a lot of fields and methods - not very well organized <br>
* <br>
* Only use this if you really need it * Only use this if you really need it
*
* @return PlotMain PlotSquared Main Class * @return PlotMain PlotSquared Main Class
*/ */
public PlotMain getMain() { public PlotMain getMain() {
return plotMain; return this.plotMain;
} }
/** /**
@ -185,7 +206,7 @@ public class PlotAPI {
* @param world * @param world
* @return PlotManager * @return PlotManager
*/ */
public PlotManager getPlotManager(World world) { public PlotManager getPlotManager(final World world) {
return PlotMain.getPlotManager(world); return PlotMain.getPlotManager(world);
} }
@ -196,7 +217,7 @@ public class PlotAPI {
* @param world * @param world
* @return PlotManager * @return PlotManager
*/ */
public PlotManager getPlotManager(String world) { public PlotManager getPlotManager(final String world) {
return PlotMain.getPlotManager(world); return PlotMain.getPlotManager(world);
} }
@ -210,7 +231,7 @@ public class PlotAPI {
* @return PlotWorld class for that world ! will return null if not a plot * @return PlotWorld class for that world ! will return null if not a plot
* world world * world world
*/ */
public PlotWorld getWorldSettings(World world) { public PlotWorld getWorldSettings(final World world) {
return PlotMain.getWorldSettings(world); return PlotMain.getWorldSettings(world);
} }
@ -222,7 +243,7 @@ public class PlotAPI {
* @return PlotWorld class for that world ! will return null if not a plot * @return PlotWorld class for that world ! will return null if not a plot
* world world * world world
*/ */
public PlotWorld getWorldSettings(String world) { public PlotWorld getWorldSettings(final String world) {
return PlotMain.getWorldSettings(world); return PlotMain.getWorldSettings(world);
} }
@ -233,7 +254,7 @@ public class PlotAPI {
* @param c * @param c
* (Caption) * (Caption)
*/ */
public void sendMessage(Player player, C c) { public void sendMessage(final Player player, final C c) {
PlayerFunctions.sendMessage(player, c); PlayerFunctions.sendMessage(player, c);
} }
@ -243,7 +264,7 @@ public class PlotAPI {
* @param player * @param player
* @param string * @param string
*/ */
public void sendMessage(Player player, String string) { public void sendMessage(final Player player, final String string) {
PlayerFunctions.sendMessage(player, string); PlayerFunctions.sendMessage(player, string);
} }
@ -252,7 +273,7 @@ public class PlotAPI {
* *
* @param msg * @param msg
*/ */
public void sendConsoleMessage(String msg) { public void sendConsoleMessage(final String msg) {
PlotMain.sendConsoleSenderMessage(msg); PlotMain.sendConsoleSenderMessage(msg);
} }
@ -262,7 +283,7 @@ public class PlotAPI {
* @param c * @param c
* (Caption) * (Caption)
*/ */
public void sendConsoleMessage(C c) { public void sendConsoleMessage(final C c) {
sendConsoleMessage(c.s()); sendConsoleMessage(c.s());
} }
@ -271,7 +292,7 @@ public class PlotAPI {
* *
* @param flag * @param flag
*/ */
public void addFlag(AbstractFlag flag) { public void addFlag(final AbstractFlag flag) {
FlagManager.addFlag(flag); FlagManager.addFlag(flag);
} }
@ -292,7 +313,7 @@ public class PlotAPI {
* @param z * @param z
* @return plot, null if ID is wrong * @return plot, null if ID is wrong
*/ */
public Plot getPlot(World world, int x, int z) { public Plot getPlot(final World world, final int x, final int z) {
return PlotHelper.getPlot(world, new PlotId(x, z)); return PlotHelper.getPlot(world, new PlotId(x, z));
} }
@ -302,7 +323,7 @@ public class PlotAPI {
* @param l * @param l
* @return plot if found, otherwise it creates a temporary plot- * @return plot if found, otherwise it creates a temporary plot-
*/ */
public Plot getPlot(Location l) { public Plot getPlot(final Location l) {
return PlotHelper.getCurrentPlot(l); return PlotHelper.getCurrentPlot(l);
} }
@ -312,7 +333,7 @@ public class PlotAPI {
* @param player * @param player
* @return plot if found, otherwise it creates a temporary plot * @return plot if found, otherwise it creates a temporary plot
*/ */
public Plot getPlot(Player player) { public Plot getPlot(final Player player) {
return this.getPlot(player.getLocation()); return this.getPlot(player.getLocation());
} }
@ -322,7 +343,7 @@ public class PlotAPI {
* @param player * @param player
* @return true if player has a plot, false if not. * @return true if player has a plot, false if not.
*/ */
public boolean hasPlot(World world, Player player) { public boolean hasPlot(final World world, final Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
} }
@ -334,9 +355,9 @@ public class PlotAPI {
* @param just_owner * @param just_owner
* should we just search for owner? Or with rights? * should we just search for owner? Or with rights?
*/ */
public Plot[] getPlots(World world, Player plr, boolean just_owner) { public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) {
ArrayList<Plot> pPlots = new ArrayList<>(); final ArrayList<Plot> pPlots = new ArrayList<>();
for (Plot plot : PlotMain.getPlots(world).values()) { for (final Plot plot : PlotMain.getPlots(world).values()) {
if (just_owner) { if (just_owner) {
if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) { if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) {
pPlots.add(plot); pPlots.add(plot);
@ -358,7 +379,7 @@ public class PlotAPI {
* to get plots of * to get plots of
* @return Plot[] - array of plot objects in world * @return Plot[] - array of plot objects in world
*/ */
public Plot[] getPlots(World world) { public Plot[] getPlots(final World world) {
return PlotMain.getWorldPlots(world); return PlotMain.getWorldPlots(world);
} }
@ -378,7 +399,7 @@ public class PlotAPI {
* (to check if plot world) * (to check if plot world)
* @return boolean (if plot world or not) * @return boolean (if plot world or not)
*/ */
public boolean isPlotWorld(World world) { public boolean isPlotWorld(final World world) {
return PlotMain.isPlotWorld(world); return PlotMain.isPlotWorld(world);
} }
@ -388,10 +409,9 @@ public class PlotAPI {
* @param p * @param p
* @return [0] = bottomLc, [1] = topLoc, [2] = home * @return [0] = bottomLc, [1] = topLoc, [2] = home
*/ */
public Location[] getLocations(Plot p) { public Location[] getLocations(final Plot p) {
World world = Bukkit.getWorld(p.world); final World world = Bukkit.getWorld(p.world);
return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), PlotHelper.getPlotHome(world, p.id) };
PlotHelper.getPlotHome(world, p.id) };
} }
/** /**
@ -400,7 +420,7 @@ public class PlotAPI {
* @param p * @param p
* @return plot bottom location * @return plot bottom location
*/ */
public Location getHomeLocation(Plot p) { public Location getHomeLocation(final Plot p) {
return PlotHelper.getPlotHome(p.getWorld(), p.id); return PlotHelper.getPlotHome(p.getWorld(), p.id);
} }
@ -410,8 +430,8 @@ public class PlotAPI {
* @param p * @param p
* @return plot bottom location * @return plot bottom location
*/ */
public Location getBottomLocation(Plot p) { public Location getBottomLocation(final Plot p) {
World world = Bukkit.getWorld(p.world); final World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotBottomLoc(world, p.id); return PlotHelper.getPlotBottomLoc(world, p.id);
} }
@ -421,8 +441,8 @@ public class PlotAPI {
* @param p * @param p
* @return plot top location * @return plot top location
*/ */
public Location getTopLocation(Plot p) { public Location getTopLocation(final Plot p) {
World world = Bukkit.getWorld(p.world); final World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotTopLoc(world, p.id); return PlotHelper.getPlotTopLoc(world, p.id);
} }
@ -432,7 +452,7 @@ public class PlotAPI {
* @param player * @param player
* @return true if the player is in a plot, false if not- * @return true if the player is in a plot, false if not-
*/ */
public boolean isInPlot(Player player) { public boolean isInPlot(final Player player) {
return PlayerFunctions.isInPlot(player); return PlayerFunctions.isInPlot(player);
} }
@ -441,7 +461,7 @@ public class PlotAPI {
* *
* @param c * @param c
*/ */
public void registerCommand(SubCommand c) { public void registerCommand(final SubCommand c) {
MainCommand.subCommands.add(c); MainCommand.subCommands.add(c);
} }
@ -460,7 +480,7 @@ public class PlotAPI {
* @param player * @param player
* @return * @return
*/ */
public int getPlayerPlotCount(World world, Player player) { public int getPlayerPlotCount(final World world, final Player player) {
return PlayerFunctions.getPlayerPlotCount(world, player); return PlayerFunctions.getPlayerPlotCount(world, player);
} }
@ -470,7 +490,7 @@ public class PlotAPI {
* @param player * @param player
* @return a set containing the players plots * @return a set containing the players plots
*/ */
public Set<Plot> getPlayerPlots(World world, Player player) { public Set<Plot> getPlayerPlots(final World world, final Player player) {
return PlayerFunctions.getPlayerPlots(world, player); return PlayerFunctions.getPlayerPlots(world, player);
} }
@ -480,7 +500,7 @@ public class PlotAPI {
* @param player * @param player
* @return the number of allowed plots * @return the number of allowed plots
*/ */
public int getAllowedPlots(Player player) { public int getAllowedPlots(final Player player) {
return PlayerFunctions.getAllowedPlots(player); return PlayerFunctions.getAllowedPlots(player);
} }
} }

View File

@ -28,11 +28,11 @@ public class Auto extends SubCommand {
super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING, true); super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING, true);
} }
public static PlotId lastPlot = new PlotId(0,0); public static PlotId lastPlot = new PlotId(0, 0);
// TODO auto claim a mega plot with schematic // TODO auto claim a mega plot with schematic
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
World world; World world;
int size_x = 1; int size_x = 1;
int size_z = 1; int size_z = 1;
@ -52,7 +52,7 @@ public class Auto extends SubCommand {
if (args.length > 0) { if (args.length > 0) {
if (PlotMain.hasPermission(plr, "plots.auto.mega")) { if (PlotMain.hasPermission(plr, "plots.auto.mega")) {
try { try {
String[] split = args[0].split(","); final String[] split = args[0].split(",");
size_x = Integer.parseInt(split[0]); size_x = Integer.parseInt(split[0]);
size_z = Integer.parseInt(split[1]); size_z = Integer.parseInt(split[1]);
if ((size_x < 1) || (size_z < 1)) { if ((size_x < 1) || (size_z < 1)) {
@ -65,7 +65,7 @@ public class Auto extends SubCommand {
schematic = args[1]; schematic = args[1];
} }
} }
catch (Exception e) { catch (final Exception e) {
schematic = args[0]; schematic = args[0];
// PlayerFunctions.sendMessage(plr, // PlayerFunctions.sendMessage(plr,
// "&cError: Invalid size (X,Y)"); // "&cError: Invalid size (X,Y)");
@ -82,12 +82,12 @@ public class Auto extends SubCommand {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return false; return false;
} }
PlotWorld pWorld = PlotMain.getWorldSettings(world); final PlotWorld pWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
double cost = pWorld.PLOT_PRICE; double cost = pWorld.PLOT_PRICE;
cost = (size_x * size_z) * cost; cost = (size_x * size_z) * cost;
if (cost > 0d) { if (cost > 0d) {
Economy economy = PlotMain.economy; final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) { if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
return true; return true;
@ -102,7 +102,7 @@ public class Auto extends SubCommand {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true; return true;
} }
if (!PlotMain.hasPermission(plr,"plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { if (!PlotMain.hasPermission(plr, "plots.claim." + schematic) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true; return true;
} }
@ -112,13 +112,13 @@ public class Auto extends SubCommand {
if ((size_x == 1) && (size_z == 1)) { if ((size_x == 1) && (size_z == 1)) {
while (!br) { while (!br) {
Plot plot = PlotHelper.getPlot(world, Auto.lastPlot); Plot plot = PlotHelper.getPlot(world, Auto.lastPlot);
if (plot==null || plot.owner == null) { if ((plot == null) || (plot.owner == null)) {
plot = PlotHelper.getPlot(world, Auto.lastPlot); plot = PlotHelper.getPlot(world, Auto.lastPlot);
Claim.claimPlot(plr, plot, true); Claim.claimPlot(plr, plot, true);
br = true; br = true;
PlotWorld pw = PlotMain.getWorldSettings(world); final PlotWorld pw = PlotMain.getWorldSettings(world);
Plot plot2 = PlotMain.getPlots(world).get(plot.id); final Plot plot2 = PlotMain.getPlots(world).get(plot.id);
if (pw.DEFAULT_FLAGS != null && pw.DEFAULT_FLAGS.size() > 0) { if ((pw.DEFAULT_FLAGS != null) && (pw.DEFAULT_FLAGS.size() > 0)) {
plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS)); plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS));
} }
} }
@ -126,24 +126,24 @@ public class Auto extends SubCommand {
} }
} }
else { else {
boolean claimed = true; final boolean claimed = true;
while (!br) { while (!br) {
PlotId start = getNextPlot(Auto.lastPlot, 1); final PlotId start = getNextPlot(Auto.lastPlot, 1);
//FIXME: Wtf is going on here? // FIXME: Wtf is going on here?
if (claimed) { if (claimed) {
if (PlotMain.getPlots(world).get(start) == null || PlotMain.getPlots(world).get(start).owner == null) { if ((PlotMain.getPlots(world).get(start) == null) || (PlotMain.getPlots(world).get(start).owner == null)) {
Auto.lastPlot = start; Auto.lastPlot = start;
continue; continue;
} }
} }
PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1); final PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1);
if (isUnowned(world, start, end)) { if (isUnowned(world, start, end)) {
for (int i = start.x; i <= end.x; i++) { for (int i = start.x; i <= end.x; i++) {
for (int j = start.y; j <= end.y; j++) { for (int j = start.y; j <= end.y; j++) {
Plot plot = PlotHelper.getPlot(world, new PlotId(i, j)); final Plot plot = PlotHelper.getPlot(world, new PlotId(i, j));
boolean teleport = ((i == end.x) && (j == end.y)); final boolean teleport = ((i == end.x) && (j == end.y));
Claim.claimPlot(plr, plot, teleport); Claim.claimPlot(plr, plot, teleport);
} }
} }
@ -151,9 +151,9 @@ public class Auto extends SubCommand {
return false; return false;
} }
br = true; br = true;
PlotWorld pw = PlotMain.getWorldSettings(world); final PlotWorld pw = PlotMain.getWorldSettings(world);
Plot plot2 = PlotMain.getPlots(world).get(start); final Plot plot2 = PlotMain.getPlots(world).get(start);
if (pw.DEFAULT_FLAGS != null && pw.DEFAULT_FLAGS.size() > 0) { if ((pw.DEFAULT_FLAGS != null) && (pw.DEFAULT_FLAGS.size() > 0)) {
plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS)); plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS));
} }
} }
@ -162,9 +162,9 @@ public class Auto extends SubCommand {
return true; return true;
} }
public static PlotId getNextPlot(PlotId id, int step) { public static PlotId getNextPlot(final PlotId id, final int step) {
int absX = Math.abs(id.x); final int absX = Math.abs(id.x);
int absY = Math.abs(id.y); final int absY = Math.abs(id.y);
if (absX > absY) { if (absX > absY) {
if (id.x > 0) { if (id.x > 0) {
return new PlotId(id.x, id.y + 1); 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); return new PlotId(id.x, id.y - 1);
} }
} }
else if (absY > absX ){ else if (absY > absX) {
if (id.y > 0) { if (id.y > 0) {
return new PlotId(id.x - 1, id.y); return new PlotId(id.x - 1, id.y);
} }
@ -182,10 +182,10 @@ public class Auto extends SubCommand {
} }
} }
else { 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); return new PlotId(id.x, id.y + step);
} }
if (id.x==absX) { if (id.x == absX) {
return new PlotId(id.x, id.y + 1); return new PlotId(id.x, id.y + 1);
} }
if (id.y == absY) { if (id.y == absY) {
@ -195,11 +195,10 @@ public class Auto extends SubCommand {
} }
} }
public boolean isUnowned(final World world, final PlotId pos1, final PlotId pos2) {
public boolean isUnowned(World world, PlotId pos1, PlotId pos2) {
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.y; y <= pos2.y; y++) {
PlotId id = new PlotId(x, y); final PlotId id = new PlotId(x, y);
if (PlotMain.getPlots(world).get(id) != null) { if (PlotMain.getPlots(world).get(id) != null) {
if (PlotMain.getPlots(world).get(id).owner != null) { if (PlotMain.getPlots(world).get(id).owner != null) {
return false; return false;

View File

@ -8,13 +8,22 @@
package com.intellectualcrafters.plot.commands; 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 net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; 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 * @author Citymonstret
*/ */
@ -25,7 +34,7 @@ public class Claim extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
String schematic = ""; String schematic = "";
if (args.length >= 1) { if (args.length >= 1) {
schematic = args[0]; schematic = args[0];
@ -38,16 +47,16 @@ public class Claim extends SubCommand {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (plot.hasOwner()) { if (plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED);
return false; return false;
} }
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); final PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && world.USE_ECONOMY) { if (PlotMain.useEconomy && world.USE_ECONOMY) {
double cost = world.PLOT_PRICE; final double cost = world.PLOT_PRICE;
if (cost > 0d) { if (cost > 0d) {
Economy economy = PlotMain.economy; final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) { if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
return true; return true;
@ -62,13 +71,13 @@ public class Claim extends SubCommand {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true; return true;
} }
if (!PlotMain.hasPermission(plr,"plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { if (!PlotMain.hasPermission(plr, "plots.claim." + schematic) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true; return true;
} }
} }
} }
boolean result = claimPlot(plr, plot, false, schematic); final boolean result = claimPlot(plr, plot, false, schematic);
if (result) { if (result) {
PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED); PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED);
return false; return false;
@ -76,12 +85,12 @@ public class Claim extends SubCommand {
return true; return true;
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport) { public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) {
return claimPlot(player, plot, teleport, ""); return claimPlot(player, plot, teleport, "");
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) { public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport, final String schematic) {
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); final PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot); PlotHelper.createPlot(player, plot);
@ -90,9 +99,9 @@ public class Claim extends SubCommand {
if (teleport) { if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot); PlotMain.teleportPlayer(player, player.getLocation(), plot);
} }
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); final PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
Plot plot2 = PlotMain.getPlots(player.getWorld()).get(plot.id); final Plot plot2 = PlotMain.getPlots(player.getWorld()).get(plot.id);
if (world.SCHEMATIC_ON_CLAIM) { if (world.SCHEMATIC_ON_CLAIM) {
SchematicHandler.Schematic sch; SchematicHandler.Schematic sch;
@ -107,12 +116,12 @@ public class Claim extends SubCommand {
} }
SchematicHandler.paste(player.getLocation(), sch, plot2, 0, 0); SchematicHandler.paste(player.getLocation(), sch, plot2, 0, 0);
} }
if (world.DEFAULT_FLAGS != null && world.DEFAULT_FLAGS.size() > 0) { if ((world.DEFAULT_FLAGS != null) && (world.DEFAULT_FLAGS.size() > 0)) {
plot2.settings.setFlags(FlagManager.parseFlags(world.DEFAULT_FLAGS)); plot2.settings.setFlags(FlagManager.parseFlags(world.DEFAULT_FLAGS));
} }
if (world instanceof DefaultPlotWorld) { if (world instanceof DefaultPlotWorld) {
DefaultPlotWorld pW = (DefaultPlotWorld) world; final DefaultPlotWorld pW = (DefaultPlotWorld) world;
if(pW.CLAIMED_WALL_BLOCK != pW.WALL_BLOCK) { if (pW.CLAIMED_WALL_BLOCK != pW.WALL_BLOCK) {
PlotMain.getPlotManager(plot.getWorld()).setWall(plot.getWorld(), world, plot.getId(), pW.CLAIMED_WALL_BLOCK); PlotMain.getPlotManager(plot.getWorld()).setWall(plot.getWorld(), world, plot.getId(), pW.CLAIMED_WALL_BLOCK);
} }
} }

View File

@ -28,18 +28,17 @@ public class Clear extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false; return false;
} }
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }

View File

@ -1,12 +1,14 @@
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotSelection; import com.intellectualcrafters.plot.PlotSelection;
import org.bukkit.entity.Player;
import static com.intellectualcrafters.plot.PlotSelection.currentSelection;
/** /**
* Created by Citymonstret on 2014-10-13. * Created by Citymonstret on 2014-10-13.
*/ */
@ -17,16 +19,16 @@ public class Clipboard extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if(!currentSelection.containsKey(plr.getName())) { if (!currentSelection.containsKey(plr.getName())) {
sendMessage(plr, C.NO_CLIPBOARD); sendMessage(plr, C.NO_CLIPBOARD);
return true; return true;
} }
PlotSelection selection = currentSelection.get(plr.getName()); final PlotSelection selection = currentSelection.get(plr.getName());
PlotId plotId = selection.getPlot().getId(); final PlotId plotId = selection.getPlot().getId();
int width = selection.getWidth(); final int width = selection.getWidth();
int total = selection.getBlocks().length; final int total = selection.getBlocks().length;
String message = C.CLIPBOARD_INFO.s(); String message = C.CLIPBOARD_INFO.s();

View File

@ -131,7 +131,7 @@ public enum Command {
/** /**
* @param command * @param command
*/ */
Command(String command) { Command(final String command) {
this.command = command; this.command = command;
this.alias = command; this.alias = command;
this.permission = new CommandPermission("plots." + command); this.permission = new CommandPermission("plots." + command);
@ -141,7 +141,7 @@ public enum Command {
* @param command * @param command
* @param permission * @param permission
*/ */
Command(String command, CommandPermission permission) { Command(final String command, final CommandPermission permission) {
this.command = command; this.command = command;
this.permission = permission; this.permission = permission;
this.alias = command; this.alias = command;
@ -151,7 +151,7 @@ public enum Command {
* @param command * @param command
* @param alias * @param alias
*/ */
Command(String command, String alias) { Command(final String command, final String alias) {
this.command = command; this.command = command;
this.alias = alias; this.alias = alias;
this.permission = new CommandPermission("plots." + command); this.permission = new CommandPermission("plots." + command);
@ -162,7 +162,7 @@ public enum Command {
* @param alias * @param alias
* @param permission * @param permission
*/ */
Command(String command, String alias, CommandPermission permission) { Command(final String command, final String alias, final CommandPermission permission) {
this.command = command; this.command = command;
this.alias = alias; this.alias = alias;
this.permission = permission; this.permission = permission;

View File

@ -28,7 +28,7 @@ public class CommandPermission {
/** /**
* @param permission * @param permission
*/ */
public CommandPermission(String permission) { public CommandPermission(final String permission) {
this.permission = permission.toLowerCase(); this.permission = permission.toLowerCase();
} }
@ -36,7 +36,7 @@ public class CommandPermission {
* @param player * @param player
* @return * @return
*/ */
public boolean hasPermission(Player player) { public boolean hasPermission(final Player player) {
return PlotMain.hasPermission(player, this.permission) || PlotMain.hasPermission(player, "plots.admin"); return PlotMain.hasPermission(player, this.permission) || PlotMain.hasPermission(player, "plots.admin");
} }
} }

View File

@ -8,14 +8,18 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*; import java.util.Arrays;
import com.intellectualcrafters.plot.database.DBFunc; import java.util.List;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.Arrays; import com.intellectualcrafters.plot.C;
import java.util.List; 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. * Created by Citymonstret on 2014-08-01.
@ -27,33 +31,32 @@ public class Comment extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasOwner()) { if (!plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
List<String> recipients = Arrays.asList(new String[] {"admin", "owner", "helper", "trusted", "everyone" }); final List<String> recipients = Arrays.asList(new String[] { "admin", "owner", "helper", "trusted", "everyone" });
if (args.length==2 && recipients.contains(args[0].toLowerCase())) { if ((args.length == 2) && recipients.contains(args[0].toLowerCase())) {
if (PlotMain.hasPermission(plr, "plots.comment."+args[0].toLowerCase())) { if (PlotMain.hasPermission(plr, "plots.comment." + args[0].toLowerCase())) {
String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); final String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " ");
PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase())); final PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase()));
plot.settings.addComment(comment); plot.settings.addComment(comment);
DBFunc.setComment(plr.getWorld().getName(), plot, comment); DBFunc.setComment(plr.getWorld().getName(), plot, comment);
return true; return true;
} }
else { else {
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment."+args[0].toLowerCase()); PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment." + args[0].toLowerCase());
return false; return false;
} }
} }

View File

@ -8,10 +8,15 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.entity.Player; 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. * Created by Citymonstret on 2014-08-01.
*/ */
@ -22,14 +27,13 @@ public class Copy extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
@ -38,14 +42,15 @@ public class Copy extends SubCommand {
return false; return false;
} }
assert plot != null; 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());
PlotSelection selection = new PlotSelection(size, plr.getWorld(), plot); final PlotSelection selection = new PlotSelection(size, plr.getWorld(), plot);
if(PlotSelection.currentSelection.containsKey(plr.getName())) { if (PlotSelection.currentSelection.containsKey(plr.getName())) {
PlotSelection.currentSelection.remove(plr.getName()); PlotSelection.currentSelection.remove(plr.getName());
} }
PlotSelection.currentSelection.put(plr.getName(), selection); PlotSelection.currentSelection.put(plr.getName(), selection);
sendMessage(plr, C.CLIPBOARD_SET); sendMessage(plr, C.CLIPBOARD_SET);
//section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs, new PlotId(plot.getId().x + 1, plot.getId().y))); // section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs,
// new PlotId(plot.getId().x + 1, plot.getId().y)));
return true; return true;
} }
} }

View File

@ -43,10 +43,10 @@ public class Debug extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
StringBuilder msg = new StringBuilder(); final StringBuilder msg = new StringBuilder();
for (C c : C.values()) { for (final C c : C.values()) {
msg.append(c.s() + "\n"); msg.append(c.s() + "\n");
} }
PlayerFunctions.sendMessage(plr, msg.toString()); PlayerFunctions.sendMessage(plr, msg.toString());
@ -73,8 +73,8 @@ public class Debug extends SubCommand {
* {this->test}|on fail(action(){return FAILED})| * {this->test}|on fail(action(){return FAILED})|
*/ */
{ {
StringBuilder worlds = new StringBuilder(""); final StringBuilder worlds = new StringBuilder("");
for (String world : PlotMain.getPlotWorlds()) { for (final String world : PlotMain.getPlotWorlds()) {
worlds.append(world + " "); worlds.append(world + " ");
} }
information.append(header); information.append(header);
@ -87,8 +87,8 @@ public class Debug extends SubCommand {
information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size())); information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size()));
// information.append(getLine(line, "PlotWorld Size", // information.append(getLine(line, "PlotWorld Size",
// PlotHelper.getWorldFolderSize() + "MB")); // PlotHelper.getWorldFolderSize() + "MB"));
for (String worldname : PlotMain.getPlotWorlds()) { for (final String worldname : PlotMain.getPlotWorlds()) {
World world = Bukkit.getWorld(worldname); final World world = Bukkit.getWorld(worldname);
information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world))); information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world)));
information.append(getLine(line, " - Entities", PlotHelper.getEntities(world))); information.append(getLine(line, " - Entities", PlotHelper.getEntities(world)));
information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world))); information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world)));
@ -111,11 +111,11 @@ public class Debug extends SubCommand {
return true; return true;
} }
private String getSection(String line, String val) { private String getSection(final String line, final String val) {
return line.replaceAll("%val%", val) + "\n"; return line.replaceAll("%val%", val) + "\n";
} }
private String getLine(String line, String var, Object val) { private String getLine(final String line, final String var, final Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n";
} }
} }

View File

@ -11,8 +11,6 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.UUID; import java.util.UUID;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Location; import org.bukkit.Location;
@ -31,7 +29,6 @@ import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotManager; import com.intellectualcrafters.plot.PlotManager;
import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.StringWrapper; import com.intellectualcrafters.plot.StringWrapper;
import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
@ -47,14 +44,14 @@ public class DebugClaimTest extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (plr==null) { if (plr == null) {
if (args.length<3) { 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}"); 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; return false;
} }
World world = Bukkit.getWorld(args[0]); final World world = Bukkit.getWorld(args[0]);
if (world==null || !PlotMain.isPlotWorld(world)) { if ((world == null) || !PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, "&cInvalid plot world!"); PlayerFunctions.sendMessage(plr, "&cInvalid plot world!");
return false; return false;
} }
@ -62,75 +59,75 @@ public class DebugClaimTest extends SubCommand {
PlotId min, max; PlotId min, max;
try { try {
String[] split1 = args[1].split(";"); final String[] split1 = args[1].split(";");
String[] split2 = args[2].split(";"); final String[] split2 = args[2].split(";");
min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1])); min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1]));
max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1])); max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1]));
} }
catch (Exception e) { 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."); 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; 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: &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)"); 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); final PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
ArrayList<Plot> plots = new ArrayList<Plot>(); final ArrayList<Plot> plots = new ArrayList<Plot>();
for (PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) { for (final PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) {
Plot plot = PlotHelper.getPlot(world, id); final Plot plot = PlotHelper.getPlot(world, id);
boolean contains = PlotMain.getPlots(world).containsKey(plot.id); final boolean contains = PlotMain.getPlots(world).containsKey(plot.id);
if (contains) { if (contains) {
PlayerFunctions.sendMessage(plr, " - &cDB Already contains: "+plot.id); PlayerFunctions.sendMessage(plr, " - &cDB Already contains: " + plot.id);
continue; continue;
} }
Location loc = manager.getSignLoc(world, plotworld, plot); final Location loc = manager.getSignLoc(world, plotworld, plot);
Chunk chunk = world.getChunkAt(loc); final Chunk chunk = world.getChunkAt(loc);
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
boolean result = chunk.load(false); final boolean result = chunk.load(false);
if (!result) { if (!result) {
continue; continue;
} }
} }
Block block = world.getBlockAt(loc); final Block block = world.getBlockAt(loc);
if (block!=null) { if (block != null) {
if (block.getState() instanceof Sign) { if (block.getState() instanceof Sign) {
Sign sign = (Sign) block.getState(); final Sign sign = (Sign) block.getState();
if (sign!=null) { if (sign != null) {
String line = sign.getLine(2); String line = sign.getLine(2);
if (line!=null && line.length() > 2) { if ((line != null) && (line.length() > 2)) {
line = line.substring(2); line = line.substring(2);
BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap(); final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = (map.get(new StringWrapper(line))); UUID uuid = (map.get(new StringWrapper(line)));
if (uuid==null) { if (uuid == null) {
for (StringWrapper string : map.keySet()) { for (final StringWrapper string : map.keySet()) {
if (string.value.toLowerCase().startsWith(line.toLowerCase())) { if (string.value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = map.get(string); uuid = map.get(string);
break; break;
} }
} }
} }
if (uuid==null) { if (uuid == null) {
uuid = UUIDHandler.getUUID(line); uuid = UUIDHandler.getUUID(line);
} }
if (uuid!=null) { if (uuid != null) {
PlayerFunctions.sendMessage(plr, " - &aFound plot: "+plot.id+" : "+line); PlayerFunctions.sendMessage(plr, " - &aFound plot: " + plot.id + " : " + line);
plot.owner = uuid; plot.owner = uuid;
plot.hasChanged = true; plot.hasChanged = true;
plots.add(plot); plots.add(plot);
} }
else { else {
PlayerFunctions.sendMessage(plr, " - &cInvalid playername: "+plot.id+" : "+line); PlayerFunctions.sendMessage(plr, " - &cInvalid playername: " + plot.id + " : " + line);
} }
} }
} }
@ -138,12 +135,12 @@ public class DebugClaimTest extends SubCommand {
} }
} }
if (plots.size()>0) { if (plots.size() > 0) {
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '"+plots.size()+"' plots!"); PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlots(plots); DBFunc.createPlots(plots);
DBFunc.createAllSettingsAndHelpers(plots); DBFunc.createAllSettingsAndHelpers(plots);
for (Plot plot : plots) { for (final Plot plot : plots) {
PlotMain.updatePlot(plot); PlotMain.updatePlot(plot);
} }
@ -161,12 +158,12 @@ public class DebugClaimTest extends SubCommand {
return true; return true;
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport) { public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) {
return claimPlot(player, plot, teleport, ""); return claimPlot(player, plot, teleport, "");
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) { public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport, final String schematic) {
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); final PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot); PlotHelper.createPlot(player, plot);

View File

@ -9,36 +9,12 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.lang.reflect.Field; 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 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.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.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.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
import com.worldcretornica.plotme.PlayerList;
/** /**
* @author Citymonstret * @author Citymonstret
@ -50,14 +26,14 @@ public class DebugLoadTest extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (plr==null) { if (plr == null) {
try { try {
Field fPlots = PlotMain.class.getDeclaredField("plots"); final Field fPlots = PlotMain.class.getDeclaredField("plots");
fPlots.setAccessible(true); fPlots.setAccessible(true);
fPlots.set(null, DBFunc.getPlots()); fPlots.set(null, DBFunc.getPlots());
} }
catch (Exception e) { catch (final Exception e) {
PlotMain.sendConsoleSenderMessage("&3===FAILED&3==="); PlotMain.sendConsoleSenderMessage("&3===FAILED&3===");
e.printStackTrace(); e.printStackTrace();
PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE==="); PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE===");

View File

@ -9,34 +9,13 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; 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 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.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain; 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.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
/** /**
* @author Citymonstret * @author Citymonstret
@ -48,9 +27,9 @@ public class DebugSaveTest extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (plr==null) { if (plr == null) {
ArrayList<Plot> plots = new ArrayList<Plot>(); final ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotMain.getPlots()); plots.addAll(PlotMain.getPlots());
DBFunc.createPlots(plots); DBFunc.createPlots(plots);
DBFunc.createAllSettingsAndHelpers(plots); DBFunc.createAllSettingsAndHelpers(plots);

View File

@ -15,7 +15,6 @@ import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
@ -30,35 +29,34 @@ public class Delete extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false; return false;
} }
if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))) if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))) && !PlotMain.hasPermission(plr, "plots.admin")) {
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); final PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
double c = pWorld.SELL_PRICE; final double c = pWorld.SELL_PRICE;
if (c > 0d) { if (c > 0d) {
Economy economy = PlotMain.economy; final Economy economy = PlotMain.economy;
economy.depositPlayer(plr, c); economy.depositPlayer(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + ""); sendMessage(plr, C.ADDED_BALANCE, c + "");
} }
} }
boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true); final boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true);
if (result) { if (result) {
plot.clear(plr); plot.clear(plr);
DBFunc.delete(plr.getWorld().getName(), plot); 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)) { 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; Auto.lastPlot = plot.id;
} }
} }

View File

@ -31,7 +31,7 @@ public class Denied extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
return true; return true;
@ -40,7 +40,7 @@ public class Denied extends SubCommand {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot.owner == null) || !plot.hasRights(plr)) { if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return true; return true;
@ -69,7 +69,7 @@ public class Denied extends SubCommand {
} }
plot.addDenied(uuid); plot.addDenied(uuid);
DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); 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); Bukkit.getPluginManager().callEvent(event);
} }
else { else {
@ -77,8 +77,8 @@ public class Denied extends SubCommand {
return false; return false;
} }
if (!uuid.equals(DBFunc.everyone) && (Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) { if (!uuid.equals(DBFunc.everyone) && (Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) {
Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid))); final Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid)));
if (pl!=null && pl.id.equals(plot.id)) { if ((pl != null) && pl.id.equals(plot.id)) {
PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED); PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED);
Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation()); Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation());
} }
@ -86,10 +86,9 @@ public class Denied extends SubCommand {
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
return true; return true;
} }
else else if (args[0].equalsIgnoreCase("remove")) {
if (args[0].equalsIgnoreCase("remove")) {
if (args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone; final UUID uuid = DBFunc.everyone;
if (!plot.denied.contains(uuid)) { if (!plot.denied.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true; return true;
@ -111,10 +110,10 @@ public class Denied extends SubCommand {
* true; } if (uuid == null) { PlayerFunctions.sendMessage(plr, * true; } if (uuid == null) { PlayerFunctions.sendMessage(plr,
* C.PLAYER_HAS_NOT_BEEN_ON); return true; } * C.PLAYER_HAS_NOT_BEEN_ON); return true; }
*/ */
UUID uuid = UUIDHandler.getUUID(args[1]); final UUID uuid = UUIDHandler.getUUID(args[1]);
plot.removeDenied(uuid); plot.removeDenied(uuid);
DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false); final PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
} }

View File

@ -19,7 +19,7 @@ public class Help extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
return false; return false;
} }
} }

View File

@ -28,7 +28,7 @@ public class Helpers extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true; return true;
@ -37,7 +37,7 @@ public class Helpers extends SubCommand {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot.owner == null) || !plot.hasRights(plr)) { if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return true; return true;
@ -65,7 +65,7 @@ public class Helpers extends SubCommand {
} }
plot.addHelper(uuid); plot.addHelper(uuid);
DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); 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); Bukkit.getPluginManager().callEvent(event);
} }
else { else {
@ -75,10 +75,9 @@ public class Helpers extends SubCommand {
PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); PlayerFunctions.sendMessage(plr, C.HELPER_ADDED);
return true; return true;
} }
else else if (args[0].equalsIgnoreCase("remove")) {
if (args[0].equalsIgnoreCase("remove")) {
if (args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone; final UUID uuid = DBFunc.everyone;
if (!plot.helpers.contains(uuid)) { if (!plot.helpers.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true; return true;
@ -101,10 +100,10 @@ public class Helpers extends SubCommand {
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* true; } * true; }
*/ */
UUID uuid = UUIDHandler.getUUID(args[1]); final UUID uuid = UUIDHandler.getUUID(args[1]);
plot.removeHelper(uuid); plot.removeHelper(uuid);
DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false); final PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
} }

View File

@ -24,8 +24,8 @@ public class Home extends SubCommand {
super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT, true); super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT, true);
} }
private Plot isAlias(String a) { private Plot isAlias(final String a) {
for (Plot p : PlotMain.getPlots()) { for (final Plot p : PlotMain.getPlots()) {
if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p; return p;
} }
@ -34,14 +34,13 @@ public class Home extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, String... args) {
Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); final Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]);
if (plots.length == 1) { if (plots.length == 1) {
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]); PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]);
return true; return true;
} }
else else if (plots.length > 1) {
if (plots.length > 1) {
if (args.length < 1) { if (args.length < 1) {
args = new String[] { "1" }; args = new String[] { "1" };
} }
@ -49,7 +48,7 @@ public class Home extends SubCommand {
try { try {
id = Integer.parseInt(args[0]); id = Integer.parseInt(args[0]);
} }
catch (Exception e) { catch (final Exception e) {
Plot temp; Plot temp;
if ((temp = isAlias(args[0])) != null) { if ((temp = isAlias(args[0])) != null) {
if (temp.hasOwner()) { if (temp.hasOwner()) {

View File

@ -13,13 +13,16 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.UUID; 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.Bukkit;
import org.bukkit.entity.Player; 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. * Created by Citymonstret on 2014-08-01.
*/ */
@ -42,7 +45,7 @@ public class Inbox extends SubCommand {
} }
Integer tier = null; Integer tier = null;
UUID uuid = plr.getUniqueId(); final UUID uuid = plr.getUniqueId();
if (PlotMain.hasPermission(plr, "plots.admin")) { if (PlotMain.hasPermission(plr, "plots.admin")) {
tier = 0; tier = 0;
} }
@ -62,7 +65,7 @@ public class Inbox extends SubCommand {
if (args.length > 0) { if (args.length > 0) {
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "admin": case "admin":
if (tier<=0) { if (tier <= 0) {
tier = 0; tier = 0;
} }
else { else {
@ -71,7 +74,7 @@ public class Inbox extends SubCommand {
} }
break; break;
case "owner": case "owner":
if (tier<=1) { if (tier <= 1) {
tier = 1; tier = 1;
} }
else { else {
@ -80,7 +83,7 @@ public class Inbox extends SubCommand {
} }
break; break;
case "helper": case "helper":
if (tier<=2) { if (tier <= 2) {
tier = 2; tier = 2;
} }
else { else {
@ -89,7 +92,7 @@ public class Inbox extends SubCommand {
} }
break; break;
case "trusted": case "trusted":
if (tier<=3) { if (tier <= 3) {
tier = 3; tier = 3;
} }
else { else {
@ -98,7 +101,7 @@ public class Inbox extends SubCommand {
} }
break; break;
case "everyone": case "everyone":
if (tier<=4) { if (tier <= 4) {
tier = 4; tier = 4;
} }
else { else {
@ -107,7 +110,7 @@ public class Inbox extends SubCommand {
} }
break; break;
case "default": case "default":
PlayerFunctions.sendMessage(plr, C.INVALID_INBOX, Arrays.copyOfRange(new String[] {"admin", "owner", "helper", "trusted", "everyone" }, tier, 4)); PlayerFunctions.sendMessage(plr, C.INVALID_INBOX, Arrays.copyOfRange(new String[] { "admin", "owner", "helper", "trusted", "everyone" }, tier, 4));
return false; return false;
} }
} }
@ -125,41 +128,41 @@ public class Inbox extends SubCommand {
} }
if (args.length == 2) { if (args.length == 2) {
String[] split = args[1].toLowerCase().split(":"); final String[] split = args[1].toLowerCase().split(":");
if (!split[0].equals("clear")) { if (!split[0].equals("clear")) {
PlayerFunctions.sendMessage(plr, "&c/plot inbox [tier] [clear][:#]"); PlayerFunctions.sendMessage(plr, "&c/plot inbox [tier] [clear][:#]");
return; return;
} }
if (split.length > 1) { if (split.length > 1) {
try { try {
int index = Integer.parseInt(split[1]); final int index = Integer.parseInt(split[1]);
PlotComment comment = comments.get(index-1); final PlotComment comment = comments.get(index - 1);
DBFunc.removeComment(world, plot, comment); DBFunc.removeComment(world, plot, comment);
PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "1 comment"); PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "1 comment");
return; return;
} }
catch (Exception e) { catch (final Exception e) {
PlayerFunctions.sendMessage(plr, "&cInvalid index:\n/plot inbox [tier] [clear][:#]"); PlayerFunctions.sendMessage(plr, "&cInvalid index:\n/plot inbox [tier] [clear][:#]");
return; return;
} }
} }
for (PlotComment comment : comments) { for (final PlotComment comment : comments) {
DBFunc.removeComment(world, plot, comment); DBFunc.removeComment(world, plot, comment);
} }
PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "all comments in that category"); PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "all comments in that category");
return; return;
} }
else { else {
final List<String> recipients = Arrays.asList(new String[] {"A", "O", "H", "T", "E" }); final List<String> recipients = Arrays.asList(new String[] { "A", "O", "H", "T", "E" });
int count = 1; int count = 1;
StringBuilder message = new StringBuilder(); final StringBuilder message = new StringBuilder();
String prefix = ""; String prefix = "";
for (PlotComment comment : comments) { for (final PlotComment comment : comments) {
message.append(prefix + "["+count+"]&6[&c" + recipients.get(tier2) + "&6] &7"+comment.senderName+"&f: "+comment.comment); message.append(prefix + "[" + count + "]&6[&c" + recipients.get(tier2) + "&6] &7" + comment.senderName + "&f: " + comment.comment);
prefix = "\n"; prefix = "\n";
count++; count++;
} }
if (comments.size()==0) { if (comments.size() == 0) {
message.append("&cNo messages."); message.append("&cNo messages.");
} }
PlayerFunctions.sendMessage(plr, message.toString()); PlayerFunctions.sendMessage(plr, message.toString());

View File

@ -8,19 +8,25 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*; import java.util.ArrayList;
import com.intellectualcrafters.plot.database.DBFunc; import java.util.UUID;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import com.intellectualcrafters.plot.C;
import java.util.UUID; 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 * @author Citymonstret
@ -32,10 +38,10 @@ public class Info extends SubCommand {
} }
@Override @Override
public boolean execute(Player player, String... args) { public boolean execute(final Player player, String... args) {
World world; World world;
Plot plot; Plot plot;
if (player!=null) { if (player != null) {
world = player.getWorld(); world = player.getWorld();
if (!PlayerFunctions.isInPlot(player)) { if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
@ -44,38 +50,38 @@ public class Info extends SubCommand {
plot = PlayerFunctions.getCurrentPlot(player); plot = PlayerFunctions.getCurrentPlot(player);
} }
else { else {
if (args.length<2) { if (args.length < 2) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE); PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false; return false;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(args[0]); final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld==null) { if (plotworld == null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD); PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD);
return false; return false;
} }
try { try {
String[] split = args[1].split(";"); final String[] split = args[1].split(";");
PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id); plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id);
if (plot==null) { if (plot == null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID); PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID);
return false; return false;
} }
world = Bukkit.getWorld(args[0]); world = Bukkit.getWorld(args[0]);
if (args.length==3) { if (args.length == 3) {
args = new String[] {args[2]}; args = new String[] { args[2] };
} }
else { else {
args = new String[0]; args = new String[0];
} }
} }
catch (Exception e) { catch (final Exception e) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE); PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false; return false;
} }
} }
boolean hasOwner = plot.hasOwner(); final boolean hasOwner = plot.hasOwner();
boolean containsEveryone; boolean containsEveryone;
boolean trustedEveryone; boolean trustedEveryone;
@ -110,9 +116,9 @@ public class Info extends SubCommand {
} }
String info = C.PLOT_INFO.s(); String info = C.PLOT_INFO.s();
if (args.length==1) { if (args.length == 1) {
info = getCaption(args[0].toLowerCase()); info = getCaption(args[0].toLowerCase());
if (info==null) { 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"); 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; return false;
} }
@ -124,7 +130,7 @@ public class Info extends SubCommand {
return true; return true;
} }
private String getCaption(String string) { private String getCaption(final String string) {
switch (string) { switch (string) {
case "helpers": case "helpers":
return C.PLOT_INFO_HELPERS.s(); return C.PLOT_INFO_HELPERS.s();
@ -151,19 +157,19 @@ public class Info extends SubCommand {
} }
} }
private String format(String info, World world, Plot plot, Player player) { private String format(String info, final World world, final Plot plot, final Player player) {
PlotId id = plot.id; final PlotId id = plot.id;
PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id; final PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id;
int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size(); final int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size();
String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none"; final String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none";
String biome = getBiomeAt(plot).toString(); final String biome = getBiomeAt(plot).toString();
String helpers = getPlayerList(plot.helpers); final String helpers = getPlayerList(plot.helpers);
String trusted = getPlayerList(plot.trusted); final String trusted = getPlayerList(plot.trusted);
String denied = getPlayerList(plot.denied); final String denied = getPlayerList(plot.denied);
String rating = String.format("%.1f", DBFunc.getRatings(plot)); final 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"); final 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); final boolean build = player == null ? true : plot.hasRights(player);
String owner = "none"; String owner = "none";
if (plot.owner != null) { if (plot.owner != null) {
@ -176,7 +182,7 @@ public class Info extends SubCommand {
info = info.replaceAll("%alias%", alias); info = info.replaceAll("%alias%", alias);
info = info.replaceAll("%id%", id.toString()); info = info.replaceAll("%id%", id.toString());
info = info.replaceAll("%id2%", id2.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("%biome%", biome);
info = info.replaceAll("%owner%", owner); info = info.replaceAll("%owner%", owner);
info = info.replaceAll("%helpers%", helpers); info = info.replaceAll("%helpers%", helpers);
@ -184,19 +190,18 @@ public class Info extends SubCommand {
info = info.replaceAll("%denied%", denied); info = info.replaceAll("%denied%", denied);
info = info.replaceAll("%rating%", rating); info = info.replaceAll("%rating%", rating);
info = info.replaceAll("%flags%", flags); info = info.replaceAll("%flags%", flags);
info = info.replaceAll("%build%", build+""); info = info.replaceAll("%build%", build + "");
info = info.replaceAll("%desc%", "No description set."); info = info.replaceAll("%desc%", "No description set.");
return info; return info;
} }
private String getPlayerList(ArrayList<UUID> l) { private String getPlayerList(final ArrayList<UUID> l) {
if ((l == null) || (l.size() < 1)) { if ((l == null) || (l.size() < 1)) {
return " none"; return " none";
} }
String c = C.PLOT_USER_LIST.s(); final String c = C.PLOT_USER_LIST.s();
StringBuilder list = new StringBuilder(); final StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) { for (int x = 0; x < l.size(); x++) {
if ((x + 1) == l.size()) { if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", ""));
@ -208,7 +213,7 @@ public class Info extends SubCommand {
return list.toString(); return list.toString();
} }
private String getPlayerName(UUID uuid) { private String getPlayerName(final UUID uuid) {
if (uuid == null) { if (uuid == null) {
return "unknown"; return "unknown";
} }
@ -222,9 +227,9 @@ public class Info extends SubCommand {
return UUIDHandler.getName(uuid); return UUIDHandler.getName(uuid);
} }
private Biome getBiomeAt(Plot plot) { private Biome getBiomeAt(final Plot plot) {
World w = Bukkit.getWorld(plot.world); final World w = Bukkit.getWorld(plot.world);
Location bl = PlotHelper.getPlotTopLoc(w, plot.id); final Location bl = PlotHelper.getPlotTopLoc(w, plot.id);
return bl.getBlock().getBiome(); return bl.getBlock().getBiome();
} }
} }

View File

@ -24,16 +24,16 @@ public class Inventory extends SubCommand {
} }
@Override @Override
public boolean execute(final Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
ArrayList<SubCommand> cmds = new ArrayList<>(); final ArrayList<SubCommand> cmds = new ArrayList<>();
for (SubCommand cmd : MainCommand.subCommands) { for (final SubCommand cmd : MainCommand.subCommands) {
if (cmd.permission.hasPermission(plr)) { if (cmd.permission.hasPermission(plr)) {
cmds.add(cmd); cmds.add(cmd);
} }
} }
int size = 9 * (int) Math.ceil(cmds.size() / 9.0); final int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); final org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands");
for (SubCommand cmd : cmds) { for (final SubCommand cmd : cmds) {
inventory.addItem(getItem(cmd)); inventory.addItem(getItem(cmd));
} }
plr.openInventory(inventory); plr.openInventory(inventory);
@ -41,11 +41,10 @@ public class Inventory extends SubCommand {
} }
private ItemStack getItem(final SubCommand cmd) { private ItemStack getItem(final SubCommand cmd) {
ItemStack stack = new ItemStack(Material.COMMAND); final ItemStack stack = new ItemStack(Material.COMMAND);
ItemMeta meta = stack.getItemMeta(); final ItemMeta meta = stack.getItemMeta();
{ {
meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]");
+ ChatColor.DARK_GRAY + "]");
meta.setLore(new ArrayList<String>() { meta.setLore(new ArrayList<String>() {
{ {
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString()); add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString());

View File

@ -26,14 +26,13 @@ public class Kick extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
@ -45,10 +44,8 @@ public class Kick extends SubCommand {
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
return false; return false;
} }
Player player = Bukkit.getPlayer(args[0]); final Player player = Bukkit.getPlayer(args[0]);
if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) || (PlayerFunctions.getCurrentPlot(player) == null) || !PlayerFunctions.getCurrentPlot(player).equals(plot)) {
|| (PlayerFunctions.getCurrentPlot(player) == null)
|| !PlayerFunctions.getCurrentPlot(player).equals(plot)) {
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
return false; return false;
} }

View File

@ -8,10 +8,9 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.C; import java.util.ArrayList;
import com.intellectualcrafters.plot.PlayerFunctions; import java.util.Arrays;
import com.intellectualcrafters.plot.PlotMain; import java.util.List;
import com.intellectualcrafters.plot.StringComparsion;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -21,9 +20,10 @@ import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.ChatPaginator; import org.bukkit.util.ChatPaginator;
import java.util.ArrayList; import com.intellectualcrafters.plot.C;
import java.util.Arrays; import com.intellectualcrafters.plot.PlayerFunctions;
import java.util.List; import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.StringComparsion;
/** /**
* PlotMain command class * PlotMain command class
@ -32,10 +32,7 @@ import java.util.List;
*/ */
public class MainCommand implements CommandExecutor, TabCompleter { 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(), 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() };
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<SubCommand> subCommands = new ArrayList<SubCommand>() { public static ArrayList<SubCommand> subCommands = new ArrayList<SubCommand>() {
{ {
@ -43,73 +40,77 @@ public class MainCommand implements CommandExecutor, TabCompleter {
} }
}; };
public static boolean no_permission(Player player, String permission) { public static boolean no_permission(final Player player, final String permission) {
PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission); PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission);
return false; return false;
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) {
Player player = (sender instanceof Player) ? (Player) sender : null; final Player player = (sender instanceof Player) ? (Player) sender : null;
if (!PlotMain.hasPermission(player, "plots.use")) if (!PlotMain.hasPermission(player, "plots.use")) {
return no_permission(player, "plots.use"); return no_permission(player, "plots.use");
}
if ((args.length < 1) if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
|| ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
if (args.length < 2) { if (args.length < 2) {
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s()); builder.append(C.HELP_INFO.s());
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { 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())); builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
} }
PlayerFunctions.sendMessage(player, builder.toString()); PlayerFunctions.sendMessage(player, builder.toString());
return true; return true;
} }
String cat = args[1]; final String cat = args[1];
SubCommand.CommandCategory cato = null; SubCommand.CommandCategory cato = null;
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
if (cat.equalsIgnoreCase(category.toString())) { if (cat.equalsIgnoreCase(category.toString())) {
cato = category; cato = category;
break; break;
} }
} }
if (cato == null) { if (cato == null) {
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s()); builder.append(C.HELP_INFO.s());
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { 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())); builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
} }
PlayerFunctions.sendMessage(player, builder.toString()); PlayerFunctions.sendMessage(player, builder.toString());
return true; return true;
} }
StringBuilder help = new StringBuilder(); final StringBuilder help = new StringBuilder();
int page = 0; int page = 0;
boolean digit = true; boolean digit = true;
for(char c : args[2].toCharArray()) for (final char c : args[2].toCharArray()) {
if(!Character.isDigit(c)) { if (!Character.isDigit(c)) {
digit = false; digit = false;
break; break;
} }
if(digit) { }
if (digit) {
page = Integer.parseInt(args[2]); 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"); help.append(string).append("\n");
}
PlayerFunctions.sendMessage(player, help.toString()); PlayerFunctions.sendMessage(player, help.toString());
return true; return true;
} }
else { else {
for (SubCommand command : subCommands) { for (final SubCommand command : subCommands) {
if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) { if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) {
String[] arguments = new String[args.length - 1]; final String[] arguments = new String[args.length - 1];
System.arraycopy(args, 1, arguments, 0, args.length - 1); System.arraycopy(args, 1, arguments, 0, args.length - 1);
if (command.permission.hasPermission(player)) { if (command.permission.hasPermission(player)) {
if (player!=null || !command.isPlayer ) { if ((player != null) || !command.isPlayer) {
return command.execute(player, arguments); return command.execute(player, arguments);
} }
else { else {
@ -124,81 +125,77 @@ public class MainCommand implements CommandExecutor, TabCompleter {
} }
PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND);
String[] commands = new String[subCommands.size()]; final String[] commands = new String[subCommands.size()];
for(int x = 0; x < subCommands.size(); x++) for (int x = 0; x < subCommands.size(); x++) {
commands[x] = subCommands.get(x).cmd; commands[x] = subCommands.get(x).cmd;
}
PlayerFunctions.sendMessage(player, C.DID_YOU_MEAN, new StringComparsion(args[0], commands).getBestMatch()); PlayerFunctions.sendMessage(player, C.DID_YOU_MEAN, new StringComparsion(args[0], commands).getBestMatch());
} }
return false; return false;
} }
public static List<SubCommand> getCommands(final SubCommand.CommandCategory category, final Player player) {
public static List<SubCommand> getCommands(SubCommand.CommandCategory category, Player player) { final List<SubCommand> cmds = new ArrayList<>();
List<SubCommand> cmds = new ArrayList<>(); for (final SubCommand c : subCommands) {
for(SubCommand c : subCommands) if ((c.category == category) && c.permission.hasPermission(player)) {
if(c.category == category && c.permission.hasPermission(player))
cmds.add(c); cmds.add(c);
}
}
return cmds; return cmds;
} }
/* /*
// Current page * // Current page
int page = 0; * int page = 0;
* //is a page specified? else use 0
//is a page specified? else use 0 * if(args.length > 1) {
if(args.length > 1) { * try {
try { * page = Integer.parseInt(args[1]);
page = Integer.parseInt(args[1]); * } catch(Exception e) {
} catch(Exception e) { * page = 0;
page = 0; * }
} * }
} * //Get the total pages
* int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size())
//Get the total pages * / 100));
int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size()) / 100)); * if(page > totalPages)
* page = totalPages;
if(page > totalPages) * //Only display 12!
page = totalPages; * int max = (page * 12) + 12;
* if(max > PlotMain.getPlotsSorted().size())
//Only display 12! * max = PlotMain.getPlotsSorted().size();
int max = (page * 12) + 12; * StringBuilder string = new StringBuilder();
* string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 +
if(max > PlotMain.getPlotsSorted().size()) * "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") +
max = PlotMain.getPlotsSorted().size(); * "\n");
* Plot p;
StringBuilder string = new StringBuilder(); * //This might work xD
* for (int x = (page * 12); x < max; x++) {
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<String> helpMenu(Player player, final SubCommand.CommandCategory category, int page) { public static ArrayList<String> helpMenu(final Player player, final SubCommand.CommandCategory category, int page) {
List<SubCommand> commands = getCommands(category, player); final List<SubCommand> commands = getCommands(category, player);
//final int totalPages = ((int) Math.ceil(12 * (commands.size()) / 100)); // final int totalPages = ((int) Math.ceil(12 * (commands.size()) /
int perPage = 5; // 100));
int totalPages = (int) Math.ceil(commands.size() / perPage); final int perPage = 5;
if(page > totalPages) final int totalPages = (int) Math.ceil(commands.size() / perPage);
if (page > totalPages) {
page = totalPages; page = totalPages;
}
int max = (page * perPage) + perPage; int max = (page * perPage) + perPage;
if(max > commands.size()) if (max > commands.size()) {
max = commands.size(); max = commands.size();
ArrayList<String> help = new ArrayList<>( }
Arrays.asList( final ArrayList<String> 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()))));
t(C.HELP_HEADER.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "")),
t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString()))
));
SubCommand cmd; SubCommand cmd;
String lines = ""; 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 += "-"; lines += "-";
} }
int start = page * perPage; final int start = page * perPage;
for(int x = start; x < max; x++) { for (int x = start; x < max; x++) {
cmd = subCommands.get(x); cmd = subCommands.get(x);
String s = t(C.HELP_PAGE.s()); String s = t(C.HELP_PAGE.s());
s = s.replaceAll("%alias%", cmd.alias); s = s.replaceAll("%alias%", cmd.alias);
@ -208,7 +205,7 @@ public class MainCommand implements CommandExecutor, TabCompleter {
help.add(s); 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))); help.add(t(C.HELP_ITEM_SEPARATOR.s().replaceAll("%lines", lines)));
} }
@ -219,18 +216,20 @@ public class MainCommand implements CommandExecutor, TabCompleter {
return help; return help;
} }
private static String t(String s) { private static String t(final String s) {
return ChatColor.translateAlternateColorCodes('&', s); return ChatColor.translateAlternateColorCodes('&', s);
} }
@Override @Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) { public List<String> onTabComplete(final CommandSender commandSender, final Command command, final String s, final String[] strings) {
if(!(commandSender instanceof Player)) return null; if (!(commandSender instanceof Player)) {
Player player = (Player) commandSender; return null;
}
final Player player = (Player) commandSender;
if(strings.length < 1) { if (strings.length < 1) {
if (strings.length==0 || "plots".startsWith(s)) { if ((strings.length == 0) || "plots".startsWith(s)) {
return Arrays.asList(new String[] {"plots"}); return Arrays.asList(new String[] { "plots" });
} }
} }
if (strings.length > 1) { if (strings.length > 1) {
@ -239,9 +238,9 @@ public class MainCommand implements CommandExecutor, TabCompleter {
if (!command.getLabel().equalsIgnoreCase("plots")) { if (!command.getLabel().equalsIgnoreCase("plots")) {
return null; return null;
} }
List<String> tabOptions = new ArrayList<String>(); final List<String> tabOptions = new ArrayList<String>();
String arg = strings[0].toLowerCase(); final String arg = strings[0].toLowerCase();
for (SubCommand cmd : subCommands) { for (final SubCommand cmd : subCommands) {
if (cmd.permission.hasPermission(player)) { if (cmd.permission.hasPermission(player)) {
if (cmd.cmd.startsWith(arg)) { if (cmd.cmd.startsWith(arg)) {
tabOptions.add(cmd.cmd); 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 tabOptions;
} }
return null; return null;

View File

@ -41,7 +41,7 @@ public class Merge extends SubCommand {
public static String direction(float yaw) { public static String direction(float yaw) {
yaw = yaw / 90; yaw = yaw / 90;
int i = Math.round(yaw); final int i = Math.round(yaw);
switch (i) { switch (i) {
case -4: case -4:
case 0: case 0:
@ -62,12 +62,12 @@ public class Merge extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot == null) || !plot.hasOwner()) { if ((plot == null) || !plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
@ -77,8 +77,7 @@ public class Merge extends SubCommand {
return false; return false;
} }
if (args.length < 1) { if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
+ StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
return false; return false;
} }
@ -90,49 +89,44 @@ public class Merge extends SubCommand {
} }
} }
if (direction == -1) { if (direction == -1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
+ StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
return false; return false;
} }
World world = plr.getWorld(); final World world = plr.getWorld();
PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; final PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id;
PlotId top = PlayerFunctions.getTopPlot(world, plot).id; final PlotId top = PlayerFunctions.getTopPlot(world, plot).id;
ArrayList<PlotId> plots; ArrayList<PlotId> plots;
switch (direction) { switch (direction) {
case 0: // north = -y case 0: // north = -y
plots = plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
break; break;
case 1: // east = +x case 1: // east = +x
plots = plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
break; break;
case 2: // south = +y case 2: // south = +y
plots = plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
break; break;
case 3: // west = -x case 3: // west = -x
plots = plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
break; break;
default: default:
return false; return false;
} }
for (PlotId myid : plots) { for (final PlotId myid : plots) {
Plot myplot = PlotMain.getPlots(world).get(myid); final Plot myplot = PlotMain.getPlots(world).get(myid);
if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) { if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) {
PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false; return false;
} }
} }
PlotWorld plotWorld = PlotMain.getWorldSettings(world); final PlotWorld plotWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) { if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE; double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost; cost = plots.size() * cost;
if (cost > 0d) { if (cost > 0d) {
Economy economy = PlotMain.economy; final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) { if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
return false; return false;
@ -142,7 +136,7 @@ public class Merge extends SubCommand {
} }
} }
PlotMergeEvent event = new PlotMergeEvent(world, plot, plots); final PlotMergeEvent event = new PlotMergeEvent(world, plot, plots);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {

View File

@ -1,35 +1,38 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.C; import java.util.Arrays;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.listeners.PlotPlusListener;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; 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 class MusicSubcommand extends SubCommand {
public MusicSubcommand() { public MusicSubcommand() {
super("music", "plots.music", "Play music in plot", "music", "mus", CommandCategory.ACTIONS, true); super("music", "plots.music", "Play music in plot", "music", "mus", CommandCategory.ACTIONS, true);
} }
@Override @Override
public boolean execute(Player player, String... args) { public boolean execute(final Player player, final String... args) {
if(!PlayerFunctions.isInPlot(player)) { if (!PlayerFunctions.isInPlot(player)) {
sendMessage(player, C.NOT_IN_PLOT); sendMessage(player, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(player); final Plot plot = PlayerFunctions.getCurrentPlot(player);
if(!plot.hasRights(player)) { if (!plot.hasRights(player)) {
sendMessage(player, C.NO_PLOT_PERMS); sendMessage(player, C.NO_PLOT_PERMS);
return true; return true;
} }
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.RED + "Plot Jukebox"); final org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.RED + "Plot Jukebox");
for(PlotPlusListener.RecordMeta meta : PlotPlusListener.RecordMeta.metaList) { for (final PlotPlusListener.RecordMeta meta : PlotPlusListener.RecordMeta.metaList) {
ItemStack stack = new ItemStack(meta.getMaterial()); final ItemStack stack = new ItemStack(meta.getMaterial());
ItemMeta itemMeta = stack.getItemMeta(); final ItemMeta itemMeta = stack.getItemMeta();
itemMeta.setDisplayName(ChatColor.GOLD + meta.toString()); itemMeta.setDisplayName(ChatColor.GOLD + meta.toString());
itemMeta.setLore(Arrays.asList(ChatColor.GRAY + "Click to play the record")); itemMeta.setLore(Arrays.asList(ChatColor.GRAY + "Click to play the record"));
stack.setItemMeta(itemMeta); stack.setItemMeta(itemMeta);

View File

@ -1,9 +1,14 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.entity.Player; 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. * Created by Citymonstret on 2014-10-12.
*/ */
@ -14,14 +19,13 @@ public class Paste extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
@ -30,17 +34,18 @@ public class Paste extends SubCommand {
return false; return false;
} }
assert plot != null; 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())) { if (PlotSelection.currentSelection.containsKey(plr.getName())) {
PlotSelection selection = PlotSelection.currentSelection.get(plr.getName()); final PlotSelection selection = PlotSelection.currentSelection.get(plr.getName());
if(size != selection.getWidth()) { if (size != selection.getWidth()) {
sendMessage(plr, C.PASTE_FAILED, "The size of the current plot is not the same as the paste"); sendMessage(plr, C.PASTE_FAILED, "The size of the current plot is not the same as the paste");
return false; return false;
} }
selection.paste(plr.getWorld(), plot); selection.paste(plr.getWorld(), plot);
sendMessage(plr, C.PASTED); sendMessage(plr, C.PASTED);
} else { }
else {
sendMessage(plr, C.NO_CLIPBOARD); sendMessage(plr, C.NO_CLIPBOARD);
return false; return false;
} }

View File

@ -27,17 +27,17 @@ public class Purge extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
if (args.length!=2) { if (args.length != 2) {
if (args.length==1) { if (args.length == 1) {
try { try {
String[] split = args[0].split(";"); final String[] split = args[0].split(";");
String world = split[0]; final String world = split[0];
PlotId id = new PlotId(Integer.parseInt(split[1]), Integer.parseInt(split[2])); final PlotId id = new PlotId(Integer.parseInt(split[1]), Integer.parseInt(split[2]));
System.out.print("VALID ID"); System.out.print("VALID ID");
if (plr!=null) { if (plr != null) {
PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE)); PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE));
return false; return false;
} }
@ -48,10 +48,10 @@ public class Purge extends SubCommand {
} }
PlotMain.getPlots(world).remove(id); PlotMain.getPlots(world).remove(id);
DBFunc.purge(world, id); DBFunc.purge(world, id);
PlayerFunctions.sendMessage(plr, "&aPurge of '"+args[0]+"' was successful!"); PlayerFunctions.sendMessage(plr, "&aPurge of '" + args[0] + "' was successful!");
return true; return true;
} }
catch (Exception e) { catch (final Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID);
} }
} }
@ -59,12 +59,12 @@ public class Purge extends SubCommand {
return false; return false;
} }
if (args[1].equals("-o")) { if (args[1].equals("-o")) {
PlotWorld plotworld = PlotMain.getWorldSettings(args[0]); final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld == null) { if (plotworld == null) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false; return false;
} }
if (plr!=null) { if (plr != null) {
PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE)); PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE));
return false; return false;
} }

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